diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000..99c1513407 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,37 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Fly Casual Release Version** +Which version did the bug occur in (use version from Main Menu, please do not say Latest or similar)? + +**Online Game Mode** +Yes/No + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Platform/Device (be as specific as possible):** + - OS: [e.g. Windows, Mac, Android] + - Version [e.g. Windows 10, iOS22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000..bbcbbe7d61 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.gitignore b/.gitignore index e1f1ae4c9e..99b3556f26 100644 --- a/.gitignore +++ b/.gitignore @@ -55,6 +55,8 @@ obj Temp MAC.app Logs +**/TextMesh Pro/ +**/TextMesh Pro.meta # Visual Studio 2015 cache directory /.vs/ @@ -81,3 +83,5 @@ ExportedObj/ /.collabignore /UserSettings +Assets/Editor/ +Assets/Editor.meta diff --git a/Assets/Animations/Gauntlet.meta b/Assets/Animations/Gauntlet.meta new file mode 100644 index 0000000000..23b0b5d9b0 --- /dev/null +++ b/Assets/Animations/Gauntlet.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5a64d8b14b151aa47ada2923dd77c716 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Animations/Gauntlet/WingPivot_Close.anim b/Assets/Animations/Gauntlet/WingPivot_Close.anim new file mode 100644 index 0000000000..b5f18be83c Binary files /dev/null and b/Assets/Animations/Gauntlet/WingPivot_Close.anim differ diff --git a/Assets/Animations/Gauntlet/WingPivot_Close.anim.meta b/Assets/Animations/Gauntlet/WingPivot_Close.anim.meta new file mode 100644 index 0000000000..6da12cc3fe --- /dev/null +++ b/Assets/Animations/Gauntlet/WingPivot_Close.anim.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e501d4013c360f641930c637ee49b4c4 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 7400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Animations/Gauntlet/WingPivot_Open.anim b/Assets/Animations/Gauntlet/WingPivot_Open.anim new file mode 100644 index 0000000000..4869001a05 Binary files /dev/null and b/Assets/Animations/Gauntlet/WingPivot_Open.anim differ diff --git a/Assets/Animations/Gauntlet/WingPivot_Open.anim.meta b/Assets/Animations/Gauntlet/WingPivot_Open.anim.meta new file mode 100644 index 0000000000..2648f8a49e --- /dev/null +++ b/Assets/Animations/Gauntlet/WingPivot_Open.anim.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a499f88b09385ba44a89cd364dbbcd8e +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 7400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Fonts/Rebellion SDF.asset b/Assets/Fonts/Rebellion SDF.asset new file mode 100644 index 0000000000..47d5915dd4 Binary files /dev/null and b/Assets/Fonts/Rebellion SDF.asset differ diff --git a/Assets/Fonts/Rebellion SDF.asset.meta b/Assets/Fonts/Rebellion SDF.asset.meta new file mode 100644 index 0000000000..ae2dc65c1b --- /dev/null +++ b/Assets/Fonts/Rebellion SDF.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2c26324329a4f044c887548b06a18a9b +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Authenticators/BasicAuthenticator.cs b/Assets/ImportedAssets/Mirror/Authenticators/BasicAuthenticator.cs index 1f0a4ca773..3c077c79cf 100644 --- a/Assets/ImportedAssets/Mirror/Authenticators/BasicAuthenticator.cs +++ b/Assets/ImportedAssets/Mirror/Authenticators/BasicAuthenticator.cs @@ -1,20 +1,26 @@ using System.Collections; +using System.Collections.Generic; using UnityEngine; namespace Mirror.Authenticators { - [AddComponentMenu("Network/Authenticators/BasicAuthenticator")] + [AddComponentMenu("Network/ Authenticators/Basic Authenticator")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-authenticators/basic-authenticator")] public class BasicAuthenticator : NetworkAuthenticator { - static readonly ILogger logger = LogFactory.GetLogger(typeof(BasicAuthenticator)); + [Header("Server Credentials")] + public string serverUsername; + public string serverPassword; - [Header("Custom Properties")] - - // set these in the inspector + [Header("Client Credentials")] public string username; public string password; - public class AuthRequestMessage : MessageBase + readonly HashSet connectionsPendingDisconnect = new HashSet(); + + #region Messages + + public struct AuthRequestMessage : NetworkMessage { // use whatever credentials make sense for your game // for example, you might want to pass the accessToken if using oauth @@ -22,46 +28,58 @@ public class AuthRequestMessage : MessageBase public string authPassword; } - public class AuthResponseMessage : MessageBase + public struct AuthResponseMessage : NetworkMessage { public byte code; public string message; } + #endregion + + #region Server + + /// + /// Called on server from StartServer to initialize the Authenticator + /// Server message handlers should be registered in this method. + /// public override void OnStartServer() { // register a handler for the authentication request we expect from client NetworkServer.RegisterHandler(OnAuthRequestMessage, false); } - public override void OnStartClient() + /// + /// Called on server from StopServer to reset the Authenticator + /// Server message handlers should be unregistered in this method. + /// + public override void OnStopServer() { - // register a handler for the authentication response we expect from server - NetworkClient.RegisterHandler(OnAuthResponseMessage, false); + // unregister the handler for the authentication request + NetworkServer.UnregisterHandler(); } - public override void OnServerAuthenticate(NetworkConnection conn) + /// + /// Called on server from OnServerConnectInternal when a client needs to authenticate + /// + /// Connection to client. + public override void OnServerAuthenticate(NetworkConnectionToClient conn) { // do nothing...wait for AuthRequestMessage from client } - public override void OnClientAuthenticate(NetworkConnection conn) + /// + /// Called on server when the client's AuthRequestMessage arrives + /// + /// Connection to client. + /// The message payload + public void OnAuthRequestMessage(NetworkConnectionToClient conn, AuthRequestMessage msg) { - AuthRequestMessage authRequestMessage = new AuthRequestMessage - { - authUsername = username, - authPassword = password - }; - - conn.Send(authRequestMessage); - } + //Debug.Log($"Authentication Request: {msg.authUsername} {msg.authPassword}"); - public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg) - { - if (logger.LogEnabled()) logger.LogFormat(LogType.Log, "Authentication Request: {0} {1}", msg.authUsername, msg.authPassword); + if (connectionsPendingDisconnect.Contains(conn)) return; // check the credentials by calling your web server, database table, playfab api, or any method appropriate. - if (msg.authUsername == username && msg.authPassword == password) + if (msg.authUsername == serverUsername && msg.authPassword == serverPassword) { // create and send msg to client so it knows to proceed AuthResponseMessage authResponseMessage = new AuthResponseMessage @@ -72,11 +90,13 @@ public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg) conn.Send(authResponseMessage); - // Invoke the event to complete a successful authentication - OnServerAuthenticated.Invoke(conn); + // Accept the successful authentication + ServerAccept(conn); } else { + connectionsPendingDisconnect.Add(conn); + // create and send msg to client so it knows to disconnect AuthResponseMessage authResponseMessage = new AuthResponseMessage { @@ -90,35 +110,83 @@ public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg) conn.isAuthenticated = false; // disconnect the client after 1 second so that response message gets delivered - StartCoroutine(DelayedDisconnect(conn, 1)); + StartCoroutine(DelayedDisconnect(conn, 1f)); } } - public IEnumerator DelayedDisconnect(NetworkConnection conn, float waitTime) + IEnumerator DelayedDisconnect(NetworkConnectionToClient conn, float waitTime) { yield return new WaitForSeconds(waitTime); - conn.Disconnect(); + + // Reject the unsuccessful authentication + ServerReject(conn); + + yield return null; + + // remove conn from pending connections + connectionsPendingDisconnect.Remove(conn); } - public void OnAuthResponseMessage(NetworkConnection conn, AuthResponseMessage msg) + #endregion + + #region Client + + /// + /// Called on client from StartClient to initialize the Authenticator + /// Client message handlers should be registered in this method. + /// + public override void OnStartClient() + { + // register a handler for the authentication response we expect from server + NetworkClient.RegisterHandler(OnAuthResponseMessage, false); + } + + /// + /// Called on client from StopClient to reset the Authenticator + /// Client message handlers should be unregistered in this method. + /// + public override void OnStopClient() + { + // unregister the handler for the authentication response + NetworkClient.UnregisterHandler(); + } + + /// + /// Called on client from OnClientConnectInternal when a client needs to authenticate + /// + public override void OnClientAuthenticate() + { + AuthRequestMessage authRequestMessage = new AuthRequestMessage + { + authUsername = username, + authPassword = password + }; + + NetworkClient.Send(authRequestMessage); + } + + /// + /// Called on client when the server's AuthResponseMessage arrives + /// + /// The message payload + public void OnAuthResponseMessage(AuthResponseMessage msg) { if (msg.code == 100) { - if (logger.LogEnabled()) logger.LogFormat(LogType.Log, "Authentication Response: {0}", msg.message); + //Debug.Log($"Authentication Response: {msg.message}"); - // Invoke the event to complete a successful authentication - OnClientAuthenticated.Invoke(conn); + // Authentication has been accepted + ClientAccept(); } else { - logger.LogFormat(LogType.Error, "Authentication Response: {0}", msg.message); + Debug.LogError($"Authentication Response: {msg.message}"); - // Set this on the client for local reference - conn.isAuthenticated = false; - - // disconnect the client - conn.Disconnect(); + // Authentication has been rejected + ClientReject(); } } + + #endregion } } diff --git a/Assets/ImportedAssets/Mirror/Authenticators/BasicAuthenticator.cs.meta b/Assets/ImportedAssets/Mirror/Authenticators/BasicAuthenticator.cs.meta index 47650136fe..17c7a5f3ef 100644 --- a/Assets/ImportedAssets/Mirror/Authenticators/BasicAuthenticator.cs.meta +++ b/Assets/ImportedAssets/Mirror/Authenticators/BasicAuthenticator.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Authenticators/BasicAuthenticator.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Authenticators/DeviceAuthenticator.cs b/Assets/ImportedAssets/Mirror/Authenticators/DeviceAuthenticator.cs new file mode 100644 index 0000000000..5e0ea5628e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Authenticators/DeviceAuthenticator.cs @@ -0,0 +1,129 @@ +using System; +using UnityEngine; + +namespace Mirror.Authenticators +{ + /// + /// An authenticator that identifies the user by their device. + /// A GUID is used as a fallback when the platform doesn't support SystemInfo.deviceUniqueIdentifier. + /// Note: deviceUniqueIdentifier can be spoofed, so security is not guaranteed. + /// See https://docs.unity3d.com/ScriptReference/SystemInfo-deviceUniqueIdentifier.html for details. + /// + [AddComponentMenu("Network/ Authenticators/Device Authenticator")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-authenticators/device-authenticator")] + public class DeviceAuthenticator : NetworkAuthenticator + { + #region Messages + + public struct AuthRequestMessage : NetworkMessage + { + public string clientDeviceID; + } + + public struct AuthResponseMessage : NetworkMessage { } + + #endregion + + #region Server + + /// + /// Called on server from StartServer to initialize the Authenticator + /// Server message handlers should be registered in this method. + /// + public override void OnStartServer() + { + // register a handler for the authentication request we expect from client + NetworkServer.RegisterHandler(OnAuthRequestMessage, false); + } + + /// + /// Called on server from StopServer to reset the Authenticator + /// Server message handlers should be registered in this method. + /// + public override void OnStopServer() + { + // unregister the handler for the authentication request + NetworkServer.UnregisterHandler(); + } + + /// + /// Called on server from OnServerConnectInternal when a client needs to authenticate + /// + /// Connection to client. + public override void OnServerAuthenticate(NetworkConnectionToClient conn) + { + // do nothing, wait for client to send his id + } + + void OnAuthRequestMessage(NetworkConnectionToClient conn, AuthRequestMessage msg) + { + Debug.Log($"connection {conn.connectionId} authenticated with id {msg.clientDeviceID}"); + + // Store the device id for later reference, e.g. when spawning the player + conn.authenticationData = msg.clientDeviceID; + + // Send a response to client telling it to proceed as authenticated + conn.Send(new AuthResponseMessage()); + + // Accept the successful authentication + ServerAccept(conn); + } + + #endregion + + #region Client + + /// + /// Called on client from StartClient to initialize the Authenticator + /// Client message handlers should be registered in this method. + /// + public override void OnStartClient() + { + // register a handler for the authentication response we expect from server + NetworkClient.RegisterHandler(OnAuthResponseMessage, false); + } + + /// + /// Called on client from StopClient to reset the Authenticator + /// Client message handlers should be unregistered in this method. + /// + public override void OnStopClient() + { + // unregister the handler for the authentication response + NetworkClient.UnregisterHandler(); + } + + /// + /// Called on client from OnClientConnectInternal when a client needs to authenticate + /// + public override void OnClientAuthenticate() + { + string deviceUniqueIdentifier = SystemInfo.deviceUniqueIdentifier; + + // Not all platforms support this, so we use a GUID instead + if (deviceUniqueIdentifier == SystemInfo.unsupportedIdentifier) + { + // Get the value from PlayerPrefs if it exists, new GUID if it doesn't + deviceUniqueIdentifier = PlayerPrefs.GetString("deviceUniqueIdentifier", Guid.NewGuid().ToString()); + + // Store the deviceUniqueIdentifier to PlayerPrefs (in case we just made a new GUID) + PlayerPrefs.SetString("deviceUniqueIdentifier", deviceUniqueIdentifier); + } + + // send the deviceUniqueIdentifier to the server + NetworkClient.Send(new AuthRequestMessage { clientDeviceID = deviceUniqueIdentifier } ); + } + + /// + /// Called on client when the server's AuthResponseMessage arrives + /// + /// The message payload + public void OnAuthResponseMessage(AuthResponseMessage msg) + { + Debug.Log("Authentication Success"); + ClientAccept(); + } + + #endregion + } +} diff --git a/Assets/ImportedAssets/Mirror/Authenticators/DeviceAuthenticator.cs.meta b/Assets/ImportedAssets/Mirror/Authenticators/DeviceAuthenticator.cs.meta new file mode 100644 index 0000000000..d40da34aed --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Authenticators/DeviceAuthenticator.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 60960a6ba81a842deb2fdcdc93788242 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Authenticators/DeviceAuthenticator.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Authenticators/Mirror.Authenticators.asmdef b/Assets/ImportedAssets/Mirror/Authenticators/Mirror.Authenticators.asmdef index 16cdfbc2fd..70eacf3eed 100644 --- a/Assets/ImportedAssets/Mirror/Authenticators/Mirror.Authenticators.asmdef +++ b/Assets/ImportedAssets/Mirror/Authenticators/Mirror.Authenticators.asmdef @@ -1,14 +1,16 @@ { "name": "Mirror.Authenticators", + "rootNamespace": "", "references": [ - "Mirror" + "GUID:30817c1a0e6d646d99c048fc403f5979" ], - "optionalUnityReferences": [], "includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": false, "overrideReferences": false, "precompiledReferences": [], "autoReferenced": true, - "defineConstraints": [] + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Authenticators/Mirror.Authenticators.asmdef.meta b/Assets/ImportedAssets/Mirror/Authenticators/Mirror.Authenticators.asmdef.meta index 273170109b..d6188917b0 100644 --- a/Assets/ImportedAssets/Mirror/Authenticators/Mirror.Authenticators.asmdef.meta +++ b/Assets/ImportedAssets/Mirror/Authenticators/Mirror.Authenticators.asmdef.meta @@ -5,3 +5,10 @@ AssemblyDefinitionImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Authenticators/Mirror.Authenticators.asmdef + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Authenticators/TimeoutAuthenticator.cs b/Assets/ImportedAssets/Mirror/Authenticators/TimeoutAuthenticator.cs index 4fa580bda6..711ee6e375 100644 --- a/Assets/ImportedAssets/Mirror/Authenticators/TimeoutAuthenticator.cs +++ b/Assets/ImportedAssets/Mirror/Authenticators/TimeoutAuthenticator.cs @@ -7,11 +7,9 @@ namespace Mirror.Authenticators /// An authenticator that disconnects connections if they don't /// authenticate within a specified time limit. /// - [AddComponentMenu("Network/Authenticators/TimeoutAuthenticator")] + [AddComponentMenu("Network/ Authenticators/Timeout Authenticator")] public class TimeoutAuthenticator : NetworkAuthenticator { - static readonly ILogger logger = LogFactory.GetLogger(typeof(TimeoutAuthenticator)); - public NetworkAuthenticator authenticator; [Range(0, 600), Tooltip("Timeout to auto-disconnect in seconds. Set to 0 for no timeout.")] @@ -19,8 +17,18 @@ public class TimeoutAuthenticator : NetworkAuthenticator public void Awake() { - authenticator.OnClientAuthenticated.AddListener(connection => OnClientAuthenticated.Invoke(connection)); authenticator.OnServerAuthenticated.AddListener(connection => OnServerAuthenticated.Invoke(connection)); + authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated.Invoke); + } + + public override void OnStartServer() + { + authenticator.OnStartServer(); + } + + public override void OnStopServer() + { + authenticator.OnStopServer(); } public override void OnStartClient() @@ -28,35 +36,33 @@ public override void OnStartClient() authenticator.OnStartClient(); } - public override void OnStartServer() + public override void OnStopClient() { - authenticator.OnStartServer(); + authenticator.OnStopClient(); } - public override void OnClientAuthenticate(NetworkConnection conn) + public override void OnServerAuthenticate(NetworkConnectionToClient conn) { - authenticator.OnClientAuthenticate(conn); + authenticator.OnServerAuthenticate(conn); if (timeout > 0) StartCoroutine(BeginAuthentication(conn)); } - public override void OnServerAuthenticate(NetworkConnection conn) + public override void OnClientAuthenticate() { - authenticator.OnServerAuthenticate(conn); + authenticator.OnClientAuthenticate(); if (timeout > 0) - StartCoroutine(BeginAuthentication(conn)); + StartCoroutine(BeginAuthentication(NetworkClient.connection)); } IEnumerator BeginAuthentication(NetworkConnection conn) { - if (logger.LogEnabled()) logger.Log($"Authentication countdown started {conn} {timeout}"); - + //Debug.Log($"Authentication countdown started {conn} {timeout}"); yield return new WaitForSecondsRealtime(timeout); if (!conn.isAuthenticated) { - if (logger.LogEnabled()) logger.Log($"Authentication Timeout {conn}"); - + Debug.LogError($"Authentication Timeout - Disconnecting {conn}"); conn.Disconnect(); } } diff --git a/Assets/ImportedAssets/Mirror/Authenticators/TimeoutAuthenticator.cs.meta b/Assets/ImportedAssets/Mirror/Authenticators/TimeoutAuthenticator.cs.meta index b19ddec124..7f0365972f 100644 --- a/Assets/ImportedAssets/Mirror/Authenticators/TimeoutAuthenticator.cs.meta +++ b/Assets/ImportedAssets/Mirror/Authenticators/TimeoutAuthenticator.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Authenticators/TimeoutAuthenticator.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Cloud/ApiConnector.cs b/Assets/ImportedAssets/Mirror/Cloud/ApiConnector.cs deleted file mode 100644 index fb6713f6ca..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/ApiConnector.cs +++ /dev/null @@ -1,61 +0,0 @@ -using Mirror.Cloud.ListServerService; -using UnityEngine; - -namespace Mirror.Cloud -{ - /// - /// Used to requests and responses from the mirror api - /// - public interface IApiConnector - { - ListServer ListServer { get; } - } - - /// - /// Used to requests and responses from the mirror api - /// - [DisallowMultipleComponent] - [AddComponentMenu("Network/CloudServices/ApiConnector")] - [HelpURL("https://mirror-networking.com/docs/CloudServices/ApiConnector.html")] - public class ApiConnector : MonoBehaviour, IApiConnector, ICoroutineRunner - { - #region Inspector - [Header("Settings")] - - [Tooltip("Base URL of api, including https")] - [SerializeField] string ApiAddress = ""; - - [Tooltip("Api key required to access api")] - [SerializeField] string ApiKey = ""; - - [Header("Events")] - - [Tooltip("Triggered when server list updates")] - [SerializeField] ServerListEvent _onServerListUpdated = new ServerListEvent(); - #endregion - - IRequestCreator requestCreator; - - public ListServer ListServer { get; private set; } - - void Awake() - { - requestCreator = new RequestCreator(ApiAddress, ApiKey, this); - - InitListServer(); - } - - void InitListServer() - { - IListServerServerApi serverApi = new ListServerServerApi(this, requestCreator); - IListServerClientApi clientApi = new ListServerClientApi(this, requestCreator, _onServerListUpdated); - ListServer = new ListServer(serverApi, clientApi); - } - - public void OnDestroy() - { - ListServer.ServerApi.Shutdown(); - ListServer.ClientApi.Shutdown(); - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core.meta b/Assets/ImportedAssets/Mirror/Cloud/Core.meta deleted file mode 100644 index 8c000591a1..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 3f34c32971e65984c93a15376ec11c65 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/BaseApi.cs b/Assets/ImportedAssets/Mirror/Cloud/Core/BaseApi.cs deleted file mode 100644 index 720f598159..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core/BaseApi.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Mirror.Cloud -{ - public interface IBaseApi - { - /// - /// Cleans up any data created by the instance - /// For Example: removing server from list - /// - void Shutdown(); - } - - public abstract class BaseApi - { - protected readonly ICoroutineRunner runner; - protected readonly IRequestCreator requestCreator; - - protected BaseApi(ICoroutineRunner runner, IRequestCreator requestCreator) - { - this.runner = runner ?? throw new ArgumentNullException(nameof(runner)); - this.requestCreator = requestCreator ?? throw new ArgumentNullException(nameof(requestCreator)); - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/Events.cs b/Assets/ImportedAssets/Mirror/Cloud/Core/Events.cs deleted file mode 100644 index ffee4d323b..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core/Events.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using Mirror.Cloud.ListServerService; -using UnityEngine.Events; - -namespace Mirror.Cloud -{ - [Serializable] - public class ServerListEvent : UnityEvent { } - - [Serializable] - public class MatchFoundEvent : UnityEvent { } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/Extensions.cs b/Assets/ImportedAssets/Mirror/Cloud/Core/Extensions.cs deleted file mode 100644 index fa7dfa7004..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core/Extensions.cs +++ /dev/null @@ -1,12 +0,0 @@ -using UnityEngine.Networking; - -namespace Mirror.Cloud -{ - public static class Extensions - { - public static bool IsOk(this UnityWebRequest webRequest) - { - return 200 <= webRequest.responseCode && webRequest.responseCode <= 299; - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/ICoroutineRunner.cs b/Assets/ImportedAssets/Mirror/Cloud/Core/ICoroutineRunner.cs deleted file mode 100644 index 7fe3bbf358..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core/ICoroutineRunner.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections; -using UnityEngine; - -namespace Mirror.Cloud -{ - public interface ICoroutineRunner : IUnityEqualCheck - { - Coroutine StartCoroutine(IEnumerator routine); - void StopCoroutine(IEnumerator routine); - void StopCoroutine(Coroutine routine); - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/IRequestCreator.cs b/Assets/ImportedAssets/Mirror/Cloud/Core/IRequestCreator.cs deleted file mode 100644 index 2709707fd0..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core/IRequestCreator.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Collections; -using UnityEngine.Networking; - -namespace Mirror.Cloud -{ - public delegate void RequestSuccess(string responseBody); - - public delegate void RequestFail(string responseBody); - - /// - /// Objects that can be sent to the Api must have this interface - /// - public interface ICanBeJson { } - - /// - /// Methods to create and send UnityWebRequest - /// - public interface IRequestCreator - { - UnityWebRequest Delete(string page); - UnityWebRequest Get(string page); - UnityWebRequest Patch(string page, T json) where T : struct, ICanBeJson; - UnityWebRequest Post(string page, T json) where T : struct, ICanBeJson; - - /// - /// Sends Request to api and invokes callback when finished - /// Starts Coroutine of SendRequestEnumerator - /// - /// - /// - /// - void SendRequest(UnityWebRequest request, RequestSuccess onSuccess = null, RequestFail onFail = null); - /// - /// Sends Request to api and invokes callback when finished - /// - /// - /// - /// - /// - IEnumerator SendRequestEnumerator(UnityWebRequest request, RequestSuccess onSuccess = null, RequestFail onFail = null); - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/IUnityEqualCheck.cs b/Assets/ImportedAssets/Mirror/Cloud/Core/IUnityEqualCheck.cs deleted file mode 100644 index be5e057cbc..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core/IUnityEqualCheck.cs +++ /dev/null @@ -1,26 +0,0 @@ -using UnityEngine; - -namespace Mirror.Cloud -{ - /// - /// Adds Extension to check if unity object is null. - /// Use these methods to stop MissingReferenceException - /// - public interface IUnityEqualCheck - { - - } - - public static class UnityEqualCheckExtension - { - public static bool IsNull(this IUnityEqualCheck obj) - { - return (obj as Object) == null; - } - - public static bool IsNotNull(this IUnityEqualCheck obj) - { - return (obj as Object) != null; - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/JsonStructs.cs b/Assets/ImportedAssets/Mirror/Cloud/Core/JsonStructs.cs deleted file mode 100644 index 7827abcb07..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core/JsonStructs.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace Mirror.Cloud -{ - [Serializable] - public struct CreatedIdJson : ICanBeJson - { - public string id; - } - - [Serializable] - public struct ErrorJson : ICanBeJson - { - public string code; - public string message; - - public int HtmlCode => int.Parse(code); - } - - [Serializable] - public struct EmptyJson : ICanBeJson - { - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/Logger.cs b/Assets/ImportedAssets/Mirror/Cloud/Core/Logger.cs deleted file mode 100644 index 89daca910a..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core/Logger.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using UnityEngine; -using UnityEngine.Networking; - -namespace Mirror.Cloud -{ - public static class Logger - { - public static bool VerboseLogging = false; - static readonly ILogger logger = LogFactory.GetLogger("MirrorCloudServices"); - - public static void LogRequest(string page, string method, bool hasJson, string json) - { - if (hasJson) - { - logger.LogFormat(LogType.Log, "Request: {0} {1} {2}", method, page, json); - } - else - { - logger.LogFormat(LogType.Log, "Request: {0} {1}", method, page); - } - } - - public static void LogResponse(UnityWebRequest statusRequest) - { - long code = statusRequest.responseCode; - LogType logType = statusRequest.IsOk() - ? LogType.Log - : LogType.Error; - - string format = "Response: {0} {1} {2} {3}"; - if (logger.IsLogTypeAllowed(logType)) - { - // we split path like this to make sure api key doesn't leak - Uri uri = new Uri(statusRequest.url); - string path = string.Join("", uri.Segments); - string msg = string.Format(format, statusRequest.method, code, path, statusRequest.downloadHandler.text); - logger.Log(logType, msg); - } - - if (!string.IsNullOrEmpty(statusRequest.error)) - { - string msg = string.Format("WEB REQUEST ERROR: {0}", statusRequest.error); - logger.Log(LogType.Error, msg); - } - } - - internal static void Log(string msg) - { - if (logger.LogEnabled()) - logger.Log(msg); - } - - internal static void LogWarning(string msg) - { - if (logger.WarnEnabled()) - logger.LogWarning(msg); - } - - internal static void LogError(string msg) - { - if (logger.ErrorEnabled()) - logger.LogError(msg); - } - - internal static void Verbose(string msg) - { - if (VerboseLogging && logger.LogEnabled()) - logger.Log(msg); - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/RequestCreator.cs b/Assets/ImportedAssets/Mirror/Cloud/Core/RequestCreator.cs deleted file mode 100644 index 7195c0e709..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Core/RequestCreator.cs +++ /dev/null @@ -1,144 +0,0 @@ -using System; -using System.Collections; -using System.Text; -using UnityEngine; -using UnityEngine.Networking; - -namespace Mirror.Cloud -{ - /// - /// Methods to create and send UnityWebRequest - /// - public class RequestCreator : IRequestCreator - { - const string GET = "GET"; - const string POST = "POST"; - const string PATCH = "PATCH"; - const string DELETE = "DELETE"; - - public readonly string baseAddress; - public readonly string apiKey; - readonly ICoroutineRunner runner; - - public RequestCreator(string baseAddress, string apiKey, ICoroutineRunner coroutineRunner) - { - if (string.IsNullOrEmpty(baseAddress)) - { - throw new ArgumentNullException(nameof(baseAddress)); - } - - if (string.IsNullOrEmpty(apiKey)) - { - throw new ArgumentNullException(nameof(apiKey)); - } - - this.baseAddress = baseAddress; - this.apiKey = apiKey; - - runner = coroutineRunner ?? throw new ArgumentNullException(nameof(coroutineRunner)); - } - - - Uri CreateUri(string page) - { - return new Uri(string.Format("{0}/{1}?key={2}", baseAddress, page, apiKey)); - } - - UnityWebRequest CreateWebRequest(string page, string method, string json = null) - { - bool hasJson = !string.IsNullOrEmpty(json); - Logger.LogRequest(page, method, hasJson, json); - - UnityWebRequest request = new UnityWebRequest(CreateUri(page)); - request.method = method; - if (hasJson) - { - request.SetRequestHeader("Content-Type", "application/json"); - } - - request.downloadHandler = new DownloadHandlerBuffer(); - - byte[] bodyRaw = hasJson - ? Encoding.UTF8.GetBytes(json) - : null; - - request.uploadHandler = new UploadHandlerRaw(bodyRaw); - - return request; - } - - - - /// - /// Create Get Request to page - /// - /// - /// - public UnityWebRequest Get(string page) - { - return CreateWebRequest(page, GET); - } - - /// - /// Creates Post Request to page with Json body - /// - /// - /// - /// - /// - public UnityWebRequest Post(string page, T json) where T : struct, ICanBeJson - { - string jsonString = JsonUtility.ToJson(json); - return CreateWebRequest(page, POST, jsonString); - } - - /// - /// Creates Patch Request to page with Json body - /// - /// - /// - /// - /// - public UnityWebRequest Patch(string page, T json) where T : struct, ICanBeJson - { - string jsonString = JsonUtility.ToJson(json); - return CreateWebRequest(page, PATCH, jsonString); - } - - /// - /// Create Delete Request to page - /// - /// - /// - public UnityWebRequest Delete(string page) - { - return CreateWebRequest(page, DELETE); - } - - - public void SendRequest(UnityWebRequest request, RequestSuccess onSuccess = null, RequestFail onFail = null) - { - runner.StartCoroutine(SendRequestEnumerator(request, onSuccess, onFail)); - } - - public IEnumerator SendRequestEnumerator(UnityWebRequest request, RequestSuccess onSuccess = null, RequestFail onFail = null) - { - using (UnityWebRequest webRequest = request) - { - yield return webRequest.SendWebRequest(); - Logger.LogResponse(webRequest); - - string text = webRequest.downloadHandler.text; - Logger.Verbose(text); - if (webRequest.IsOk()) - { - onSuccess?.Invoke(text); - } - else - { - onFail?.Invoke(text); - } - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer.meta b/Assets/ImportedAssets/Mirror/Cloud/ListServer.meta deleted file mode 100644 index bc85c3d041..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/ListServer.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: c4c4be148a492b143a881cd08bf7e320 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServer.cs b/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServer.cs deleted file mode 100644 index 8b4af8053b..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServer.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using UnityEngine.Events; - -namespace Mirror.Cloud.ListServerService -{ - public sealed class ListServer - { - public readonly IListServerServerApi ServerApi; - public readonly IListServerClientApi ClientApi; - - public ListServer(IListServerServerApi serverApi, IListServerClientApi clientApi) - { - ServerApi = serverApi ?? throw new ArgumentNullException(nameof(serverApi)); - ClientApi = clientApi ?? throw new ArgumentNullException(nameof(clientApi)); - } - } - - public interface IListServerServerApi : IBaseApi - { - /// - /// Has a server been added to the list with this connection - /// - bool ServerInList { get; } - /// - /// Add a server to the list - /// - /// - void AddServer(ServerJson server); - /// - /// Update the current server - /// - /// - void UpdateServer(int newPlayerCount); - /// - /// Update the current server - /// - /// - void UpdateServer(ServerJson server); - /// - /// Removes the current server - /// - void RemoveServer(); - } - - public interface IListServerClientApi : IBaseApi - { - /// - /// Called when the server list is updated - /// - event UnityAction onServerListUpdated; - - /// - /// Get the server list once - /// - void GetServerList(); - /// - /// Start getting the server list every interval - /// - /// - void StartGetServerListRepeat(int interval); - /// - /// Stop getting the server list - /// - void StopGetServerListRepeat(); - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerBaseApi.cs b/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerBaseApi.cs deleted file mode 100644 index 05d2e2e6ba..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerBaseApi.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Mirror.Cloud.ListServerService -{ - public abstract class ListServerBaseApi : BaseApi - { - protected ListServerBaseApi(ICoroutineRunner runner, IRequestCreator requestCreator) : base(runner, requestCreator) - { - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerClientApi.cs b/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerClientApi.cs deleted file mode 100644 index 22867c17aa..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerClientApi.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Collections; -using UnityEngine; -using UnityEngine.Events; -using UnityEngine.Networking; - -namespace Mirror.Cloud.ListServerService -{ - public sealed class ListServerClientApi : ListServerBaseApi, IListServerClientApi - { - readonly ServerListEvent _onServerListUpdated; - - Coroutine getServerListRepeatCoroutine; - - public event UnityAction onServerListUpdated - { - add => _onServerListUpdated.AddListener(value); - remove => _onServerListUpdated.RemoveListener(value); - } - - public ListServerClientApi(ICoroutineRunner runner, IRequestCreator requestCreator, ServerListEvent onServerListUpdated) : base(runner, requestCreator) - { - _onServerListUpdated = onServerListUpdated; - } - - public void Shutdown() - { - StopGetServerListRepeat(); - } - - public void GetServerList() - { - runner.StartCoroutine(getServerList()); - } - - public void StartGetServerListRepeat(int interval) - { - getServerListRepeatCoroutine = runner.StartCoroutine(GetServerListRepeat(interval)); - } - - public void StopGetServerListRepeat() - { - // if runner is null it has been destroyed and will alraedy be null - if (runner.IsNotNull() && getServerListRepeatCoroutine != null) - { - runner.StopCoroutine(getServerListRepeatCoroutine); - } - } - - IEnumerator GetServerListRepeat(int interval) - { - while (true) - { - yield return getServerList(); - - yield return new WaitForSeconds(interval); - } - } - IEnumerator getServerList() - { - UnityWebRequest request = requestCreator.Get("servers"); - yield return requestCreator.SendRequestEnumerator(request, onSuccess); - - void onSuccess(string responseBody) - { - ServerCollectionJson serverlist = JsonUtility.FromJson(responseBody); - _onServerListUpdated?.Invoke(serverlist); - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerJson.cs b/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerJson.cs deleted file mode 100644 index 2591331b90..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerJson.cs +++ /dev/null @@ -1,207 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Mirror.Cloud.ListServerService -{ - [Serializable] - public struct ServerCollectionJson : ICanBeJson - { - public ServerJson[] servers; - } - - [Serializable] - public struct ServerJson : ICanBeJson - { - public string protocol; - public int port; - public int playerCount; - public int maxPlayerCount; - - /// - /// optional - /// - public string displayName; - - /// - /// Uri string of the ip and port of the server. - /// The ip is calculated by the request to the API - /// This is returns from the api, any incoming address fields will be ignored - /// - public string address; - - /// - /// Can be used to set custom uri - /// optional - /// - public string customAddress; - - /// - /// Array of custom data, use SetCustomData to set values - /// optional - /// - public KeyValue[] customData; - - /// - /// Uri from address field - /// - /// - public Uri GetServerUri() => new Uri(address); - - /// - /// Uri from customAddress field - /// - /// - public Uri GetCustomUri() => new Uri(customAddress); - - /// - /// Updates the customData array - /// - /// - public void SetCustomData(Dictionary data) - { - if (data == null) - { - customData = null; - } - else - { - customData = data.ToKeyValueArray(); - CustomDataHelper.ValidateCustomData(customData); - } - } - - public bool Validate() - { - CustomDataHelper.ValidateCustomData(customData); - - if (string.IsNullOrEmpty(protocol)) - { - Logger.LogError("ServerJson should not have empty protocol"); - return false; - } - - if (port == 0) - { - Logger.LogError("ServerJson should not have port equal 0"); - return false; - } - - if (maxPlayerCount == 0) - { - Logger.LogError("ServerJson should not have maxPlayerCount equal 0"); - return false; - } - - return true; - } - } - - [Serializable] - public struct PartialServerJson : ICanBeJson - { - /// - /// optional - /// - public int playerCount; - - /// - /// optional - /// - public int maxPlayerCount; - - /// - /// optional - /// - public string displayName; - - /// - /// Array of custom data, use SetCustomData to set values - /// optional - /// - public KeyValue[] customData; - - - public void SetCustomData(Dictionary data) - { - if (data == null) - { - customData = null; - } - else - { - customData = data.ToKeyValueArray(); - CustomDataHelper.ValidateCustomData(customData); - } - } - - public void Validate() - { - CustomDataHelper.ValidateCustomData(customData); - } - } - - public static class CustomDataHelper - { - const int MaxCustomData = 16; - - public static Dictionary ToDictionary(this KeyValue[] keyValues) - { - return keyValues.ToDictionary(x => x.key, x => x.value); - } - public static KeyValue[] ToKeyValueArray(this Dictionary dictionary) - { - return dictionary.Select(kvp => new KeyValue(kvp.Key, kvp.Value)).ToArray(); - } - - public static void ValidateCustomData(KeyValue[] customData) - { - if (customData == null) - { - return; - } - - if (customData.Length > MaxCustomData) - { - Logger.LogError($"There can only be {MaxCustomData} custom data but there was {customData.Length} values given"); - Array.Resize(ref customData, MaxCustomData); - } - - foreach (KeyValue item in customData) - { - item.Validate(); - } - } - } - - [Serializable] - public struct KeyValue - { - const int MaxKeySize = 32; - const int MaxValueSize = 256; - - public string key; - public string value; - - public KeyValue(string key, string value) - { - this.key = key; - this.value = value; - } - - public void Validate() - { - if (key.Length > MaxKeySize) - { - Logger.LogError($"Custom Data must have key with length less than {MaxKeySize}"); - key = key.Substring(0, MaxKeySize); - } - - if (value.Length > MaxValueSize) - { - Logger.LogError($"Custom Data must have value with length less than {MaxValueSize}"); - value = value.Substring(0, MaxValueSize); - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerServerApi.cs b/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerServerApi.cs deleted file mode 100644 index 3ca4b0d192..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerServerApi.cs +++ /dev/null @@ -1,219 +0,0 @@ -using System.Collections; -using UnityEngine; -using UnityEngine.Networking; - -namespace Mirror.Cloud.ListServerService -{ - public sealed class ListServerServerApi : ListServerBaseApi, IListServerServerApi - { - const int PingInterval = 20; - const int MaxPingFails = 15; - - ServerJson currentServer; - string serverId; - - Coroutine _pingCoroutine; - /// - /// If the server has already been added - /// - bool added; - /// - /// if a request is currently sending - /// - bool sending; - /// - /// If an update request was recently sent - /// - bool skipNextPing; - /// - /// How many failed pings in a row - /// - int pingFails = 0; - - public bool ServerInList => added; - - public ListServerServerApi(ICoroutineRunner runner, IRequestCreator requestCreator) : base(runner, requestCreator) - { - } - - public void Shutdown() - { - stopPingCoroutine(); - if (added) - { - removeServerWithoutCoroutine(); - } - added = false; - } - - public void AddServer(ServerJson server) - { - if (added) { Logger.LogWarning("AddServer called when server was already adding or added"); return; } - bool valid = server.Validate(); - if (!valid) { return; } - - runner.StartCoroutine(addServer(server)); - } - - public void UpdateServer(int newPlayerCount) - { - if (!added) { Logger.LogWarning("UpdateServer called when before server was added"); return; } - - currentServer.playerCount = newPlayerCount; - UpdateServer(currentServer); - } - - public void UpdateServer(ServerJson server) - { - // TODO, use PartialServerJson as Arg Instead - if (!added) { Logger.LogWarning("UpdateServer called when before server was added"); return; } - - PartialServerJson partialServer = new PartialServerJson - { - displayName = server.displayName, - playerCount = server.playerCount, - maxPlayerCount = server.maxPlayerCount, - customData = server.customData, - }; - partialServer.Validate(); - - runner.StartCoroutine(updateServer(partialServer)); - } - - public void RemoveServer() - { - if (!added) { return; } - - if (string.IsNullOrEmpty(serverId)) - { - Logger.LogWarning("Can not remove server because serverId was empty"); - return; - } - - stopPingCoroutine(); - runner.StartCoroutine(removeServer()); - } - - void stopPingCoroutine() - { - if (_pingCoroutine != null) - { - runner.StopCoroutine(_pingCoroutine); - _pingCoroutine = null; - } - } - - IEnumerator addServer(ServerJson server) - { - added = true; - sending = true; - currentServer = server; - - UnityWebRequest request = requestCreator.Post("servers", currentServer); - yield return requestCreator.SendRequestEnumerator(request, onSuccess, onFail); - sending = false; - - void onSuccess(string responseBody) - { - CreatedIdJson created = JsonUtility.FromJson(responseBody); - serverId = created.id; - - // Start ping to keep server alive - _pingCoroutine = runner.StartCoroutine(ping()); - } - void onFail(string responseBody) - { - added = false; - } - } - - IEnumerator updateServer(PartialServerJson server) - { - // wait to not be sending - while (sending) - { - yield return new WaitForSeconds(1); - } - - // We need to check added incase Update is called soon after Add, and add failed - if (!added) { Logger.LogWarning("UpdateServer called when before server was added"); yield break; } - - sending = true; - UnityWebRequest request = requestCreator.Patch("servers/" + serverId, server); - yield return requestCreator.SendRequestEnumerator(request, onSuccess); - sending = false; - - void onSuccess(string responseBody) - { - skipNextPing = true; - - if (_pingCoroutine == null) - { - _pingCoroutine = runner.StartCoroutine(ping()); - } - } - } - - /// - /// Keeps server alive in database - /// - /// - IEnumerator ping() - { - while (pingFails <= MaxPingFails) - { - yield return new WaitForSeconds(PingInterval); - if (skipNextPing) - { - skipNextPing = false; - continue; - } - - sending = true; - UnityWebRequest request = requestCreator.Patch("servers/" + serverId, new EmptyJson()); - yield return requestCreator.SendRequestEnumerator(request, onSuccess, onFail); - sending = false; - } - - Logger.LogWarning("Max ping fails reached, stoping to ping server"); - _pingCoroutine = null; - - - void onSuccess(string responseBody) - { - pingFails = 0; - } - void onFail(string responseBody) - { - pingFails++; - } - } - - IEnumerator removeServer() - { - sending = true; - UnityWebRequest request = requestCreator.Delete("servers/" + serverId); - yield return requestCreator.SendRequestEnumerator(request); - sending = false; - - added = false; - } - - void removeServerWithoutCoroutine() - { - if (string.IsNullOrEmpty(serverId)) - { - Logger.LogWarning("Can not remove server becuase serverId was empty"); - return; - } - - UnityWebRequest request = requestCreator.Delete("servers/" + serverId); - UnityWebRequestAsyncOperation operation = request.SendWebRequest(); - - operation.completed += (op) => - { - Logger.LogResponse(request); - }; - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Cloud/Mirror.Cloud.asmdef b/Assets/ImportedAssets/Mirror/Cloud/Mirror.Cloud.asmdef deleted file mode 100644 index dbea9716d1..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Mirror.Cloud.asmdef +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "Mirror.Cloud", - "references": [ - "Mirror" - ], - "optionalUnityReferences": [], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [] -} \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Cloud/Mirror.Cloud.asmdef.meta b/Assets/ImportedAssets/Mirror/Cloud/Mirror.Cloud.asmdef.meta deleted file mode 100644 index bd17c2b3ff..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/Mirror.Cloud.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: c21ba7b8c3183cb47b7fe3b3799d49c4 -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Cloud/README.md b/Assets/ImportedAssets/Mirror/Cloud/README.md deleted file mode 100644 index 5e476a2700..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# Mirror Cloud Services - -## Mirror List Server - -Example has API key that can be used for as a demo. - -To get an API key to use within your game you can subscribe on the [Mirror Networking Website](https://mirror-networking.com/list-server/) - -### Key features - -- The Cloud Service works via https so is secure and can be used from any platform. -- It runs on Google Cloud so there is no worry about server down time. -- It scales really well. Default quota is 1000 API requests per minute. If you have high demands, contact us and we can increase that limit. - -## List Server Examples - -An example for this can be found in Mirror/Examples/Cloud/ - -*Note: you can not connect to your own public ip address, you will need at least people to test this* - -## How to use - -Add `ApiConnector` component to an object in your game, It is probably best to put this on the same object as your NetworkManager. Once it has been added set the `ApiAddress` and `ApiKey` fields. - -To use `ApiConnector` either directly reference it in an inspector field or get it when your script awakes -```cs -ApiConnector connector; - -void Awake() -{ - connector = FindObjectOfType(); -} -``` - - -The Api calls are grouped into objects. `connector.ListServer.ServerApi` has the Server api calls like `AddServer`. `connector.ListServer.ClientApi` has the Client Api calls like `GetServerList`. - -### Server Api Example - -Example of how to add server -```cs -void AddServer(int playerCount) -{ - Transport transport = Transport.activeTransport; - - Uri uri = transport.ServerUri(); - int port = uri.Port; - string protocol = uri.Scheme; - - connector.ListServer.ServerApi.AddServer(new ServerJson - { - displayName = "Fun game!!!", - protocol = protocol, - port = port, - maxPlayerCount = NetworkManager.singleton.maxConnections, - playerCount = playerCount - }); -} -``` - -### Client Api Example -Example of how to list servers - -```cs -ApiConnector connector; - -void Awake() -{ - connector = FindObjectOfType(); - // add listener to event that will update UI when Server list is refreshed - connector.ListServer.ClientApi.onServerListUpdated += onServerListUpdated; - - // add listen to button so that player can refresh server list - refreshButton.onClick.AddListener(RefreshButtonHandler); -} - -public void RefreshButtonHandler() -{ - connector.ListServer.ClientApi.GetServerList(); -} - -void onServerListUpdated() -{ - // Update UI here -} -``` diff --git a/Assets/ImportedAssets/Mirror/Cloud/README.md.meta b/Assets/ImportedAssets/Mirror/Cloud/README.md.meta deleted file mode 100644 index d669f54f35..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/README.md.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 04945d14ccbed964597a1ee00805c059 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Cloud/version.txt b/Assets/ImportedAssets/Mirror/Cloud/version.txt deleted file mode 100644 index 7b0bc8d620..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/version.txt +++ /dev/null @@ -1 +0,0 @@ -MirrorCloudServices v0.1.0 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Cloud/version.txt.meta b/Assets/ImportedAssets/Mirror/Cloud/version.txt.meta deleted file mode 100644 index 1e13fd52b4..0000000000 --- a/Assets/ImportedAssets/Mirror/Cloud/version.txt.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: bf81e376b88e68e48a47531b8bfeb0f4 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef.meta b/Assets/ImportedAssets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef.meta index 8b2382361d..3612f5efd2 100644 --- a/Assets/ImportedAssets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef.meta +++ b/Assets/ImportedAssets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef.meta @@ -5,3 +5,10 @@ AssemblyDefinitionImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/CompilerSymbols/PreprocessorDefine.cs b/Assets/ImportedAssets/Mirror/CompilerSymbols/PreprocessorDefine.cs index a05069583b..79775a7bd6 100644 --- a/Assets/ImportedAssets/Mirror/CompilerSymbols/PreprocessorDefine.cs +++ b/Assets/ImportedAssets/Mirror/CompilerSymbols/PreprocessorDefine.cs @@ -11,35 +11,38 @@ static class PreprocessorDefine [InitializeOnLoadMethod] public static void AddDefineSymbols() { +#if UNITY_2021_2_OR_NEWER + string currentDefines = PlayerSettings.GetScriptingDefineSymbols(UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup(EditorUserBuildSettings.selectedBuildTargetGroup)); +#else + // Deprecated in Unity 2023.1 string currentDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); +#endif + // Remove oldest when adding next month's symbol. + // Keep a rolling 12 months of symbols. HashSet defines = new HashSet(currentDefines.Split(';')) { "MIRROR", - "MIRROR_1726_OR_NEWER", - "MIRROR_3_0_OR_NEWER", - "MIRROR_3_12_OR_NEWER", - "MIRROR_4_0_OR_NEWER", - "MIRROR_5_0_OR_NEWER", - "MIRROR_6_0_OR_NEWER", - "MIRROR_7_0_OR_NEWER", - "MIRROR_8_0_OR_NEWER", - "MIRROR_9_0_OR_NEWER", - "MIRROR_10_0_OR_NEWER", - "MIRROR_11_0_OR_NEWER", - "MIRROR_12_0_OR_NEWER", - "MIRROR_13_0_OR_NEWER", - "MIRROR_14_0_OR_NEWER", - "MIRROR_15_0_OR_NEWER", - "MIRROR_16_0_OR_NEWER", - "MIRROR_17_0_OR_NEWER" + "MIRROR_79_OR_NEWER", + "MIRROR_81_OR_NEWER", + "MIRROR_82_OR_NEWER", + "MIRROR_83_OR_NEWER", + "MIRROR_84_OR_NEWER", + "MIRROR_85_OR_NEWER", + "MIRROR_86_OR_NEWER", + "MIRROR_89_OR_NEWER" }; - // only touch PlayerSettings if we actually modified it. + // only touch PlayerSettings if we actually modified it, // otherwise it shows up as changed in git each time. string newDefines = string.Join(";", defines); if (newDefines != currentDefines) { +#if UNITY_2021_2_OR_NEWER + PlayerSettings.SetScriptingDefineSymbols(UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup(EditorUserBuildSettings.selectedBuildTargetGroup), newDefines); +#else + // Deprecated in Unity 2023.1 PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, newDefines); +#endif } } } diff --git a/Assets/ImportedAssets/Mirror/CompilerSymbols/PreprocessorDefine.cs.meta b/Assets/ImportedAssets/Mirror/CompilerSymbols/PreprocessorDefine.cs.meta index 30806d0f57..a97e174fec 100644 --- a/Assets/ImportedAssets/Mirror/CompilerSymbols/PreprocessorDefine.cs.meta +++ b/Assets/ImportedAssets/Mirror/CompilerSymbols/PreprocessorDefine.cs.meta @@ -5,7 +5,14 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/CompilerSymbols/PreprocessorDefine.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/AssemblyInfo.cs b/Assets/ImportedAssets/Mirror/Components/AssemblyInfo.cs new file mode 100644 index 0000000000..f342716a8b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/AssemblyInfo.cs @@ -0,0 +1,12 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Mirror.Tests.Common")] +[assembly: InternalsVisibleTo("Mirror.Tests")] +// need to use Unity.*.CodeGen assembly name to import Unity.CompilationPipeline +// for ILPostProcessor tests. +[assembly: InternalsVisibleTo("Unity.Mirror.Tests.CodeGen")] +[assembly: InternalsVisibleTo("Mirror.Tests.Generated")] +[assembly: InternalsVisibleTo("Mirror.Tests.Runtime")] +[assembly: InternalsVisibleTo("Mirror.Tests.Performance.Editor")] +[assembly: InternalsVisibleTo("Mirror.Tests.Performance.Runtime")] +[assembly: InternalsVisibleTo("Mirror.Editor")] diff --git a/Assets/ImportedAssets/Mirror/Components/AssemblyInfo.cs.meta b/Assets/ImportedAssets/Mirror/Components/AssemblyInfo.cs.meta new file mode 100644 index 0000000000..f739791d54 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/AssemblyInfo.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a65b9283f7a724e70b8e17cb277f4c1e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/AssemblyInfo.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscovery.cs b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscovery.cs index dd64a34e7e..5fa939728c 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscovery.cs +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscovery.cs @@ -6,35 +6,14 @@ namespace Mirror.Discovery { [Serializable] - public class ServerFoundUnityEvent : UnityEvent { }; + public class ServerFoundUnityEvent : UnityEvent {}; [DisallowMultipleComponent] - [AddComponentMenu("Network/NetworkDiscovery")] + [AddComponentMenu("Network/Network Discovery")] public class NetworkDiscovery : NetworkDiscoveryBase { #region Server - public long ServerId { get; private set; } - - [Tooltip("Transport to be advertised during discovery")] - public Transport transport; - - [Tooltip("Invoked when a server is found")] - public ServerFoundUnityEvent OnServerFound; - - public override void Start() - { - ServerId = RandomLong(); - - // active transport gets initialized in awake - // so make sure we set it here in Start() (after awakes) - // Or just let the user assign it in the inspector - if (transport == null) - transport = Transport.activeTransport; - - base.Start(); - } - /// /// Process the request from a client /// @@ -42,7 +21,7 @@ public override void Start() /// Override if you wish to provide more information to the clients /// such as the name of the host player /// - /// Request comming from client + /// Request coming from client /// Address of the client that sent the request /// The message to be sent back to the client or null protected override ServerResponse ProcessRequest(ServerRequest request, IPEndPoint endpoint) diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscovery.cs.meta b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscovery.cs.meta index c691a613bf..dd1b44fc7c 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscovery.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscovery.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscovery.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs index c55c1ebb47..4417344026 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs @@ -16,16 +16,21 @@ namespace Mirror.Discovery /// NetworkDiscovery for a sample implementation /// [DisallowMultipleComponent] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkDiscovery.html")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-discovery")] public abstract class NetworkDiscoveryBase : MonoBehaviour - where Request : IMessageBase, new() - where Response : IMessageBase, new() + where Request : NetworkMessage + where Response : NetworkMessage { public static bool SupportedOnThisPlatform { get { return Application.platform != RuntimePlatform.WebGLPlayer; } } - // each game should have a random unique handshake, this way you can tell if this is the same game or not - [HideInInspector] - public long secretHandshake; + [SerializeField] + [Tooltip("If true, broadcasts a discovery request every ActiveDiscoveryInterval seconds")] + public bool enableActiveDiscovery = true; + + // broadcast address needs to be configurable on iOS: + // https://github.com/vis2k/Mirror/pull/3255 + [Tooltip("iOS may require LAN IP address here (e.g. 192.168.x.x), otherwise leave blank.")] + public string BroadcastAddress = ""; [SerializeField] [Tooltip("The UDP port the server will listen for multi-cast messages")] @@ -36,12 +41,28 @@ public abstract class NetworkDiscoveryBase : MonoBehaviour [Range(1, 60)] float ActiveDiscoveryInterval = 3; + [Tooltip("Transport to be advertised during discovery")] + public Transport transport; + + [Tooltip("Invoked when a server is found")] + public ServerFoundUnityEvent OnServerFound; + + // Each game should have a random unique handshake, + // this way you can tell if this is the same game or not + [HideInInspector] + public long secretHandshake; + + public long ServerId { get; private set; } + protected UdpClient serverUdpClient; protected UdpClient clientUdpClient; #if UNITY_EDITOR - void OnValidate() + public virtual void OnValidate() { + if (transport == null) + transport = GetComponent(); + if (secretHandshake == 0) { secretHandshake = RandomLong(); @@ -50,32 +71,55 @@ void OnValidate() } #endif - public static long RandomLong() - { - int value1 = UnityEngine.Random.Range(int.MinValue, int.MaxValue); - int value2 = UnityEngine.Random.Range(int.MinValue, int.MaxValue); - return value1 + ((long)value2 << 32); - } - /// /// virtual so that inheriting classes' Start() can call base.Start() too /// public virtual void Start() { + ServerId = RandomLong(); + + // active transport gets initialized in Awake + // so make sure we set it here in Start() after Awake + // Or just let the user assign it in the inspector + if (transport == null) + transport = Transport.active; + // Server mode? then start advertising -#if UNITY_SERVER - AdvertiseServer(); -#endif + if (Utils.IsHeadless()) + { + AdvertiseServer(); + } + } + + public static long RandomLong() + { + int value1 = UnityEngine.Random.Range(int.MinValue, int.MaxValue); + int value2 = UnityEngine.Random.Range(int.MinValue, int.MaxValue); + return value1 + ((long)value2 << 32); } // Ensure the ports are cleared no matter when Game/Unity UI exits void OnApplicationQuit() { + //Debug.Log("NetworkDiscoveryBase OnApplicationQuit"); + Shutdown(); + } + + void OnDisable() + { + //Debug.Log("NetworkDiscoveryBase OnDisable"); + Shutdown(); + } + + void OnDestroy() + { + //Debug.Log("NetworkDiscoveryBase OnDestroy"); Shutdown(); } void Shutdown() { + EndpMulticastLock(); if (serverUdpClient != null) { try @@ -132,6 +176,7 @@ public void AdvertiseServer() public async Task ServerListenAsync() { + BeginMulticastLock(); while (true) { try @@ -143,9 +188,7 @@ public async Task ServerListenAsync() // socket has been closed break; } - catch (Exception) - { - } + catch (Exception) {} } } @@ -156,17 +199,16 @@ async Task ReceiveRequestAsync(UdpClient udpClient) UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(udpReceiveResult.Buffer)) + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(udpReceiveResult.Buffer)) { - long handshake = networkReader.ReadInt64(); + long handshake = networkReader.ReadLong(); if (handshake != secretHandshake) { // message is not for us throw new ProtocolViolationException("Invalid handshake"); } - Request request = new Request(); - request.Deserialize(networkReader); + Request request = networkReader.Read(); ProcessClientRequest(request, udpReceiveResult.RemoteEndPoint); } @@ -179,7 +221,7 @@ async Task ReceiveRequestAsync(UdpClient udpClient) /// Override if you wish to ignore server requests based on /// custom criteria such as language, full server game mode or difficulty /// - /// Request comming from client + /// Request coming from client /// Address of the client that sent the request protected virtual void ProcessClientRequest(Request request, IPEndPoint endpoint) { @@ -188,13 +230,13 @@ protected virtual void ProcessClientRequest(Request request, IPEndPoint endpoint if (info == null) return; - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) { try { - writer.WriteInt64(secretHandshake); + writer.WriteLong(secretHandshake); - info.Serialize(writer); + writer.Write(info); ArraySegment data = writer.ToArraySegment(); // signature matches @@ -215,12 +257,48 @@ protected virtual void ProcessClientRequest(Request request, IPEndPoint endpoint /// Override if you wish to provide more information to the clients /// such as the name of the host player /// - /// Request comming from client + /// Request coming from client /// Address of the client that sent the request /// The message to be sent back to the client or null protected abstract Response ProcessRequest(Request request, IPEndPoint endpoint); - #endregion + // Android Multicast fix: https://github.com/vis2k/Mirror/pull/2887 +#if UNITY_ANDROID + AndroidJavaObject multicastLock; + bool hasMulticastLock; +#endif + + void BeginMulticastLock() + { +#if UNITY_ANDROID + if (hasMulticastLock) return; + + if (Application.platform == RuntimePlatform.Android) + { + using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity")) + { + using (var wifiManager = activity.Call("getSystemService", "wifi")) + { + multicastLock = wifiManager.Call("createMulticastLock", "lock"); + multicastLock.Call("acquire"); + hasMulticastLock = true; + } + } + } +#endif + } + + void EndpMulticastLock() + { +#if UNITY_ANDROID + if (!hasMulticastLock) return; + + multicastLock?.Call("release"); + hasMulticastLock = false; +#endif + } + +#endregion #region Client @@ -246,13 +324,14 @@ public void StartDiscovery() catch (Exception) { // Free the port if we took it + //Debug.LogError("NetworkDiscoveryBase StartDiscovery Exception"); Shutdown(); throw; } _ = ClientListenAsync(); - InvokeRepeating(nameof(BroadcastDiscoveryRequest), 0, ActiveDiscoveryInterval); + if (enableActiveDiscovery) InvokeRepeating(nameof(BroadcastDiscoveryRequest), 0, ActiveDiscoveryInterval); } /// @@ -260,6 +339,7 @@ public void StartDiscovery() /// public void StopDiscovery() { + //Debug.Log("NetworkDiscoveryBase StopDiscovery"); Shutdown(); } @@ -269,7 +349,18 @@ public void StopDiscovery() /// ClientListenAsync Task public async Task ClientListenAsync() { - while (true) + // while clientUpdClient to fix: + // https://github.com/vis2k/Mirror/pull/2908 + // + // If, you cancel discovery the clientUdpClient is set to null. + // However, nothing cancels ClientListenAsync. If we change the if(true) + // to check if the client is null. You can properly cancel the discovery, + // and kill the listen thread. + // + // Prior to this fix, if you cancel the discovery search. It crashes the + // thread, and is super noisy in the output. As well as causes issues on + // the quest. + while (clientUdpClient != null) { try { @@ -295,17 +386,35 @@ public void BroadcastDiscoveryRequest() if (clientUdpClient == null) return; + if (NetworkClient.isConnected) + { + StopDiscovery(); + return; + } + IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, serverBroadcastListenPort); - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + if (!string.IsNullOrWhiteSpace(BroadcastAddress)) + { + try + { + endPoint = new IPEndPoint(IPAddress.Parse(BroadcastAddress), serverBroadcastListenPort); + } + catch (Exception ex) + { + Debug.LogException(ex); + } + } + + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) { - writer.WriteInt64(secretHandshake); + writer.WriteLong(secretHandshake); try { Request request = GetRequest(); - request.Serialize(writer); + writer.Write(request); ArraySegment data = writer.ToArraySegment(); @@ -325,7 +434,7 @@ public void BroadcastDiscoveryRequest() /// Override if you wish to include additional data in the discovery message /// such as desired game mode, language, difficulty, etc... /// An instance of ServerRequest with data to be broadcasted - protected virtual Request GetRequest() => new Request(); + protected virtual Request GetRequest() => default; async Task ReceiveGameBroadcastAsync(UdpClient udpClient) { @@ -334,13 +443,12 @@ async Task ReceiveGameBroadcastAsync(UdpClient udpClient) UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(udpReceiveResult.Buffer)) + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(udpReceiveResult.Buffer)) { - if (networkReader.ReadInt64() != secretHandshake) + if (networkReader.ReadLong() != secretHandshake) return; - Response response = new Response(); - response.Deserialize(networkReader); + Response response = networkReader.Read(); ProcessResponse(response, udpReceiveResult.RemoteEndPoint); } diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs.meta b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs.meta index 7dfbaf62a1..5e363c3635 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs.meta @@ -5,7 +5,14 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs index cfb53d686d..e43c3d7720 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs @@ -4,8 +4,8 @@ namespace Mirror.Discovery { [DisallowMultipleComponent] - [AddComponentMenu("Network/NetworkDiscoveryHUD")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkDiscovery.html")] + [AddComponentMenu("Network/Network Discovery HUD")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-discovery")] [RequireComponent(typeof(NetworkDiscovery))] public class NetworkDiscoveryHUD : MonoBehaviour { @@ -31,15 +31,16 @@ void OnGUI() if (NetworkManager.singleton == null) return; - if (NetworkServer.active || NetworkClient.active) - return; - if (!NetworkClient.isConnected && !NetworkServer.active && !NetworkClient.active) DrawGUI(); + + if (NetworkServer.active || NetworkClient.active) + StopButtons(); } void DrawGUI() { + GUILayout.BeginArea(new Rect(10, 10, 300, 500)); GUILayout.BeginHorizontal(); if (GUILayout.Button("Find Servers")) @@ -61,7 +62,6 @@ void DrawGUI() { discoveredServers.Clear(); NetworkManager.singleton.StartServer(); - networkDiscovery.AdvertiseServer(); } @@ -79,10 +79,47 @@ void DrawGUI() Connect(info); GUILayout.EndScrollView(); + GUILayout.EndArea(); + } + + void StopButtons() + { + GUILayout.BeginArea(new Rect(10, 40, 100, 25)); + + // stop host if host mode + if (NetworkServer.active && NetworkClient.isConnected) + { + if (GUILayout.Button("Stop Host")) + { + NetworkManager.singleton.StopHost(); + networkDiscovery.StopDiscovery(); + } + } + // stop client if client-only + else if (NetworkClient.isConnected) + { + if (GUILayout.Button("Stop Client")) + { + NetworkManager.singleton.StopClient(); + networkDiscovery.StopDiscovery(); + } + } + // stop server if server-only + else if (NetworkServer.active) + { + if (GUILayout.Button("Stop Server")) + { + NetworkManager.singleton.StopServer(); + networkDiscovery.StopDiscovery(); + } + } + + GUILayout.EndArea(); } void Connect(ServerResponse info) { + networkDiscovery.StopDiscovery(); NetworkManager.singleton.StartClient(info.uri); } diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs.meta b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs.meta index f93b275c2a..4bcd3d61ef 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/ServerRequest.cs b/Assets/ImportedAssets/Mirror/Components/Discovery/ServerRequest.cs index 3ac59cfa4e..647b619db3 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/ServerRequest.cs +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/ServerRequest.cs @@ -1,4 +1,4 @@ namespace Mirror.Discovery { - public class ServerRequest : MessageBase { } + public struct ServerRequest : NetworkMessage {} } diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/ServerRequest.cs.meta b/Assets/ImportedAssets/Mirror/Components/Discovery/ServerRequest.cs.meta index 84f3232a16..2b98e6dbe0 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/ServerRequest.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/ServerRequest.cs.meta @@ -5,7 +5,14 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/Discovery/ServerRequest.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/ServerResponse.cs b/Assets/ImportedAssets/Mirror/Components/Discovery/ServerResponse.cs index 34173e532b..7465783760 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/ServerResponse.cs +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/ServerResponse.cs @@ -3,7 +3,7 @@ namespace Mirror.Discovery { - public class ServerResponse : MessageBase + public struct ServerResponse : NetworkMessage { // The server that sent this // this is a property so that it is not serialized, but the diff --git a/Assets/ImportedAssets/Mirror/Components/Discovery/ServerResponse.cs.meta b/Assets/ImportedAssets/Mirror/Components/Discovery/ServerResponse.cs.meta index 44f23bac43..edbbb3788e 100644 --- a/Assets/ImportedAssets/Mirror/Components/Discovery/ServerResponse.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/Discovery/ServerResponse.cs.meta @@ -5,7 +5,14 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/Discovery/ServerResponse.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs index ac1e2df854..f3be8c8949 100644 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs +++ b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs @@ -1,23 +1,26 @@ +using System; using UnityEngine; namespace Mirror.Experimental { - [AddComponentMenu("Network/Experimental/NetworkLerpRigidbody")] - //[HelpURL("https://mirror-networking.com/docs/Components/NetworkLerpRigidbody.html")] + [AddComponentMenu("")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-lerp-rigidbody")] + [Obsolete("Use the new NetworkRigidbodyReliable/Unreliable component with Snapshot Interpolation instead.")] public class NetworkLerpRigidbody : NetworkBehaviour { [Header("Settings")] [SerializeField] internal Rigidbody target = null; + [Tooltip("How quickly current velocity approaches target velocity")] [SerializeField] float lerpVelocityAmount = 0.5f; + [Tooltip("How quickly current position approaches target position")] [SerializeField] float lerpPositionAmount = 0.5f; [Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")] [SerializeField] bool clientAuthority = false; - float nextSyncTime; - + double nextSyncTime; [SyncVar()] Vector3 targetVelocity; @@ -28,40 +31,41 @@ public class NetworkLerpRigidbody : NetworkBehaviour /// /// Ignore value if is host or client with Authority /// - /// bool IgnoreSync => isServer || ClientWithAuthority; - bool ClientWithAuthority => clientAuthority && hasAuthority; + bool ClientWithAuthority => clientAuthority && isOwned; - void OnValidate() + protected override void OnValidate() + { + base.OnValidate(); + Reset(); + } + + public virtual void Reset() { if (target == null) - { target = GetComponent(); - } + + syncDirection = SyncDirection.ClientToServer; } void Update() { if (isServer) - { SyncToClients(); - } else if (ClientWithAuthority) - { SendToServer(); - } } - private void SyncToClients() + void SyncToClients() { targetVelocity = target.velocity; targetPosition = target.position; } - private void SendToServer() + void SendToServer() { - float now = Time.time; + double now = NetworkTime.localTime; // Unity 2019 doesn't have Time.timeAsDouble yet if (now > nextSyncTime) { nextSyncTime = now + syncInterval; @@ -70,7 +74,7 @@ private void SendToServer() } [Command] - private void CmdSendState(Vector3 velocity, Vector3 position) + void CmdSendState(Vector3 velocity, Vector3 position) { target.velocity = velocity; target.position = position; @@ -85,7 +89,7 @@ void FixedUpdate() target.velocity = Vector3.Lerp(target.velocity, targetVelocity, lerpVelocityAmount); target.position = Vector3.Lerp(target.position, targetPosition, lerpPositionAmount); // add velocity to position as position would have moved on server at that velocity - targetPosition += target.velocity * Time.fixedDeltaTime; + target.position += target.velocity * Time.fixedDeltaTime; // TODO does this also need to sync acceleration so and update velocity? } diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs.meta b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs.meta index a742b54d11..c1cc5a6e77 100644 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs.meta @@ -5,7 +5,14 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {instanceID: 0} + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody.cs b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody.cs index fe851585a3..e99f6ed3d6 100644 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody.cs +++ b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody.cs @@ -1,21 +1,20 @@ +using System; using UnityEngine; namespace Mirror.Experimental { - [AddComponentMenu("Network/Experimental/NetworkRigidbody")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkRigidbody.html")] + [AddComponentMenu("")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-rigidbody")] + [Obsolete("Use the new NetworkRigidbodyReliable/Unreliable component with Snapshot Interpolation instead.")] public class NetworkRigidbody : NetworkBehaviour { - static readonly ILogger logger = LogFactory.GetLogger(typeof(NetworkRigidbody)); - [Header("Settings")] [SerializeField] internal Rigidbody target = null; [Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")] - [SerializeField] bool clientAuthority = false; + public bool clientAuthority = false; [Header("Velocity")] - [Tooltip("Syncs Velocity every SyncInterval")] [SerializeField] bool syncVelocity = true; @@ -25,9 +24,7 @@ public class NetworkRigidbody : NetworkBehaviour [Tooltip("Only Syncs Value if distance between previous and current is great than sensitivity")] [SerializeField] float velocitySensitivity = 0.1f; - [Header("Angular Velocity")] - [Tooltip("Syncs AngularVelocity every SyncInterval")] [SerializeField] bool syncAngularVelocity = true; @@ -38,20 +35,26 @@ public class NetworkRigidbody : NetworkBehaviour [SerializeField] float angularVelocitySensitivity = 0.1f; /// - /// Values sent on client with authoirty after they are sent to the server + /// Values sent on client with authority after they are sent to the server /// readonly ClientSyncState previousValue = new ClientSyncState(); - void OnValidate() + protected override void OnValidate() + { + base.OnValidate(); + Reset(); + } + + public virtual void Reset() { if (target == null) - { target = GetComponent(); - } - } + syncDirection = SyncDirection.ClientToServer; + } #region Sync vars + [SyncVar(hook = nameof(OnVelocityChanged))] Vector3 velocity; @@ -76,7 +79,7 @@ void OnValidate() /// bool IgnoreSync => isServer || ClientWithAuthority; - bool ClientWithAuthority => clientAuthority && hasAuthority; + bool ClientWithAuthority => clientAuthority && isOwned; void OnVelocityChanged(Vector3 _, Vector3 newValue) { @@ -86,7 +89,6 @@ void OnVelocityChanged(Vector3 _, Vector3 newValue) target.velocity = newValue; } - void OnAngularVelocityChanged(Vector3 _, Vector3 newValue) { if (IgnoreSync) @@ -126,32 +128,24 @@ void OnAngularDragChanged(float _, float newValue) target.angularDrag = newValue; } - #endregion + #endregion internal void Update() { if (isServer) - { SyncToClients(); - } else if (ClientWithAuthority) - { SendToServer(); - } } internal void FixedUpdate() { if (clearAngularVelocity && !syncAngularVelocity) - { target.angularVelocity = Vector3.zero; - } if (clearVelocity && !syncVelocity) - { target.velocity = Vector3.zero; - } } /// @@ -193,9 +187,9 @@ void SyncToClients() [Client] void SendToServer() { - if (!hasAuthority) + if (!isOwned) { - logger.LogWarning("SendToServer called without authority"); + Debug.LogWarning("SendToServer called without authority"); return; } @@ -206,7 +200,7 @@ void SendToServer() [Client] void SendVelocity() { - float now = Time.time; + double now = NetworkTime.localTime; // Unity 2019 doesn't have Time.timeAsDouble yet if (now < previousValue.nextSyncTime) return; @@ -233,9 +227,7 @@ void SendVelocity() // only update syncTime if either has changed if (angularVelocityChanged || velocityChanged) - { previousValue.nextSyncTime = now + syncInterval; - } } [Client] @@ -291,10 +283,9 @@ void CmdSendVelocityAndAngular(Vector3 velocity, Vector3 angularVelocity) if (syncVelocity) { this.velocity = velocity; - target.velocity = velocity; - } + this.angularVelocity = angularVelocity; target.angularVelocity = angularVelocity; } @@ -351,7 +342,7 @@ public class ClientSyncState /// /// Next sync time that velocity will be synced, based on syncInterval. /// - public float nextSyncTime; + public double nextSyncTime; public Vector3 velocity; public Vector3 angularVelocity; public bool isKinematic; diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody.cs.meta b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody.cs.meta index 1610f0a737..48a6ca37e6 100644 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody2D.cs b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody2D.cs new file mode 100644 index 0000000000..3209dfe4cd --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody2D.cs @@ -0,0 +1,351 @@ +using System; +using UnityEngine; + +namespace Mirror.Experimental +{ + [AddComponentMenu("")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-rigidbody")] + [Obsolete("Use the new NetworkRigidbodyReliable/Unreliable 2D component with Snapshot Interpolation instead.")] + public class NetworkRigidbody2D : NetworkBehaviour + { + [Header("Settings")] + [SerializeField] internal Rigidbody2D target = null; + + [Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")] + public bool clientAuthority = false; + + [Header("Velocity")] + [Tooltip("Syncs Velocity every SyncInterval")] + [SerializeField] bool syncVelocity = true; + + [Tooltip("Set velocity to 0 each frame (only works if syncVelocity is false")] + [SerializeField] bool clearVelocity = false; + + [Tooltip("Only Syncs Value if distance between previous and current is great than sensitivity")] + [SerializeField] float velocitySensitivity = 0.1f; + + [Header("Angular Velocity")] + [Tooltip("Syncs AngularVelocity every SyncInterval")] + [SerializeField] bool syncAngularVelocity = true; + + [Tooltip("Set angularVelocity to 0 each frame (only works if syncAngularVelocity is false")] + [SerializeField] bool clearAngularVelocity = false; + + [Tooltip("Only Syncs Value if distance between previous and current is great than sensitivity")] + [SerializeField] float angularVelocitySensitivity = 0.1f; + + /// + /// Values sent on client with authority after they are sent to the server + /// + readonly ClientSyncState previousValue = new ClientSyncState(); + + protected override void OnValidate() + { + base.OnValidate(); + Reset(); + } + + public virtual void Reset() + { + if (target == null) + target = GetComponent(); + + syncDirection = SyncDirection.ClientToServer; + } + + #region Sync vars + + [SyncVar(hook = nameof(OnVelocityChanged))] + Vector2 velocity; + + [SyncVar(hook = nameof(OnAngularVelocityChanged))] + float angularVelocity; + + [SyncVar(hook = nameof(OnIsKinematicChanged))] + bool isKinematic; + + [SyncVar(hook = nameof(OnGravityScaleChanged))] + float gravityScale; + + [SyncVar(hook = nameof(OnuDragChanged))] + float drag; + + [SyncVar(hook = nameof(OnAngularDragChanged))] + float angularDrag; + + /// + /// Ignore value if is host or client with Authority + /// + bool IgnoreSync => isServer || ClientWithAuthority; + + bool ClientWithAuthority => clientAuthority && isOwned; + + void OnVelocityChanged(Vector2 _, Vector2 newValue) + { + if (IgnoreSync) + return; + + target.velocity = newValue; + } + + void OnAngularVelocityChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.angularVelocity = newValue; + } + + void OnIsKinematicChanged(bool _, bool newValue) + { + if (IgnoreSync) + return; + + target.isKinematic = newValue; + } + + void OnGravityScaleChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.gravityScale = newValue; + } + + void OnuDragChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.drag = newValue; + } + + void OnAngularDragChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.angularDrag = newValue; + } + + #endregion + + internal void Update() + { + if (isServer) + SyncToClients(); + else if (ClientWithAuthority) + SendToServer(); + } + + internal void FixedUpdate() + { + if (clearAngularVelocity && !syncAngularVelocity) + target.angularVelocity = 0f; + + if (clearVelocity && !syncVelocity) + target.velocity = Vector2.zero; + } + + /// + /// Updates sync var values on server so that they sync to the client + /// + [Server] + void SyncToClients() + { + // only update if they have changed more than Sensitivity + + Vector2 currentVelocity = syncVelocity ? target.velocity : default; + float currentAngularVelocity = syncAngularVelocity ? target.angularVelocity : default; + + bool velocityChanged = syncVelocity && ((previousValue.velocity - currentVelocity).sqrMagnitude > velocitySensitivity * velocitySensitivity); + bool angularVelocityChanged = syncAngularVelocity && ((previousValue.angularVelocity - currentAngularVelocity) > angularVelocitySensitivity); + + if (velocityChanged) + { + velocity = currentVelocity; + previousValue.velocity = currentVelocity; + } + + if (angularVelocityChanged) + { + angularVelocity = currentAngularVelocity; + previousValue.angularVelocity = currentAngularVelocity; + } + + // other rigidbody settings + isKinematic = target.isKinematic; + gravityScale = target.gravityScale; + drag = target.drag; + angularDrag = target.angularDrag; + } + + /// + /// Uses Command to send values to server + /// + [Client] + void SendToServer() + { + if (!isOwned) + { + Debug.LogWarning("SendToServer called without authority"); + return; + } + + SendVelocity(); + SendRigidBodySettings(); + } + + [Client] + void SendVelocity() + { + float now = Time.time; + if (now < previousValue.nextSyncTime) + return; + + Vector2 currentVelocity = syncVelocity ? target.velocity : default; + float currentAngularVelocity = syncAngularVelocity ? target.angularVelocity : default; + + bool velocityChanged = syncVelocity && ((previousValue.velocity - currentVelocity).sqrMagnitude > velocitySensitivity * velocitySensitivity); + bool angularVelocityChanged = syncAngularVelocity && previousValue.angularVelocity != currentAngularVelocity;//((previousValue.angularVelocity - currentAngularVelocity).sqrMagnitude > angularVelocitySensitivity * angularVelocitySensitivity); + + // if angularVelocity has changed it is likely that velocity has also changed so just sync both values + // however if only velocity has changed just send velocity + if (angularVelocityChanged) + { + CmdSendVelocityAndAngular(currentVelocity, currentAngularVelocity); + previousValue.velocity = currentVelocity; + previousValue.angularVelocity = currentAngularVelocity; + } + else if (velocityChanged) + { + CmdSendVelocity(currentVelocity); + previousValue.velocity = currentVelocity; + } + + // only update syncTime if either has changed + if (angularVelocityChanged || velocityChanged) + previousValue.nextSyncTime = now + syncInterval; + } + + [Client] + void SendRigidBodySettings() + { + // These shouldn't change often so it is ok to send in their own Command + if (previousValue.isKinematic != target.isKinematic) + { + CmdSendIsKinematic(target.isKinematic); + previousValue.isKinematic = target.isKinematic; + } + if (previousValue.gravityScale != target.gravityScale) + { + CmdChangeGravityScale(target.gravityScale); + previousValue.gravityScale = target.gravityScale; + } + if (previousValue.drag != target.drag) + { + CmdSendDrag(target.drag); + previousValue.drag = target.drag; + } + if (previousValue.angularDrag != target.angularDrag) + { + CmdSendAngularDrag(target.angularDrag); + previousValue.angularDrag = target.angularDrag; + } + } + + /// + /// Called when only Velocity has changed on the client + /// + [Command] + void CmdSendVelocity(Vector2 velocity) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.velocity = velocity; + target.velocity = velocity; + } + + /// + /// Called when angularVelocity has changed on the client + /// + [Command] + void CmdSendVelocityAndAngular(Vector2 velocity, float angularVelocity) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + if (syncVelocity) + { + this.velocity = velocity; + target.velocity = velocity; + } + this.angularVelocity = angularVelocity; + target.angularVelocity = angularVelocity; + } + + [Command] + void CmdSendIsKinematic(bool isKinematic) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.isKinematic = isKinematic; + target.isKinematic = isKinematic; + } + + [Command] + void CmdChangeGravityScale(float gravityScale) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.gravityScale = gravityScale; + target.gravityScale = gravityScale; + } + + [Command] + void CmdSendDrag(float drag) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.drag = drag; + target.drag = drag; + } + + [Command] + void CmdSendAngularDrag(float angularDrag) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.angularDrag = angularDrag; + target.angularDrag = angularDrag; + } + + /// + /// holds previously synced values + /// + public class ClientSyncState + { + /// + /// Next sync time that velocity will be synced, based on syncInterval. + /// + public float nextSyncTime; + public Vector2 velocity; + public float angularVelocity; + public bool isKinematic; + public float gravityScale; + public float drag; + public float angularDrag; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody2D.cs.meta b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody2D.cs.meta new file mode 100644 index 0000000000..bb82099445 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody2D.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ab2cbc52526ea384ba280d13cd1a57b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/Experimental/NetworkRigidbody2D.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransform.cs b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransform.cs deleted file mode 100644 index 288a5e637e..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransform.cs +++ /dev/null @@ -1,12 +0,0 @@ -using UnityEngine; - -namespace Mirror.Experimental -{ - [DisallowMultipleComponent] - [AddComponentMenu("Network/Experimental/NetworkTransformExperimental")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkTransform.html")] - public class NetworkTransform : NetworkTransformBase - { - protected override Transform targetTransform => transform; - } -} diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransform.cs.meta b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransform.cs.meta deleted file mode 100644 index 2bc16dd87e..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransform.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 741bbe11f5357b44593b15c0d11b16bd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformBase.cs b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformBase.cs deleted file mode 100644 index bd33d08b3a..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformBase.cs +++ /dev/null @@ -1,430 +0,0 @@ -// vis2k: -// base class for NetworkTransform and NetworkTransformChild. -// New method is simple and stupid. No more 1500 lines of code. -// -// Server sends current data. -// Client saves it and interpolates last and latest data points. -// Update handles transform movement / rotation -// FixedUpdate handles rigidbody movement / rotation -// -// Notes: -// * Built-in Teleport detection in case of lags / teleport / obstacles -// * Quaternion > EulerAngles because gimbal lock and Quaternion.Slerp -// * Syncs XYZ. Works 3D and 2D. Saving 4 bytes isn't worth 1000 lines of code. -// * Initial delay might happen if server sends packet immediately after moving -// just 1cm, hence we move 1cm and then wait 100ms for next packet -// * Only way for smooth movement is to use a fixed movement speed during -// interpolation. interpolation over time is never that good. -// -using System; -using UnityEngine; - -namespace Mirror.Experimental -{ - public abstract class NetworkTransformBase : NetworkBehaviour - { - // target transform to sync. can be on a child. - protected abstract Transform targetTransform { get; } - - [Header("Authority")] - - [Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")] - [SyncVar] - public bool clientAuthority; - - [Tooltip("Set to true if updates from server should be ignored by owner")] - [SyncVar] - public bool excludeOwnerUpdate = true; - - [Header("Synchronization")] - - [Tooltip("Set to true if position should be synchronized")] - [SyncVar] - public bool syncPosition = true; - - [Tooltip("Set to true if rotation should be synchronized")] - [SyncVar] - public bool syncRotation = true; - - [Tooltip("Set to true if scale should be synchronized")] - [SyncVar] - public bool syncScale = true; - - [Header("Interpolation")] - - [Tooltip("Set to true if position should be interpolated")] - [SyncVar] - public bool interpolatePosition = true; - - [Tooltip("Set to true if rotation should be interpolated")] - [SyncVar] - public bool interpolateRotation = true; - - [Tooltip("Set to true if scale should be interpolated")] - [SyncVar] - public bool interpolateScale = true; - - // Sensitivity is added for VR where human players tend to have micro movements so this can quiet down - // the network traffic. Additionally, rigidbody drift should send less traffic, e.g very slow sliding / rolling. - [Header("Sensitivity")] - - [Tooltip("Changes to the transform must exceed these values to be transmitted on the network.")] - [SyncVar] - public float localPositionSensitivity = .01f; - - [Tooltip("If rotation exceeds this angle, it will be transmitted on the network")] - [SyncVar] - public float localRotationSensitivity = .01f; - - [Tooltip("Changes to the transform must exceed these values to be transmitted on the network.")] - [SyncVar] - public float localScaleSensitivity = .01f; - - [Header("Diagnostics")] - - // server - public Vector3 lastPosition; - public Quaternion lastRotation; - public Vector3 lastScale; - - // client - // use local position/rotation for VR support - [Serializable] - public struct DataPoint - { - public float timeStamp; - public Vector3 localPosition; - public Quaternion localRotation; - public Vector3 localScale; - public float movementSpeed; - - public bool isValid => timeStamp != 0; - } - - // Is this a client with authority over this transform? - // This component could be on the player object or any object that has been assigned authority to this client. - bool IsOwnerWithClientAuthority => hasAuthority && clientAuthority; - - // interpolation start and goal - public DataPoint start = new DataPoint(); - public DataPoint goal = new DataPoint(); - - void FixedUpdate() - { - // if server then always sync to others. - // let the clients know that this has moved - if (isServer && HasEitherMovedRotatedScaled()) - { - RpcMove(targetTransform.localPosition, targetTransform.localRotation, targetTransform.localScale); - } - - if (isClient) - { - // send to server if we have local authority (and aren't the server) - // -> only if connectionToServer has been initialized yet too - if (IsOwnerWithClientAuthority) - { - if (!isServer && HasEitherMovedRotatedScaled()) - { - // serialize - // local position/rotation for VR support - // send to server - CmdClientToServerSync(targetTransform.localPosition, targetTransform.localRotation, targetTransform.localScale); - } - } - else if (goal.isValid) - { - // teleport or interpolate - if (NeedsTeleport()) - { - // local position/rotation for VR support - ApplyPositionRotationScale(goal.localPosition, goal.localRotation, goal.localScale); - - // reset data points so we don't keep interpolating - start = new DataPoint(); - goal = new DataPoint(); - } - else - { - // local position/rotation for VR support - ApplyPositionRotationScale(InterpolatePosition(start, goal, targetTransform.localPosition), - InterpolateRotation(start, goal, targetTransform.localRotation), - InterpolateScale(start, goal, targetTransform.localScale)); - } - - } - } - } - - // moved or rotated or scaled since last time we checked it? - bool HasEitherMovedRotatedScaled() - { - // Save last for next frame to compare only if change was detected, otherwise - // slow moving objects might never sync because of C#'s float comparison tolerance. - // See also: https://github.com/vis2k/Mirror/pull/428) - bool changed = HasMoved || HasRotated || HasScaled; - if (changed) - { - // local position/rotation for VR support - if (syncPosition) lastPosition = targetTransform.localPosition; - if (syncRotation) lastRotation = targetTransform.localRotation; - if (syncScale) lastScale = targetTransform.localScale; - } - return changed; - } - - // local position/rotation for VR support - // SqrMagnitude is faster than Distance per Unity docs - // https://docs.unity3d.com/ScriptReference/Vector3-sqrMagnitude.html - - bool HasMoved => syncPosition && Vector3.SqrMagnitude(lastPosition - targetTransform.localPosition) > localPositionSensitivity * localPositionSensitivity; - bool HasRotated => syncRotation && Quaternion.Angle(lastRotation, targetTransform.localRotation) > localRotationSensitivity; - bool HasScaled => syncScale && Vector3.SqrMagnitude(lastScale - targetTransform.localScale) > localScaleSensitivity * localScaleSensitivity; - - // teleport / lag / stuck detection - // - checking distance is not enough since there could be just a tiny fence between us and the goal - // - checking time always works, this way we just teleport if we still didn't reach the goal after too much time has elapsed - bool NeedsTeleport() - { - // calculate time between the two data points - float startTime = start.isValid ? start.timeStamp : Time.time - Time.fixedDeltaTime; - float goalTime = goal.isValid ? goal.timeStamp : Time.time; - float difference = goalTime - startTime; - float timeSinceGoalReceived = Time.time - goalTime; - return timeSinceGoalReceived > difference * 5; - } - - // local authority client sends sync message to server for broadcasting - [Command] - void CmdClientToServerSync(Vector3 position, Quaternion rotation, Vector3 scale) - { - // Ignore messages from client if not in client authority mode - if (!clientAuthority) - return; - - // deserialize payload - SetGoal(position, rotation, scale); - - // server-only mode does no interpolation to save computations, but let's set the position directly - if (isServer && !isClient) - ApplyPositionRotationScale(goal.localPosition, goal.localRotation, goal.localScale); - - RpcMove(position, rotation, scale); - } - - [ClientRpc] - void RpcMove(Vector3 position, Quaternion rotation, Vector3 scale) - { - if (hasAuthority && excludeOwnerUpdate) return; - - if (!isServer) - SetGoal(position, rotation, scale); - } - - // serialization is needed by OnSerialize and by manual sending from authority - void SetGoal(Vector3 position, Quaternion rotation, Vector3 scale) - { - // put it into a data point immediately - DataPoint temp = new DataPoint - { - // deserialize position - localPosition = position, - localRotation = rotation, - localScale = scale, - timeStamp = Time.time - }; - - // movement speed: based on how far it moved since last time has to be calculated before 'start' is overwritten - temp.movementSpeed = EstimateMovementSpeed(goal, temp, targetTransform, Time.fixedDeltaTime); - - // reassign start wisely - // first ever data point? then make something up for previous one so that we can start interpolation without waiting for next. - if (start.timeStamp == 0) - { - start = new DataPoint - { - timeStamp = Time.time - Time.fixedDeltaTime, - // local position/rotation for VR support - localPosition = targetTransform.localPosition, - localRotation = targetTransform.localRotation, - localScale = targetTransform.localScale, - movementSpeed = temp.movementSpeed - }; - } - // second or nth data point? then update previous - // but: we start at where ever we are right now, so that it's perfectly smooth and we don't jump anywhere - // - // example if we are at 'x': - // - // A--x->B - // - // and then receive a new point C: - // - // A--x--B - // | - // | - // C - // - // then we don't want to just jump to B and start interpolation: - // - // x - // | - // | - // C - // - // we stay at 'x' and interpolate from there to C: - // - // x..B - // \ . - // \. - // C - // - else - { - float oldDistance = Vector3.Distance(start.localPosition, goal.localPosition); - float newDistance = Vector3.Distance(goal.localPosition, temp.localPosition); - - start = goal; - - // local position/rotation for VR support - // teleport / lag / obstacle detection: only continue at current position if we aren't too far away - // XC < AB + BC (see comments above) - if (Vector3.Distance(targetTransform.localPosition, start.localPosition) < oldDistance + newDistance) - { - start.localPosition = targetTransform.localPosition; - start.localRotation = targetTransform.localRotation; - start.localScale = targetTransform.localScale; - } - } - - // set new destination in any case. new data is best data. - goal = temp; - } - - // try to estimate movement speed for a data point based on how far it moved since the previous one - // - if this is the first time ever then we use our best guess: - // - delta based on transform.localPosition - // - elapsed based on send interval hoping that it roughly matches - static float EstimateMovementSpeed(DataPoint from, DataPoint to, Transform transform, float sendInterval) - { - Vector3 delta = to.localPosition - (from.localPosition != transform.localPosition ? from.localPosition : transform.localPosition); - float elapsed = from.isValid ? to.timeStamp - from.timeStamp : sendInterval; - - // avoid NaN - return elapsed > 0 ? delta.magnitude / elapsed : 0; - } - - // set position carefully depending on the target component - void ApplyPositionRotationScale(Vector3 position, Quaternion rotation, Vector3 scale) - { - // local position/rotation for VR support - if (syncPosition) targetTransform.localPosition = position; - if (syncRotation) targetTransform.localRotation = rotation; - if (syncScale) targetTransform.localScale = scale; - } - - // where are we in the timeline between start and goal? [0,1] - Vector3 InterpolatePosition(DataPoint start, DataPoint goal, Vector3 currentPosition) - { - if (!interpolatePosition) - return currentPosition; - - if (start.movementSpeed != 0) - { - // Option 1: simply interpolate based on time, but stutter will happen, it's not that smooth. - // This is especially noticeable if the camera automatically follows the player - // - Tell SonarCloud this isn't really commented code but actual comments and to stfu about it - // - float t = CurrentInterpolationFactor(); - // - return Vector3.Lerp(start.position, goal.position, t); - - // Option 2: always += speed - // speed is 0 if we just started after idle, so always use max for best results - float speed = Mathf.Max(start.movementSpeed, goal.movementSpeed); - return Vector3.MoveTowards(currentPosition, goal.localPosition, speed * Time.deltaTime); - } - - return currentPosition; - } - - Quaternion InterpolateRotation(DataPoint start, DataPoint goal, Quaternion defaultRotation) - { - if (!interpolateRotation) - return defaultRotation; - - if (start.localRotation != goal.localRotation) - { - float t = CurrentInterpolationFactor(start, goal); - return Quaternion.Slerp(start.localRotation, goal.localRotation, t); - } - - return defaultRotation; - } - - Vector3 InterpolateScale(DataPoint start, DataPoint goal, Vector3 currentScale) - { - if (!interpolateScale) - return currentScale; - - if (start.localScale != goal.localScale) - { - float t = CurrentInterpolationFactor(start, goal); - return Vector3.Lerp(start.localScale, goal.localScale, t); - } - - return currentScale; - } - - static float CurrentInterpolationFactor(DataPoint start, DataPoint goal) - { - if (start.isValid) - { - float difference = goal.timeStamp - start.timeStamp; - - // the moment we get 'goal', 'start' is supposed to start, so elapsed time is based on: - float elapsed = Time.time - goal.timeStamp; - - // avoid NaN - return difference > 0 ? elapsed / difference : 1; - } - return 1; - } - - #region Debug Gizmos - - // draw the data points for easier debugging - void OnDrawGizmos() - { - // draw start and goal points and a line between them - if (start.localPosition != goal.localPosition) - { - DrawDataPointGizmo(start, Color.yellow); - DrawDataPointGizmo(goal, Color.green); - DrawLineBetweenDataPoints(start, goal, Color.cyan); - } - } - - static void DrawDataPointGizmo(DataPoint data, Color color) - { - // use a little offset because transform.localPosition might be in the ground in many cases - Vector3 offset = Vector3.up * 0.01f; - - // draw position - Gizmos.color = color; - Gizmos.DrawSphere(data.localPosition + offset, 0.5f); - - // draw forward and up like unity move tool - Gizmos.color = Color.blue; - Gizmos.DrawRay(data.localPosition + offset, data.localRotation * Vector3.forward); - Gizmos.color = Color.green; - Gizmos.DrawRay(data.localPosition + offset, data.localRotation * Vector3.up); - } - - static void DrawLineBetweenDataPoints(DataPoint data1, DataPoint data2, Color color) - { - Gizmos.color = color; - Gizmos.DrawLine(data1.localPosition, data2.localPosition); - } - - #endregion - } -} diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformBase.cs.meta b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformBase.cs.meta deleted file mode 100644 index d737bed83a..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ea7c690c4fbf8c4439726f4c62eda6d3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformChild.cs b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformChild.cs deleted file mode 100644 index 4494bd1164..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformChild.cs +++ /dev/null @@ -1,18 +0,0 @@ -using UnityEngine; - -namespace Mirror.Experimental -{ - /// - /// A component to synchronize the position of child transforms of networked objects. - /// There must be a NetworkTransform on the root object of the hierarchy. There can be multiple NetworkTransformChild components on an object. This does not use physics for synchronization, it simply synchronizes the localPosition and localRotation of the child transform and lerps towards the recieved values. - /// - [AddComponentMenu("Network/Experimental/NetworkTransformChildExperimentalExperimental")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkTransformChild.html")] - public class NetworkTransformChild : NetworkTransformBase - { - [Header("Target")] - public Transform target; - - protected override Transform targetTransform => target; - } -} diff --git a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformChild.cs.meta b/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformChild.cs.meta deleted file mode 100644 index 30f0d890b6..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/Experimental/NetworkTransformChild.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f65214da13a861f4a8ae309d3daea1c6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Components/GUIConsole.cs b/Assets/ImportedAssets/Mirror/Components/GUIConsole.cs new file mode 100644 index 0000000000..7055fe1ba4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/GUIConsole.cs @@ -0,0 +1,133 @@ +// People should be able to see and report errors to the developer very easily. +// +// Unity's Developer Console only works in development builds and it only shows +// errors. This class provides a console that works in all builds and also shows +// log and warnings in development builds. +// +// Note: we don't include the stack trace, because that can also be grabbed from +// the log files if needed. +// +// Note: there is no 'hide' button because we DO want people to see those errors +// and report them back to us. +// +// Note: normal Debug.Log messages can be shown by building in Debug/Development +// mode. +using UnityEngine; +using System.Collections.Generic; + +namespace Mirror +{ + struct LogEntry + { + public string message; + public LogType type; + + public LogEntry(string message, LogType type) + { + this.message = message; + this.type = type; + } + } + + public class GUIConsole : MonoBehaviour + { + public int height = 80; + public int offsetY = 40; + + // only keep the recent 'n' entries. otherwise memory would grow forever + // and drawing would get slower and slower. + public int maxLogCount = 50; + + // Unity Editor has the Console window, we don't need to show it there. + // unless for testing, so keep it as option. + public bool showInEditor = false; + + // log as queue so we can remove the first entry easily + readonly Queue log = new Queue(); + + // hotkey to show/hide at runtime for easier debugging + // (sometimes we need to temporarily hide/show it) + // Default is BackQuote, because F keys are already assigned in browsers + [Tooltip("Hotkey to show/hide the console at runtime\nBack Quote is usually on the left above Tab\nChange with caution - F keys are generally already taken in Browsers")] + public KeyCode hotKey = KeyCode.BackQuote; + + // GUI + bool visible; + Vector2 scroll = Vector2.zero; + + // only show at runtime, or if showInEditor is enabled + bool show => !Application.isEditor || showInEditor; + + void Awake() + { + // only show at runtime, or if showInEditor is enabled + if (show) + Application.logMessageReceived += OnLog; + } + + // OnLog logs everything, even Debug.Log messages in release builds + // => this makes a lot of things easier. e.g. addon initialization logs. + // => it's really better to have than not to have those + void OnLog(string message, string stackTrace, LogType type) + { + // is this important? + // => always show exceptions & errors + // => usually a good idea to show warnings too, otherwise it's too + // easy to miss OnDeserialize warnings etc. in builds + bool isImportant = type == LogType.Error || type == LogType.Exception || type == LogType.Warning; + + // use stack trace only if important + // (otherwise users would have to find and search the log file. + // seeing it in the console directly is way easier to deal with.) + // => only add \n if stack trace is available (only in debug builds) + if (isImportant && !string.IsNullOrWhiteSpace(stackTrace)) + message += $"\n{stackTrace}"; + + // add to queue + log.Enqueue(new LogEntry(message, type)); + + // respect max entries + if (log.Count > maxLogCount) + log.Dequeue(); + + // become visible if it was important + // (no need to become visible for regular log. let the user decide.) + if (isImportant) + visible = true; + + // auto scroll + scroll.y = float.MaxValue; + } + + void Update() + { + if (show && Input.GetKeyDown(hotKey)) + visible = !visible; + } + + void OnGUI() + { + if (!visible) return; + + // If this offset is changed, also change width in NetworkManagerHUD::OnGUI + int offsetX = 300 + 20; + + GUILayout.BeginArea(new Rect(offsetX, offsetY, Screen.width - offsetX - 10, height)); + + scroll = GUILayout.BeginScrollView(scroll, "Box", GUILayout.Width(Screen.width - offsetX - 10), GUILayout.Height(height)); + foreach (LogEntry entry in log) + { + if (entry.type == LogType.Error || entry.type == LogType.Exception) + GUI.color = Color.red; + else if (entry.type == LogType.Warning) + GUI.color = Color.yellow; + + GUILayout.Label(entry.message); + GUI.color = Color.white; + } + GUILayout.EndScrollView(); + + GUILayout.EndArea(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/GUIConsole.cs.meta b/Assets/ImportedAssets/Mirror/Components/GUIConsole.cs.meta new file mode 100644 index 0000000000..a3a0139a8a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/GUIConsole.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 9021b6cc314944290986ab6feb48db79 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/GUIConsole.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement.meta new file mode 100644 index 0000000000..9b1f7466eb --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c66f27e006ab94253b39a55a3b213651 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance.meta new file mode 100644 index 0000000000..98479020df --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fa4cbc6b9c584db4971985cb9f369077 +timeCreated: 1613110605 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs new file mode 100644 index 0000000000..654996191b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs @@ -0,0 +1,90 @@ +// straight forward Vector3.Distance based interest management. +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Distance/Distance Interest Management")] + public class DistanceInterestManagement : InterestManagement + { + [Tooltip("The maximum range that objects will be visible at. Add DistanceInterestManagementCustomRange onto NetworkIdentities for custom ranges.")] + public int visRange = 500; + + [Tooltip("Rebuild all every 'rebuildInterval' seconds.")] + public float rebuildInterval = 1; + double lastRebuildTime; + + // cache custom ranges to avoid runtime TryGetComponent lookups + readonly Dictionary CustomRanges = new Dictionary(); + + // helper function to get vis range for a given object, or default. + [ServerCallback] + int GetVisRange(NetworkIdentity identity) + { + return CustomRanges.TryGetValue(identity, out DistanceInterestManagementCustomRange custom) ? custom.visRange : visRange; + } + + [ServerCallback] + public override void ResetState() + { + lastRebuildTime = 0D; + CustomRanges.Clear(); + } + + public override void OnSpawned(NetworkIdentity identity) + { + if (identity.TryGetComponent(out DistanceInterestManagementCustomRange custom)) + CustomRanges[identity] = custom; + } + + public override void OnDestroyed(NetworkIdentity identity) + { + CustomRanges.Remove(identity); + } + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + int range = GetVisRange(identity); + return Vector3.Distance(identity.transform.position, newObserver.identity.transform.position) < range; + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + // cache range and .transform because both call GetComponent. + int range = GetVisRange(identity); + Vector3 position = identity.transform.position; + + // brute force distance check + // -> only player connections can be observers, so it's enough if we + // go through all connections instead of all spawned identities. + // -> compared to UNET's sphere cast checking, this one is orders of + // magnitude faster. if we have 10k monsters and run a sphere + // cast 10k times, we will see a noticeable lag even with physics + // layers. but checking to every connection is fast. + foreach (NetworkConnectionToClient conn in NetworkServer.connections.Values) + { + // authenticated and joined world with a player? + if (conn != null && conn.isAuthenticated && conn.identity != null) + { + // check distance + if (Vector3.Distance(conn.identity.transform.position, position) < range) + { + newObservers.Add(conn); + } + } + } + } + + // internal so we can update from tests + [ServerCallback] + internal void Update() + { + // rebuild all spawned NetworkIdentity's observers every interval + if (NetworkTime.localTime >= lastRebuildTime + rebuildInterval) + { + RebuildAll(); + lastRebuildTime = NetworkTime.localTime; + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs.meta new file mode 100644 index 0000000000..83bb4b2500 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8f60becab051427fbdd3c8ac9ab4712b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs new file mode 100644 index 0000000000..12556e5fe4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs @@ -0,0 +1,15 @@ +// add this to NetworkIdentities for custom range if needed. +// only works with DistanceInterestManagement. +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [AddComponentMenu("Network/ Interest Management/ Distance/Distance Custom Range")] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public class DistanceInterestManagementCustomRange : NetworkBehaviour + { + [Tooltip("The maximum range that objects will be visible at.")] + public int visRange = 100; + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs.meta new file mode 100644 index 0000000000..5b027777bf --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: b2e242ee38a14076a39934172a19079b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match.meta new file mode 100644 index 0000000000..e429883464 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5eca5245ae6bb460e9a92f7e14d5493a +timeCreated: 1622649517 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs new file mode 100644 index 0000000000..d741d0c79b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Match/Match Interest Management")] + public class MatchInterestManagement : InterestManagement + { + [Header("Diagnostics")] + [ReadOnly, SerializeField] + internal ushort matchCount; + + readonly Dictionary> matchObjects = + new Dictionary>(); + + readonly HashSet dirtyMatches = new HashSet(); + + // LateUpdate so that all spawns/despawns/changes are done + [ServerCallback] + void LateUpdate() + { + // Rebuild all dirty matches + // dirtyMatches will be empty if no matches changed members + // by spawning or destroying or changing matchId in this frame. + foreach (Guid dirtyMatch in dirtyMatches) + { + // rebuild always, even if matchObjects[dirtyMatch] is empty. + // Players might have left the match, but they may still be spawned. + RebuildMatchObservers(dirtyMatch); + + // clean up empty entries in the dict + if (matchObjects[dirtyMatch].Count == 0) + matchObjects.Remove(dirtyMatch); + } + + dirtyMatches.Clear(); + + matchCount = (ushort)matchObjects.Count; + } + + [ServerCallback] + void RebuildMatchObservers(Guid matchId) + { + foreach (NetworkMatch networkMatch in matchObjects[matchId]) + if (networkMatch.netIdentity != null) + NetworkServer.RebuildObservers(networkMatch.netIdentity, false); + } + + // called by NetworkMatch.matchId setter + [ServerCallback] + internal void OnMatchChanged(NetworkMatch networkMatch, Guid oldMatch) + { + // This object is in a new match so observers in the prior match + // and the new match need to rebuild their respective observers lists. + + // Remove this object from the hashset of the match it just left + // Guid.Empty is never a valid matchId + if (oldMatch != Guid.Empty) + { + dirtyMatches.Add(oldMatch); + matchObjects[oldMatch].Remove(networkMatch); + } + + // Guid.Empty is never a valid matchId + if (networkMatch.matchId == Guid.Empty) + return; + + dirtyMatches.Add(networkMatch.matchId); + + // Make sure this new match is in the dictionary + if (!matchObjects.ContainsKey(networkMatch.matchId)) + matchObjects[networkMatch.matchId] = new HashSet(); + + // Add this object to the hashset of the new match + matchObjects[networkMatch.matchId].Add(networkMatch); + } + + [ServerCallback] + public override void OnSpawned(NetworkIdentity identity) + { + if (!identity.TryGetComponent(out NetworkMatch networkMatch)) + return; + + Guid networkMatchId = networkMatch.matchId; + + // Guid.Empty is never a valid matchId...do not add to matchObjects collection + if (networkMatchId == Guid.Empty) + return; + + // Debug.Log($"MatchInterestManagement.OnSpawned({identity.name}) currentMatch: {currentMatch}"); + if (!matchObjects.TryGetValue(networkMatchId, out HashSet objects)) + { + objects = new HashSet(); + matchObjects.Add(networkMatchId, objects); + } + + objects.Add(networkMatch); + + // Match ID could have been set in NetworkBehaviour::OnStartServer on this object. + // Since that's after OnCheckObserver is called it would be missed, so force Rebuild here. + // Add the current match to dirtyMatches for LateUpdate to rebuild it. + dirtyMatches.Add(networkMatchId); + } + + [ServerCallback] + public override void OnDestroyed(NetworkIdentity identity) + { + // Don't RebuildSceneObservers here - that will happen in LateUpdate. + // Multiple objects could be destroyed in same frame and we don't + // want to rebuild for each one...let LateUpdate do it once. + // We must add the current match to dirtyMatches for LateUpdate to rebuild it. + if (identity.TryGetComponent(out NetworkMatch currentMatch)) + { + if (currentMatch.matchId != Guid.Empty && + matchObjects.TryGetValue(currentMatch.matchId, out HashSet objects) && + objects.Remove(currentMatch)) + dirtyMatches.Add(currentMatch.matchId); + } + } + + [ServerCallback] + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + // Never observed if no NetworkMatch component + if (!identity.TryGetComponent(out NetworkMatch identityNetworkMatch)) + return false; + + // Guid.Empty is never a valid matchId + if (identityNetworkMatch.matchId == Guid.Empty) + return false; + + // Never observed if no NetworkMatch component + if (!newObserver.identity.TryGetComponent(out NetworkMatch newObserverNetworkMatch)) + return false; + + // Guid.Empty is never a valid matchId + if (newObserverNetworkMatch.matchId == Guid.Empty) + return false; + + return identityNetworkMatch.matchId == newObserverNetworkMatch.matchId; + } + + [ServerCallback] + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + if (!identity.TryGetComponent(out NetworkMatch networkMatch)) + return; + + // Guid.Empty is never a valid matchId + if (networkMatch.matchId == Guid.Empty) + return; + + // Abort if this match hasn't been created yet by OnSpawned or OnMatchChanged + if (!matchObjects.TryGetValue(networkMatch.matchId, out HashSet objects)) + return; + + // Add everything in the hashset for this object's current match + foreach (NetworkMatch netMatch in objects) + if (netMatch.netIdentity != null && netMatch.netIdentity.connectionToClient != null) + newObservers.Add(netMatch.netIdentity.connectionToClient); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs.meta new file mode 100644 index 0000000000..fb5a900851 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: d09f5c8bf2f4747b7a9284ef5d9ce2a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs new file mode 100644 index 0000000000..0d55fd015a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs @@ -0,0 +1,42 @@ +// simple component that holds match information +using System; +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [AddComponentMenu("Network/ Interest Management/ Match/Network Match")] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public class NetworkMatch : NetworkBehaviour + { + Guid _matchId; + +#pragma warning disable IDE0052 // Suppress warning for unused field...this is for debugging purposes + [SerializeField, ReadOnly] + [Tooltip("Match ID is shown here on server for debugging purposes.")] + string MatchID = string.Empty; +#pragma warning restore IDE0052 + + ///Set this to the same value on all networked objects that belong to a given match + public Guid matchId + { + get => _matchId; + set + { + if (!NetworkServer.active) + throw new InvalidOperationException("matchId can only be set at runtime on active server"); + + if (_matchId == value) + return; + + Guid oldMatch = _matchId; + _matchId = value; + MatchID = value.ToString(); + + // Only inform the AOI if this netIdentity has been spawned (isServer) and only if using a MatchInterestManagement + if (isServer && NetworkServer.aoi is MatchInterestManagement matchInterestManagement) + matchInterestManagement.OnMatchChanged(this, oldMatch); + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs.meta new file mode 100644 index 0000000000..76b705d51c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 5d17e718851449a6879986e45c458fb7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene.meta new file mode 100644 index 0000000000..28b469fe3e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7655d309a46a4bd4860edf964228b3f6 +timeCreated: 1622649517 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs new file mode 100644 index 0000000000..28e5ebabb3 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Scene/Scene Interest Management")] + public class SceneInterestManagement : InterestManagement + { + // Use Scene instead of string scene.name because when additively + // loading multiples of a subscene the name won't be unique + readonly Dictionary> sceneObjects = + new Dictionary>(); + + readonly Dictionary lastObjectScene = + new Dictionary(); + + HashSet dirtyScenes = new HashSet(); + + [ServerCallback] + public override void OnSpawned(NetworkIdentity identity) + { + Scene currentScene = identity.gameObject.scene; + lastObjectScene[identity] = currentScene; + // Debug.Log($"SceneInterestManagement.OnSpawned({identity.name}) currentScene: {currentScene}"); + if (!sceneObjects.TryGetValue(currentScene, out HashSet objects)) + { + objects = new HashSet(); + sceneObjects.Add(currentScene, objects); + } + + objects.Add(identity); + } + + [ServerCallback] + public override void OnDestroyed(NetworkIdentity identity) + { + // Don't RebuildSceneObservers here - that will happen in Update. + // Multiple objects could be destroyed in same frame and we don't + // want to rebuild for each one...let Update do it once. + // We must add the current scene to dirtyScenes for Update to rebuild it. + if (lastObjectScene.TryGetValue(identity, out Scene currentScene)) + { + lastObjectScene.Remove(identity); + if (sceneObjects.TryGetValue(currentScene, out HashSet objects) && objects.Remove(identity)) + dirtyScenes.Add(currentScene); + } + } + + // internal so we can update from tests + [ServerCallback] + internal void Update() + { + // for each spawned: + // if scene changed: + // add previous to dirty + // add new to dirty + foreach (NetworkIdentity identity in NetworkServer.spawned.Values) + { + if (!lastObjectScene.TryGetValue(identity, out Scene currentScene)) + continue; + + Scene newScene = identity.gameObject.scene; + if (newScene == currentScene) + continue; + + // Mark new/old scenes as dirty so they get rebuilt + dirtyScenes.Add(currentScene); + dirtyScenes.Add(newScene); + + // This object is in a new scene so observers in the prior scene + // and the new scene need to rebuild their respective observers lists. + + // Remove this object from the hashset of the scene it just left + sceneObjects[currentScene].Remove(identity); + + // Set this to the new scene this object just entered + lastObjectScene[identity] = newScene; + + // Make sure this new scene is in the dictionary + if (!sceneObjects.ContainsKey(newScene)) + sceneObjects.Add(newScene, new HashSet()); + + // Add this object to the hashset of the new scene + sceneObjects[newScene].Add(identity); + } + + // rebuild all dirty scenes + foreach (Scene dirtyScene in dirtyScenes) + RebuildSceneObservers(dirtyScene); + + dirtyScenes.Clear(); + } + + void RebuildSceneObservers(Scene scene) + { + foreach (NetworkIdentity netIdentity in sceneObjects[scene]) + if (netIdentity != null) + NetworkServer.RebuildObservers(netIdentity, false); + } + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + return identity.gameObject.scene == newObserver.identity.gameObject.scene; + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + if (!sceneObjects.TryGetValue(identity.gameObject.scene, out HashSet objects)) + return; + + // Add everything in the hashset for this object's current scene + foreach (NetworkIdentity networkIdentity in objects) + if (networkIdentity != null && networkIdentity.connectionToClient != null) + newObservers.Add(networkIdentity.connectionToClient); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs.meta new file mode 100644 index 0000000000..48534f5d20 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: b979f26c95d34324ba005bfacfa9c4fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing.meta new file mode 100644 index 0000000000..00f5cd6001 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cfa12b73503344d49b398b01bcb07967 +timeCreated: 1613110634 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs new file mode 100644 index 0000000000..d55771357d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs @@ -0,0 +1,104 @@ +// Grid2D from uMMORPG: get/set values of type T at any point +// -> not named 'Grid' because Unity already has a Grid type. causes warnings. +// -> struct to avoid memory indirection. it's accessed a lot. +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // struct to avoid memory indirection. it's accessed a lot. + public struct Grid2D + { + // the grid + // note that we never remove old keys. + // => over time, HashSets will be allocated for every possible + // grid position in the world + // => Clear() doesn't clear them so we don't constantly reallocate the + // entries when populating the grid in every Update() call + // => makes the code a lot easier too + // => this is FINE because in the worst case, every grid position in the + // game world is filled with a player anyway! + readonly Dictionary> grid; + + // cache a 9 neighbor grid of vector2 offsets so we can use them more easily + readonly Vector2Int[] neighbourOffsets; + + public Grid2D(int initialCapacity) + { + grid = new Dictionary>(initialCapacity); + + neighbourOffsets = new[] { + Vector2Int.up, + Vector2Int.up + Vector2Int.left, + Vector2Int.up + Vector2Int.right, + Vector2Int.left, + Vector2Int.zero, + Vector2Int.right, + Vector2Int.down, + Vector2Int.down + Vector2Int.left, + Vector2Int.down + Vector2Int.right + }; + } + + // helper function so we can add an entry without worrying + public void Add(Vector2Int position, T value) + { + // initialize set in grid if it's not in there yet + if (!grid.TryGetValue(position, out HashSet hashSet)) + { + // each grid entry may hold hundreds of entities. + // let's create the HashSet with a large initial capacity + // in order to avoid resizing & allocations. +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have "new HashSet(capacity)" yet + hashSet = new HashSet(); +#else + hashSet = new HashSet(128); +#endif + grid[position] = hashSet; + } + + // add to it + hashSet.Add(value); + } + + // helper function to get set at position without worrying + // -> result is passed as parameter to avoid allocations + // -> result is not cleared before. this allows us to pass the HashSet from + // GetWithNeighbours and avoid .UnionWith which is very expensive. + void GetAt(Vector2Int position, HashSet result) + { + // return the set at position + if (grid.TryGetValue(position, out HashSet hashSet)) + { + foreach (T entry in hashSet) + result.Add(entry); + } + } + + // helper function to get at position and it's 8 neighbors without worrying + // -> result is passed as parameter to avoid allocations + public void GetWithNeighbours(Vector2Int position, HashSet result) + { + // clear result first + result.Clear(); + + // add neighbours + foreach (Vector2Int offset in neighbourOffsets) + GetAt(position + offset, result); + } + + // clear: clears the whole grid + // IMPORTANT: we already allocated HashSets and don't want to do + // reallocate every single update when we rebuild the grid. + // => so simply remove each position's entries, but keep + // every position in there + // => see 'grid' comments above! + // => named ClearNonAlloc to make it more obvious! + public void ClearNonAlloc() + { + foreach (HashSet hashSet in grid.Values) + hashSet.Clear(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs.meta new file mode 100644 index 0000000000..a57b2fb6df --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 7c5232a4d2854116a35d52b80ec07752 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid3D.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid3D.cs new file mode 100644 index 0000000000..64ca4975dd --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid3D.cs @@ -0,0 +1,106 @@ +// Grid3D based on Grid2D +// -> not named 'Grid' because Unity already has a Grid type. causes warnings. +// -> struct to avoid memory indirection. it's accessed a lot. +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // struct to avoid memory indirection. it's accessed a lot. + public struct Grid3D + { + // the grid + // note that we never remove old keys. + // => over time, HashSets will be allocated for every possible + // grid position in the world + // => Clear() doesn't clear them so we don't constantly reallocate the + // entries when populating the grid in every Update() call + // => makes the code a lot easier too + // => this is FINE because in the worst case, every grid position in the + // game world is filled with a player anyway! + readonly Dictionary> grid; + + // cache a 9 x 3 neighbor grid of vector3 offsets so we can use them more easily + readonly Vector3Int[] neighbourOffsets; + + public Grid3D(int initialCapacity) + { + grid = new Dictionary>(initialCapacity); + + neighbourOffsets = new Vector3Int[9 * 3]; + int i = 0; + for (int x = -1; x <= 1; x++) + { + for (int y = -1; y <= 1; y++) + { + for (int z = -1; z <= 1; z++) + { + neighbourOffsets[i] = new Vector3Int(x, y, z); + i += 1; + } + } + } + } + + // helper function so we can add an entry without worrying + public void Add(Vector3Int position, T value) + { + // initialize set in grid if it's not in there yet + if (!grid.TryGetValue(position, out HashSet hashSet)) + { + // each grid entry may hold hundreds of entities. + // let's create the HashSet with a large initial capacity + // in order to avoid resizing & allocations. +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have "new HashSet(capacity)" yet + hashSet = new HashSet(); +#else + hashSet = new HashSet(128); +#endif + grid[position] = hashSet; + } + + // add to it + hashSet.Add(value); + } + + // helper function to get set at position without worrying + // -> result is passed as parameter to avoid allocations + // -> result is not cleared before. this allows us to pass the HashSet from + // GetWithNeighbours and avoid .UnionWith which is very expensive. + void GetAt(Vector3Int position, HashSet result) + { + // return the set at position + if (grid.TryGetValue(position, out HashSet hashSet)) + { + foreach (T entry in hashSet) + result.Add(entry); + } + } + + // helper function to get at position and it's 8 neighbors without worrying + // -> result is passed as parameter to avoid allocations + public void GetWithNeighbours(Vector3Int position, HashSet result) + { + // clear result first + result.Clear(); + + // add neighbours + foreach (Vector3Int offset in neighbourOffsets) + GetAt(position + offset, result); + } + + // clear: clears the whole grid + // IMPORTANT: we already allocated HashSets and don't want to do + // reallocate every single update when we rebuild the grid. + // => so simply remove each position's entries, but keep + // every position in there + // => see 'grid' comments above! + // => named ClearNonAlloc to make it more obvious! + public void ClearNonAlloc() + { + foreach (HashSet hashSet in grid.Values) + hashSet.Clear(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid3D.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid3D.cs.meta new file mode 100644 index 0000000000..08a0ab1cae --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid3D.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b157c08313c64752b0856469b1b70771 +timeCreated: 1713533175 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/Grid3D.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashing3DInterestManagement.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashing3DInterestManagement.cs new file mode 100644 index 0000000000..1953de7e2f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashing3DInterestManagement.cs @@ -0,0 +1,146 @@ +// extremely fast spatial hashing interest management based on uMMORPG GridChecker. +// => 30x faster in initial tests +// => scales way higher +// checks on three dimensions (XYZ) which includes the vertical axes. +// this is slower than XY checking for regular spatial hashing. +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Spatial Hash/Spatial Hashing Interest Management")] + public class SpatialHashing3DInterestManagement : InterestManagement + { + [Tooltip("The maximum range that objects will be visible at.")] + public int visRange = 30; + + // we use a 9 neighbour grid. + // so we always see in a distance of 2 grids. + // for example, our own grid and then one on top / below / left / right. + // + // this means that grid resolution needs to be distance / 2. + // so for example, for distance = 30 we see 2 cells = 15 * 2 distance. + // + // on first sight, it seems we need distance / 3 (we see left/us/right). + // but that's not the case. + // resolution would be 10, and we only see 1 cell far, so 10+10=20. + public int resolution => visRange / 2; // same as XY because if XY is rotated 90 degree for 3D, it's still the same distance + + [Tooltip("Rebuild all every 'rebuildInterval' seconds.")] + public float rebuildInterval = 1; + double lastRebuildTime; + + [Header("Debug Settings")] + public bool showSlider; + + // the grid + // begin with a large capacity to avoid resizing & allocations. + Grid3D grid = new Grid3D(1024); + + // project 3d world position to grid position + Vector3Int ProjectToGrid(Vector3 position) => + Vector3Int.RoundToInt(position / resolution); + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + // calculate projected positions + Vector3Int projected = ProjectToGrid(identity.transform.position); + Vector3Int observerProjected = ProjectToGrid(newObserver.identity.transform.position); + + // distance needs to be at max one of the 8 neighbors, which is + // 1 for the direct neighbors + // 1.41 for the diagonal neighbors (= sqrt(2)) + // => use sqrMagnitude and '2' to avoid computations. same result. + return (projected - observerProjected).sqrMagnitude <= 2; // same as XY because if XY is rotated 90 degree for 3D, it's still the same distance + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + // add everyone in 9 neighbour grid + // -> pass observers to GetWithNeighbours directly to avoid allocations + // and expensive .UnionWith computations. + Vector3Int current = ProjectToGrid(identity.transform.position); + grid.GetWithNeighbours(current, newObservers); + } + + [ServerCallback] + public override void ResetState() + { + lastRebuildTime = 0D; + } + + // update everyone's position in the grid + // (internal so we can update from tests) + [ServerCallback] + internal void Update() + { + // NOTE: unlike Scene/MatchInterestManagement, this rebuilds ALL + // entities every INTERVAL. consider the other approach later. + + // IMPORTANT: refresh grid every update! + // => newly spawned entities get observers assigned via + // OnCheckObservers. this can happen any time and we don't want + // them broadcast to old (moved or destroyed) connections. + // => players do move all the time. we want them to always be in the + // correct grid position. + // => note that the actual 'rebuildall' doesn't need to happen all + // the time. + // NOTE: consider refreshing grid only every 'interval' too. but not + // for now. stability & correctness matter. + + // clear old grid results before we update everyone's position. + // (this way we get rid of destroyed connections automatically) + // + // NOTE: keeps allocated HashSets internally. + // clearing & populating every frame works without allocations + grid.ClearNonAlloc(); + + // put every connection into the grid at it's main player's position + // NOTE: player sees in a radius around him. NOT around his pet too. + foreach (NetworkConnectionToClient connection in NetworkServer.connections.Values) + { + // authenticated and joined world with a player? + if (connection.isAuthenticated && connection.identity != null) + { + // calculate current grid position + Vector3Int position = ProjectToGrid(connection.identity.transform.position); + + // put into grid + grid.Add(position, connection); + } + } + + // rebuild all spawned entities' observers every 'interval' + // this will call OnRebuildObservers which then returns the + // observers at grid[position] for each entity. + if (NetworkTime.localTime >= lastRebuildTime + rebuildInterval) + { + RebuildAll(); + lastRebuildTime = NetworkTime.localTime; + } + } + +// OnGUI allocates even if it does nothing. avoid in release. +#if UNITY_EDITOR || DEVELOPMENT_BUILD + // slider from dotsnet. it's nice to play around with in the benchmark + // demo. + void OnGUI() + { + if (!showSlider) return; + + // only show while server is running. not on client, etc. + if (!NetworkServer.active) return; + + int height = 30; + int width = 250; + GUILayout.BeginArea(new Rect(Screen.width / 2 - width / 2, Screen.height - height, width, height)); + GUILayout.BeginHorizontal("Box"); + GUILayout.Label("Radius:"); + visRange = Mathf.RoundToInt(GUILayout.HorizontalSlider(visRange, 0, 200, GUILayout.Width(150))); + GUILayout.Label(visRange.ToString()); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + } +#endif + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashing3DInterestManagement.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashing3DInterestManagement.cs.meta new file mode 100644 index 0000000000..0ec1e0c8a0 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashing3DInterestManagement.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 120b4d6121d94e0280cd2ec536b0ea8f +timeCreated: 1713534045 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashing3DInterestManagement.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs new file mode 100644 index 0000000000..0cb5e23139 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs @@ -0,0 +1,156 @@ +// extremely fast spatial hashing interest management based on uMMORPG GridChecker. +// => 30x faster in initial tests +// => scales way higher +// checks on two dimensions only(!), for example: XZ for 3D games or XY for 2D games. +// this is faster than XYZ checking but doesn't check vertical distance. +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Spatial Hash/Spatial Hashing Interest Management")] + public class SpatialHashingInterestManagement : InterestManagement + { + [Tooltip("The maximum range that objects will be visible at.")] + public int visRange = 30; + + // we use a 9 neighbour grid. + // so we always see in a distance of 2 grids. + // for example, our own grid and then one on top / below / left / right. + // + // this means that grid resolution needs to be distance / 2. + // so for example, for distance = 30 we see 2 cells = 15 * 2 distance. + // + // on first sight, it seems we need distance / 3 (we see left/us/right). + // but that's not the case. + // resolution would be 10, and we only see 1 cell far, so 10+10=20. + public int resolution => visRange / 2; + + [Tooltip("Rebuild all every 'rebuildInterval' seconds.")] + public float rebuildInterval = 1; + double lastRebuildTime; + + public enum CheckMethod + { + XZ_FOR_3D, + XY_FOR_2D + } + [Tooltip("Spatial Hashing supports 3D (XZ) and 2D (XY) games.")] + public CheckMethod checkMethod = CheckMethod.XZ_FOR_3D; + + [Header("Debug Settings")] + public bool showSlider; + + // the grid + // begin with a large capacity to avoid resizing & allocations. + Grid2D grid = new Grid2D(1024); + + // project 3d world position to grid position + Vector2Int ProjectToGrid(Vector3 position) => + checkMethod == CheckMethod.XZ_FOR_3D + ? Vector2Int.RoundToInt(new Vector2(position.x, position.z) / resolution) + : Vector2Int.RoundToInt(new Vector2(position.x, position.y) / resolution); + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + // calculate projected positions + Vector2Int projected = ProjectToGrid(identity.transform.position); + Vector2Int observerProjected = ProjectToGrid(newObserver.identity.transform.position); + + // distance needs to be at max one of the 8 neighbors, which is + // 1 for the direct neighbors + // 1.41 for the diagonal neighbors (= sqrt(2)) + // => use sqrMagnitude and '2' to avoid computations. same result. + return (projected - observerProjected).sqrMagnitude <= 2; + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + // add everyone in 9 neighbour grid + // -> pass observers to GetWithNeighbours directly to avoid allocations + // and expensive .UnionWith computations. + Vector2Int current = ProjectToGrid(identity.transform.position); + grid.GetWithNeighbours(current, newObservers); + } + + [ServerCallback] + public override void ResetState() + { + lastRebuildTime = 0D; + } + + // update everyone's position in the grid + // (internal so we can update from tests) + [ServerCallback] + internal void Update() + { + // NOTE: unlike Scene/MatchInterestManagement, this rebuilds ALL + // entities every INTERVAL. consider the other approach later. + + // IMPORTANT: refresh grid every update! + // => newly spawned entities get observers assigned via + // OnCheckObservers. this can happen any time and we don't want + // them broadcast to old (moved or destroyed) connections. + // => players do move all the time. we want them to always be in the + // correct grid position. + // => note that the actual 'rebuildall' doesn't need to happen all + // the time. + // NOTE: consider refreshing grid only every 'interval' too. but not + // for now. stability & correctness matter. + + // clear old grid results before we update everyone's position. + // (this way we get rid of destroyed connections automatically) + // + // NOTE: keeps allocated HashSets internally. + // clearing & populating every frame works without allocations + grid.ClearNonAlloc(); + + // put every connection into the grid at it's main player's position + // NOTE: player sees in a radius around him. NOT around his pet too. + foreach (NetworkConnectionToClient connection in NetworkServer.connections.Values) + { + // authenticated and joined world with a player? + if (connection.isAuthenticated && connection.identity != null) + { + // calculate current grid position + Vector2Int position = ProjectToGrid(connection.identity.transform.position); + + // put into grid + grid.Add(position, connection); + } + } + + // rebuild all spawned entities' observers every 'interval' + // this will call OnRebuildObservers which then returns the + // observers at grid[position] for each entity. + if (NetworkTime.localTime >= lastRebuildTime + rebuildInterval) + { + RebuildAll(); + lastRebuildTime = NetworkTime.localTime; + } + } + +// OnGUI allocates even if it does nothing. avoid in release. +#if UNITY_EDITOR || DEVELOPMENT_BUILD + // slider from dotsnet. it's nice to play around with in the benchmark + // demo. + void OnGUI() + { + if (!showSlider) return; + + // only show while server is running. not on client, etc. + if (!NetworkServer.active) return; + + int height = 30; + int width = 250; + GUILayout.BeginArea(new Rect(Screen.width / 2 - width / 2, Screen.height - height, width, height)); + GUILayout.BeginHorizontal("Box"); + GUILayout.Label("Radius:"); + visRange = Mathf.RoundToInt(GUILayout.HorizontalSlider(visRange, 0, 200, GUILayout.Width(150))); + GUILayout.Label(visRange.ToString()); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + } +#endif + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs.meta new file mode 100644 index 0000000000..fdeb019464 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 39adc6e09d5544ed955a50ce8600355a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team.meta new file mode 100644 index 0000000000..fe40aa4985 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2d418e60072433b4bbebbf5f3a7de1bb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs new file mode 100644 index 0000000000..290eb06983 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs @@ -0,0 +1,39 @@ +// simple component that holds team information +using System; +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [AddComponentMenu("Network/ Interest Management/ Team/Network Team")] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public class NetworkTeam : NetworkBehaviour + { + [SerializeField] + [Tooltip("Set teamId on Server at runtime to the same value on all networked objects that belong to a given team")] + string _teamId; + + public string teamId + { + get => _teamId; + set + { + if (Application.IsPlaying(gameObject) && !NetworkServer.active) + throw new InvalidOperationException("teamId can only be set at runtime on active server"); + + if (_teamId == value) + return; + + string oldTeam = _teamId; + _teamId = value; + + //Only inform the AOI if this netIdentity has been spawned(isServer) and only if using a TeamInterestManagement + if (isServer && NetworkServer.aoi is TeamInterestManagement teamInterestManagement) + teamInterestManagement.OnTeamChanged(this, oldTeam); + } + } + + [Tooltip("When enabled this object is visible to all clients. Typically this would be true for player objects")] + public bool forceShown; + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs.meta new file mode 100644 index 0000000000..ffb17cd51e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 2576730625b1632468cbcbfe5e721f88 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs new file mode 100644 index 0000000000..cb5bdb7d90 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs @@ -0,0 +1,182 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Team/Team Interest Management")] + public class TeamInterestManagement : InterestManagement + { + readonly Dictionary> teamObjects = + new Dictionary>(); + + readonly HashSet dirtyTeams = new HashSet(); + + // LateUpdate so that all spawns/despawns/changes are done + [ServerCallback] + void LateUpdate() + { + // Rebuild all dirty teams + // dirtyTeams will be empty if no teams changed members + // by spawning or destroying or changing teamId in this frame. + foreach (string dirtyTeam in dirtyTeams) + { + // rebuild always, even if teamObjects[dirtyTeam] is empty. + // Players might have left the team, but they may still be spawned. + RebuildTeamObservers(dirtyTeam); + + // clean up empty entries in the dict + if (teamObjects[dirtyTeam].Count == 0) + teamObjects.Remove(dirtyTeam); + } + + dirtyTeams.Clear(); + } + + [ServerCallback] + void RebuildTeamObservers(string teamId) + { + foreach (NetworkTeam networkTeam in teamObjects[teamId]) + if (networkTeam.netIdentity != null) + NetworkServer.RebuildObservers(networkTeam.netIdentity, false); + } + + // called by NetworkTeam.teamId setter + [ServerCallback] + internal void OnTeamChanged(NetworkTeam networkTeam, string oldTeam) + { + // This object is in a new team so observers in the prior team + // and the new team need to rebuild their respective observers lists. + + // Remove this object from the hashset of the team it just left + // Null / Empty string is never a valid teamId + if (!string.IsNullOrWhiteSpace(oldTeam)) + { + dirtyTeams.Add(oldTeam); + teamObjects[oldTeam].Remove(networkTeam); + } + + // Null / Empty string is never a valid teamId + if (string.IsNullOrWhiteSpace(networkTeam.teamId)) + return; + + dirtyTeams.Add(networkTeam.teamId); + + // Make sure this new team is in the dictionary + if (!teamObjects.ContainsKey(networkTeam.teamId)) + teamObjects[networkTeam.teamId] = new HashSet(); + + // Add this object to the hashset of the new team + teamObjects[networkTeam.teamId].Add(networkTeam); + } + + [ServerCallback] + public override void OnSpawned(NetworkIdentity identity) + { + if (!identity.TryGetComponent(out NetworkTeam networkTeam)) + return; + + string networkTeamId = networkTeam.teamId; + + // Null / Empty string is never a valid teamId...do not add to teamObjects collection + if (string.IsNullOrWhiteSpace(networkTeamId)) + return; + + // Debug.Log($"TeamInterestManagement.OnSpawned({identity.name}) currentTeam: {currentTeam}"); + if (!teamObjects.TryGetValue(networkTeamId, out HashSet objects)) + { + objects = new HashSet(); + teamObjects.Add(networkTeamId, objects); + } + + objects.Add(networkTeam); + + // Team ID could have been set in NetworkBehaviour::OnStartServer on this object. + // Since that's after OnCheckObserver is called it would be missed, so force Rebuild here. + // Add the current team to dirtyTeames for LateUpdate to rebuild it. + dirtyTeams.Add(networkTeamId); + } + + [ServerCallback] + public override void OnDestroyed(NetworkIdentity identity) + { + // Don't RebuildSceneObservers here - that will happen in LateUpdate. + // Multiple objects could be destroyed in same frame and we don't + // want to rebuild for each one...let LateUpdate do it once. + // We must add the current team to dirtyTeames for LateUpdate to rebuild it. + if (identity.TryGetComponent(out NetworkTeam currentTeam)) + { + if (!string.IsNullOrWhiteSpace(currentTeam.teamId) && + teamObjects.TryGetValue(currentTeam.teamId, out HashSet objects) && + objects.Remove(currentTeam)) + dirtyTeams.Add(currentTeam.teamId); + } + } + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + // Always observed if no NetworkTeam component + if (!identity.TryGetComponent(out NetworkTeam identityNetworkTeam)) + return true; + + if (identityNetworkTeam.forceShown) + return true; + + // Null / Empty string is never a valid teamId + if (string.IsNullOrWhiteSpace(identityNetworkTeam.teamId)) + return false; + + // Always observed if no NetworkTeam component + if (!newObserver.identity.TryGetComponent(out NetworkTeam newObserverNetworkTeam)) + return true; + + // Null / Empty string is never a valid teamId + if (string.IsNullOrWhiteSpace(newObserverNetworkTeam.teamId)) + return false; + + //Debug.Log($"TeamInterestManagement.OnCheckObserver {identity.name} {identityNetworkTeam.teamId} | {newObserver.identity.name} {newObserverNetworkTeam.teamId}"); + + // Observed only if teamId's team + return identityNetworkTeam.teamId == newObserverNetworkTeam.teamId; + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + // If this object doesn't have a NetworkTeam then it's visible to all clients + if (!identity.TryGetComponent(out NetworkTeam networkTeam)) + { + AddAllConnections(newObservers); + return; + } + + // If this object has NetworkTeam and forceShown == true then it's visible to all clients + if (networkTeam.forceShown) + { + AddAllConnections(newObservers); + return; + } + + // Null / Empty string is never a valid teamId + if (string.IsNullOrWhiteSpace(networkTeam.teamId)) + return; + + // Abort if this team hasn't been created yet by OnSpawned or OnTeamChanged + if (!teamObjects.TryGetValue(networkTeam.teamId, out HashSet objects)) + return; + + // Add everything in the hashset for this object's current team + foreach (NetworkTeam netTeam in objects) + if (netTeam.netIdentity != null && netTeam.netIdentity.connectionToClient != null) + newObservers.Add(netTeam.netIdentity.connectionToClient); + } + + void AddAllConnections(HashSet newObservers) + { + foreach (NetworkConnectionToClient conn in NetworkServer.connections.Values) + { + // authenticated and joined world with a player? + if (conn != null && conn.isAuthenticated && conn.identity != null) + newObservers.Add(conn); + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs.meta b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs.meta new file mode 100644 index 0000000000..05c4f7a16d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: dceb9a7085758fd4590419ff5b14b636 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/LagCompensation.meta b/Assets/ImportedAssets/Mirror/Components/LagCompensation.meta new file mode 100644 index 0000000000..669a5b8c39 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/LagCompensation.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 00ac1d0527f234939aba22b4d7cbf280 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Components/LagCompensation/HistoryCollider.cs b/Assets/ImportedAssets/Mirror/Components/LagCompensation/HistoryCollider.cs new file mode 100644 index 0000000000..876eb18425 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/LagCompensation/HistoryCollider.cs @@ -0,0 +1,109 @@ +// Applies HistoryBounds to the physics world by projecting to a trigger Collider. +// This way we can use Physics.Raycast on it. +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [AddComponentMenu("Network/ Lag Compensation/ History Collider")] + public class HistoryCollider : MonoBehaviour + { + [Header("Components")] + [Tooltip("The object's actual collider. We need to know where it is, and how large it is.")] + public Collider actualCollider; + + [Tooltip("The helper collider that the history bounds are projected onto.\nNeeds to be added to a child GameObject to counter-rotate an axis aligned Bounding Box onto it.\nThis is only used by this component.")] + public BoxCollider boundsCollider; + + [Header("History")] + [Tooltip("Keep this many past bounds in the buffer. The larger this is, the further we can raycast into the past.\nMaximum time := historyAmount * captureInterval")] + public int boundsLimit = 8; + + [Tooltip("Gather N bounds at a time into a bucket for faster encapsulation. A factor of 2 will be twice as fast, etc.")] + public int boundsPerBucket = 2; + + [Tooltip("Capture bounds every 'captureInterval' seconds. Larger values will require fewer computations, but may not capture every small move.")] + public float captureInterval = 0.100f; // 100 ms + double lastCaptureTime = 0; + + [Header("Debug")] + public Color historyColor = new Color(1.0f, 0.5f, 0.0f, 1.0f); + public Color currentColor = Color.red; + + protected HistoryBounds history = null; + + protected virtual void Awake() + { + history = new HistoryBounds(boundsLimit, boundsPerBucket); + + // ensure colliders were set. + // bounds collider should always be a trigger. + if (actualCollider == null) Debug.LogError("HistoryCollider: actualCollider was not set."); + if (boundsCollider == null) Debug.LogError("HistoryCollider: boundsCollider was not set."); + if (boundsCollider.transform.parent != transform) Debug.LogError("HistoryCollider: boundsCollider must be a child of this GameObject."); + if (!boundsCollider.isTrigger) Debug.LogError("HistoryCollider: boundsCollider must be a trigger."); + } + + // capturing and projecting onto colliders should use physics update + protected virtual void FixedUpdate() + { + // capture current bounds every interval + if (NetworkTime.localTime >= lastCaptureTime + captureInterval) + { + lastCaptureTime = NetworkTime.localTime; + CaptureBounds(); + } + + // project bounds onto helper collider + ProjectBounds(); + } + + protected virtual void CaptureBounds() + { + // grab current collider bounds + // this is in world space coordinates, and axis aligned + // TODO double check + Bounds bounds = actualCollider.bounds; + + // insert into history + history.Insert(bounds); + } + + protected virtual void ProjectBounds() + { + // grab total collider encapsulating all of history + Bounds total = history.total; + + // don't assign empty bounds, this will throw a Unity warning + if (history.boundsCount == 0) return; + + // scale projection doesn't work yet. + // for now, don't allow scale changes. + if (transform.lossyScale != Vector3.one) + { + Debug.LogWarning($"HistoryCollider: {name}'s transform global scale must be (1,1,1)."); + return; + } + + // counter rotate the child collider against the gameobject's rotation. + // we need this to always be axis aligned. + boundsCollider.transform.localRotation = Quaternion.Inverse(transform.rotation); + + // project world space bounds to collider's local space + boundsCollider.center = boundsCollider.transform.InverseTransformPoint(total.center); + boundsCollider.size = total.size; // TODO projection? + } + + // TODO runtime drawing for debugging? + protected virtual void OnDrawGizmos() + { + // draw total bounds + Gizmos.color = historyColor; + Gizmos.DrawWireCube(history.total.center, history.total.size); + + // draw current bounds + Gizmos.color = currentColor; + Gizmos.DrawWireCube(actualCollider.bounds.center, actualCollider.bounds.size); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/LagCompensation/HistoryCollider.cs.meta b/Assets/ImportedAssets/Mirror/Components/LagCompensation/HistoryCollider.cs.meta new file mode 100644 index 0000000000..cc70baea4e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/LagCompensation/HistoryCollider.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: f5f2158d9776d4b569858f793be4da60 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/LagCompensation/HistoryCollider.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/LagCompensation/LagCompensator.cs b/Assets/ImportedAssets/Mirror/Components/LagCompensation/LagCompensator.cs new file mode 100644 index 0000000000..63669c0ed5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/LagCompensation/LagCompensator.cs @@ -0,0 +1,197 @@ +// Add this component to a Player object with collider. +// Automatically keeps a history for lag compensation. +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + public struct Capture3D : Capture + { + public double timestamp { get; set; } + public Vector3 position; + public Vector3 size; + + public Capture3D(double timestamp, Vector3 position, Vector3 size) + { + this.timestamp = timestamp; + this.position = position; + this.size = size; + } + + public void DrawGizmo() + { + Gizmos.DrawWireCube(position, size); + } + + public static Capture3D Interpolate(Capture3D from, Capture3D to, double t) => + new Capture3D( + 0, // interpolated snapshot is applied directly. don't need timestamps. + Vector3.LerpUnclamped(from.position, to.position, (float)t), + Vector3.LerpUnclamped(from.size, to.size, (float)t) + ); + + public override string ToString() => $"(time={timestamp} pos={position} size={size})"; + } + + [DisallowMultipleComponent] + [AddComponentMenu("Network/ Lag Compensation/ Lag Compensator")] + [HelpURL("https://mirror-networking.gitbook.io/docs/manual/general/lag-compensation")] + public class LagCompensator : NetworkBehaviour + { + [Header("Components")] + [Tooltip("The collider to keep a history of.")] + public Collider trackedCollider; // assign this in inspector + + [Header("Settings")] + public LagCompensationSettings lagCompensationSettings = new LagCompensationSettings(); + double lastCaptureTime; + + // lag compensation history of + readonly Queue> history = new Queue>(); + + [Header("Debugging")] + public Color historyColor = Color.white; + + [ServerCallback] + protected virtual void Update() + { + // capture lag compensation snapshots every interval. + // NetworkTime.localTime because Unity 2019 doesn't have 'double' time yet. + if (NetworkTime.localTime >= lastCaptureTime + lagCompensationSettings.captureInterval) + { + lastCaptureTime = NetworkTime.localTime; + Capture(); + } + } + + [ServerCallback] + protected virtual void Capture() + { + // capture current state + Capture3D capture = new Capture3D( + NetworkTime.localTime, + trackedCollider.bounds.center, + trackedCollider.bounds.size + ); + + // insert into history + LagCompensation.Insert(history, lagCompensationSettings.historyLimit, NetworkTime.localTime, capture); + } + + protected virtual void OnDrawGizmos() + { + // draw history + Gizmos.color = historyColor; + LagCompensation.DrawGizmos(history); + } + + // sampling //////////////////////////////////////////////////////////// + // sample the sub-tick (=interpolated) history of this object for a hit test. + // 'viewer' needs to be the player who fired! + // for example, if A fires at B, then call B.Sample(viewer, point, tolerance). + [ServerCallback] + public virtual bool Sample(NetworkConnectionToClient viewer, out Capture3D sample) + { + // never trust the client: estimate client time instead. + // https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking + // the estimation is very good. the error is as low as ~6ms for the demo. + // note that passing 'rtt' is fine: EstimateTime halves it to latency. + double estimatedTime = LagCompensation.EstimateTime(NetworkTime.localTime, viewer.rtt, NetworkClient.bufferTime); + + // sample the history to get the nearest snapshots around 'timestamp' + if (LagCompensation.Sample(history, estimatedTime, lagCompensationSettings.captureInterval, out Capture3D resultBefore, out Capture3D resultAfter, out double t)) + { + // interpolate to get a decent estimation at exactly 'timestamp' + sample = Capture3D.Interpolate(resultBefore, resultAfter, t); + return true; + } + else Debug.Log($"CmdClicked: history doesn't contain {estimatedTime:F3}"); + + sample = default; + return false; + } + + // convenience tests /////////////////////////////////////////////////// + // there are multiple different ways to check a hit against the sample: + // - raycasting + // - bounds.contains + // - increasing bounds by tolerance and checking contains + // - threshold to bounds.closestpoint + // let's offer a few solutions directly and see which users prefer. + + // bounds check: checks distance to closest point on bounds in history @ -rtt. + // 'viewer' needs to be the player who fired! + // for example, if A fires at B, then call B.Sample(viewer, point, tolerance). + // this is super simple and fast, but not 100% physically accurate since we don't raycast. + [ServerCallback] + public virtual bool BoundsCheck( + NetworkConnectionToClient viewer, + Vector3 hitPoint, + float toleranceDistance, + out float distance, + out Vector3 nearest) + { + // first, sample the history at -rtt of the viewer. + if (Sample(viewer, out Capture3D capture)) + { + // now that we know where the other player was at that time, + // we can see if the hit point was within tolerance of it. + // TODO consider rotations??? + // TODO consider original collider shape?? + Bounds bounds = new Bounds(capture.position, capture.size); + nearest = bounds.ClosestPoint(hitPoint); + distance = Vector3.Distance(nearest, hitPoint); + return distance <= toleranceDistance; + } + nearest = hitPoint; + distance = 0; + return false; + } + + // raycast check: creates a collider the sampled position and raycasts to hitPoint. + // 'viewer' needs to be the player who fired! + // for example, if A fires at B, then call B.Sample(viewer, point, tolerance). + // this is physically accurate (checks against walls etc.), with the cost + // of a runtime instantiation. + // + // originPoint: where the player fired the weapon. + // hitPoint: where the player's local raycast hit. + // tolerance: scale up the sampled collider by % in order to have a bit of a tolerance. + // 0 means no extra tolerance, 0.05 means 5% extra tolerance. + // layerMask: the layer mask to use for the raycast. + [ServerCallback] + public virtual bool RaycastCheck( + NetworkConnectionToClient viewer, + Vector3 originPoint, + Vector3 hitPoint, + float tolerancePercent, + int layerMask, + out RaycastHit hit) + { + // first, sample the history at -rtt of the viewer. + if (Sample(viewer, out Capture3D capture)) + { + // instantiate a real physics collider on demand. + // TODO rotation?? + // TODO different collier types?? + GameObject temp = new GameObject("LagCompensatorTest"); + temp.transform.position = capture.position; + BoxCollider tempCollider = temp.AddComponent(); + tempCollider.size = capture.size * (1 + tolerancePercent); + + // raycast + Vector3 direction = hitPoint - originPoint; + float maxDistance = direction.magnitude * 2; + bool result = Physics.Raycast(originPoint, direction, out hit, maxDistance, layerMask); + + // cleanup + Destroy(temp); + return result; + } + + hit = default; + return false; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/LagCompensation/LagCompensator.cs.meta b/Assets/ImportedAssets/Mirror/Components/LagCompensation/LagCompensator.cs.meta new file mode 100644 index 0000000000..583091a956 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/LagCompensation/LagCompensator.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a898831dd60c4cdfbfd9a6ea5702ed01 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/LagCompensation/LagCompensator.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/Mirror.Components.asmdef b/Assets/ImportedAssets/Mirror/Components/Mirror.Components.asmdef index a61c7dbf2d..90c360e6cb 100644 --- a/Assets/ImportedAssets/Mirror/Components/Mirror.Components.asmdef +++ b/Assets/ImportedAssets/Mirror/Components/Mirror.Components.asmdef @@ -1,14 +1,16 @@ { "name": "Mirror.Components", + "rootNamespace": "", "references": [ - "Mirror" + "GUID:30817c1a0e6d646d99c048fc403f5979" ], - "optionalUnityReferences": [], "includePlatforms": [], "excludePlatforms": [], - "allowUnsafeCode": false, + "allowUnsafeCode": true, "overrideReferences": false, "precompiledReferences": [], "autoReferenced": true, - "defineConstraints": [] + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Components/Mirror.Components.asmdef.meta b/Assets/ImportedAssets/Mirror/Components/Mirror.Components.asmdef.meta index 263b6f065d..55d11bd251 100644 --- a/Assets/ImportedAssets/Mirror/Components/Mirror.Components.asmdef.meta +++ b/Assets/ImportedAssets/Mirror/Components/Mirror.Components.asmdef.meta @@ -5,3 +5,10 @@ AssemblyDefinitionImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/Mirror.Components.asmdef + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkAnimator.cs b/Assets/ImportedAssets/Mirror/Components/NetworkAnimator.cs index 1924bf6eb7..657c28fa21 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkAnimator.cs +++ b/Assets/ImportedAssets/Mirror/Components/NetworkAnimator.cs @@ -11,15 +11,13 @@ namespace Mirror /// The animation of game objects can be networked by this component. There are two models of authority for networked movement: /// If the object has authority on the client, then it should be animated locally on the owning client. The animation state information will be sent from the owning client to the server, then broadcast to all of the other clients. This is common for player objects. /// If the object has authority on the server, then it should be animated on the server and state information will be sent to all clients. This is common for objects not related to a specific client, such as an enemy unit. - /// The NetworkAnimator synchronizes all animation parameters of the selected Animator. It does not automatically sychronize triggers. The function SetTrigger can by used by an object with authority to fire an animation trigger on other clients. + /// The NetworkAnimator synchronizes all animation parameters of the selected Animator. It does not automatically synchronize triggers. The function SetTrigger can by used by an object with authority to fire an animation trigger on other clients. /// - [AddComponentMenu("Network/NetworkAnimator")] - [RequireComponent(typeof(NetworkIdentity))] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkAnimator.html")] + // [RequireComponent(typeof(NetworkIdentity))] disabled to allow child NetworkBehaviours + [AddComponentMenu("Network/Network Animator")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-animator")] public class NetworkAnimator : NetworkBehaviour { - static readonly ILogger logger = LogFactory.GetLogger(typeof(NetworkAnimator)); - [Header("Authority")] [Tooltip("Set to true if animations come from owner client, set to false if animations always come from server")] public bool clientAuthority; @@ -32,6 +30,14 @@ public class NetworkAnimator : NetworkBehaviour [Tooltip("Animator that will have parameters synchronized")] public Animator animator; + /// + /// Syncs animator.speed. + /// Default to 1 because Animator.speed defaults to 1. + /// + [SyncVar(hook = nameof(OnAnimatorSpeedChanged))] + float animatorSpeed = 1f; + float previousSpeed = 1f; + // Note: not an object[] array because otherwise initialization is real annoying int[] lastIntParameters; float[] lastFloatParameters; @@ -42,7 +48,7 @@ public class NetworkAnimator : NetworkBehaviour int[] animationHash; int[] transitionHash; float[] layerWeight; - float nextSendTime; + double nextSendTime; bool SendMessagesAllowed { @@ -62,11 +68,11 @@ bool SendMessagesAllowed return true; } - return (hasAuthority && clientAuthority); + return (isOwned && clientAuthority); } } - void Awake() + void Initialize() { // store the animator parameters in a variable - the "Animator.parameters" getter allocates // a new parameter array every time it is accessed so we should avoid doing it in a loop @@ -82,6 +88,17 @@ void Awake() layerWeight = new float[animator.layerCount]; } + // fix https://github.com/MirrorNetworking/Mirror/issues/2810 + // both Awake and Enable need to initialize arrays. + // in case users call SetActive(false) -> SetActive(true). + void Awake() => Initialize(); + void OnEnable() => Initialize(); + + public virtual void Reset() + { + syncDirection = SyncDirection.ClientToServer; + } + void FixedUpdate() { if (!SendMessagesAllowed) @@ -101,12 +118,41 @@ void FixedUpdate() continue; } - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) { WriteParameters(writer); SendAnimationMessage(stateHash, normalizedTime, i, layerWeight[i], writer.ToArray()); } } + + CheckSpeed(); + } + + void CheckSpeed() + { + float newSpeed = animator.speed; + if (Mathf.Abs(previousSpeed - newSpeed) > 0.001f) + { + previousSpeed = newSpeed; + if (isServer) + { + animatorSpeed = newSpeed; + } + else if (isClient) + { + CmdSetAnimatorSpeed(newSpeed); + } + } + } + + void OnAnimatorSpeedChanged(float _, float value) + { + // skip if host or client with authority + // they will have already set the speed so don't set again + if (isServer || (isOwned && clientAuthority)) + return; + + animator.speed = value; } bool CheckAnimStateChanged(out int stateHash, out float normalizedTime, int layerId) @@ -154,12 +200,12 @@ bool CheckAnimStateChanged(out int stateHash, out float normalizedTime, int laye void CheckSendRate() { - float now = Time.time; + double now = NetworkTime.localTime; if (SendMessagesAllowed && syncInterval >= 0 && now > nextSendTime) { nextSendTime = now + syncInterval; - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) { if (WriteParameters(writer)) SendAnimationParametersMessage(writer.ToArray()); @@ -173,7 +219,7 @@ void SendAnimationMessage(int stateHash, float normalizedTime, int layerId, floa { RpcOnAnimationClientMessage(stateHash, normalizedTime, layerId, weight, parameters); } - else if (ClientScene.readyConnection != null) + else if (isClient) { CmdOnAnimationServerMessage(stateHash, normalizedTime, layerId, weight, parameters); } @@ -185,7 +231,7 @@ void SendAnimationParametersMessage(byte[] parameters) { RpcOnAnimationParametersClientMessage(parameters); } - else if (ClientScene.readyConnection != null) + else if (isClient) { CmdOnAnimationParametersServerMessage(parameters); } @@ -193,7 +239,7 @@ void SendAnimationParametersMessage(byte[] parameters) void HandleAnimMsg(int stateHash, float normalizedTime, int layerId, float weight, NetworkReader reader) { - if (hasAuthority && clientAuthority) + if (isOwned && clientAuthority) return; // usually transitions will be triggered by parameters, if not, play anims directly. @@ -211,7 +257,7 @@ void HandleAnimMsg(int stateHash, float normalizedTime, int layerId, float weigh void HandleAnimParamsMsg(NetworkReader reader) { - if (hasAuthority && clientAuthority) + if (isOwned && clientAuthority) return; ReadParameters(reader); @@ -268,9 +314,18 @@ ulong NextDirtyBits() bool WriteParameters(NetworkWriter writer, bool forceAll = false) { + // fix: https://github.com/MirrorNetworking/Mirror/issues/2852 + // serialize parameterCount to be 100% sure we deserialize correct amount of bytes. + // (255 parameters should be enough for everyone, write it as byte) + byte parameterCount = (byte)parameters.Length; + writer.WriteByte(parameterCount); + ulong dirtyBits = forceAll ? (~0ul) : NextDirtyBits(); - writer.WritePackedUInt64(dirtyBits); - for (int i = 0; i < parameters.Length; i++) + writer.WriteULong(dirtyBits); + + // iterate on byte count. if it's >256, it won't break + // serialization - just not serialize excess layers. + for (int i = 0; i < parameterCount; i++) { if ((dirtyBits & (1ul << i)) == 0) continue; @@ -279,17 +334,17 @@ bool WriteParameters(NetworkWriter writer, bool forceAll = false) if (par.type == AnimatorControllerParameterType.Int) { int newIntValue = animator.GetInteger(par.nameHash); - writer.WritePackedInt32(newIntValue); + writer.WriteInt(newIntValue); } else if (par.type == AnimatorControllerParameterType.Float) { float newFloatValue = animator.GetFloat(par.nameHash); - writer.WriteSingle(newFloatValue); + writer.WriteFloat(newFloatValue); } else if (par.type == AnimatorControllerParameterType.Bool) { bool newBoolValue = animator.GetBool(par.nameHash); - writer.WriteBoolean(newBoolValue); + writer.WriteBool(newBoolValue); } } return dirtyBits != 0; @@ -297,11 +352,20 @@ bool WriteParameters(NetworkWriter writer, bool forceAll = false) void ReadParameters(NetworkReader reader) { + // fix: https://github.com/MirrorNetworking/Mirror/issues/2852 + // serialize parameterCount to be 100% sure we deserialize correct amount of bytes. + // mismatch shows error to make this super easy to debug. + byte parameterCount = reader.ReadByte(); + if (parameterCount != parameters.Length) + { + Debug.LogError($"NetworkAnimator: serialized parameter count={parameterCount} does not match expected parameter count={parameters.Length}. Are you changing animators at runtime?", gameObject); + return; + } + bool animatorEnabled = animator.enabled; // need to read values from NetworkReader even if animator is disabled - - ulong dirtyBits = reader.ReadPackedUInt64(); - for (int i = 0; i < parameters.Length; i++) + ulong dirtyBits = reader.ReadULong(); + for (int i = 0; i < parameterCount; i++) { if ((dirtyBits & (1ul << i)) == 0) continue; @@ -309,71 +373,73 @@ void ReadParameters(NetworkReader reader) AnimatorControllerParameter par = parameters[i]; if (par.type == AnimatorControllerParameterType.Int) { - int newIntValue = reader.ReadPackedInt32(); + int newIntValue = reader.ReadInt(); if (animatorEnabled) animator.SetInteger(par.nameHash, newIntValue); } else if (par.type == AnimatorControllerParameterType.Float) { - float newFloatValue = reader.ReadSingle(); + float newFloatValue = reader.ReadFloat(); if (animatorEnabled) animator.SetFloat(par.nameHash, newFloatValue); } else if (par.type == AnimatorControllerParameterType.Bool) { - bool newBoolValue = reader.ReadBoolean(); + bool newBoolValue = reader.ReadBool(); if (animatorEnabled) animator.SetBool(par.nameHash, newBoolValue); } } } - /// - /// Custom Serialization - /// - /// - /// - /// - public override bool OnSerialize(NetworkWriter writer, bool initialState) + public override void OnSerialize(NetworkWriter writer, bool initialState) { + base.OnSerialize(writer, initialState); if (initialState) { - for (int i = 0; i < animator.layerCount; i++) + // fix: https://github.com/MirrorNetworking/Mirror/issues/2852 + // serialize layerCount to be 100% sure we deserialize correct amount of bytes. + // (255 layers should be enough for everyone, write it as byte) + byte layerCount = (byte)animator.layerCount; + writer.WriteByte(layerCount); + + // iterate on byte count. if it's >256, it won't break + // serialization - just not serialize excess layers. + for (int i = 0; i < layerCount; i++) { - if (animator.IsInTransition(i)) - { - AnimatorStateInfo st = animator.GetNextAnimatorStateInfo(i); - writer.WriteInt32(st.fullPathHash); - writer.WriteSingle(st.normalizedTime); - } - else - { - AnimatorStateInfo st = animator.GetCurrentAnimatorStateInfo(i); - writer.WriteInt32(st.fullPathHash); - writer.WriteSingle(st.normalizedTime); - } - writer.WriteSingle(animator.GetLayerWeight(i)); + AnimatorStateInfo st = animator.IsInTransition(i) + ? animator.GetNextAnimatorStateInfo(i) + : animator.GetCurrentAnimatorStateInfo(i); + writer.WriteInt(st.fullPathHash); + writer.WriteFloat(st.normalizedTime); + writer.WriteFloat(animator.GetLayerWeight(i)); } - WriteParameters(writer, initialState); - return true; + WriteParameters(writer, true); } - return false; } - /// - /// Custom Deserialization - /// - /// - /// public override void OnDeserialize(NetworkReader reader, bool initialState) { + base.OnDeserialize(reader, initialState); if (initialState) { - for (int i = 0; i < animator.layerCount; i++) + // fix: https://github.com/MirrorNetworking/Mirror/issues/2852 + // serialize layerCount to be 100% sure we deserialize correct amount of bytes. + // mismatch shows error to make this super easy to debug. + byte layerCount = reader.ReadByte(); + if (layerCount != animator.layerCount) { - int stateHash = reader.ReadInt32(); - float normalizedTime = reader.ReadSingle(); - animator.SetLayerWeight(i, reader.ReadSingle()); + Debug.LogError($"NetworkAnimator: serialized layer count={layerCount} does not match expected layer count={animator.layerCount}. Are you changing animators at runtime?", gameObject); + return; + } + + for (int i = 0; i < layerCount; i++) + { + int stateHash = reader.ReadInt(); + float normalizedTime = reader.ReadFloat(); + float weight = reader.ReadFloat(); + + animator.SetLayerWeight(i, weight); animator.Play(stateHash, i, normalizedTime); } @@ -401,17 +467,17 @@ public void SetTrigger(int hash) { if (!isClient) { - logger.LogWarning("Tried to set animation in the server for a client-controlled animator"); + Debug.LogWarning("Tried to set animation in the server for a client-controlled animator", gameObject); return; } - if (!hasAuthority) + if (!isOwned) { - logger.LogWarning("Only the client with authority can set animations"); + Debug.LogWarning("Only the client with authority can set animations", gameObject); return; } - if (ClientScene.readyConnection != null) + if (isClient) CmdOnAnimationTriggerServerMessage(hash); // call on client right away @@ -421,7 +487,7 @@ public void SetTrigger(int hash) { if (!isServer) { - logger.LogWarning("Tried to set animation in the client for a server-controlled animator"); + Debug.LogWarning("Tried to set animation in the client for a server-controlled animator", gameObject); return; } @@ -440,9 +506,7 @@ public void ResetTrigger(string triggerName) ResetTrigger(Animator.StringToHash(triggerName)); } - /// - /// Causes an animation trigger to be reset for a networked object. - /// + /// Causes an animation trigger to be reset for a networked object. /// Hash id of trigger (from the Animator). public void ResetTrigger(int hash) { @@ -450,17 +514,17 @@ public void ResetTrigger(int hash) { if (!isClient) { - logger.LogWarning("Tried to reset animation in the server for a client-controlled animator"); + Debug.LogWarning("Tried to reset animation in the server for a client-controlled animator", gameObject); return; } - if (!hasAuthority) + if (!isOwned) { - logger.LogWarning("Only the client with authority can reset animations"); + Debug.LogWarning("Only the client with authority can reset animations", gameObject); return; } - if (ClientScene.readyConnection != null) + if (isClient) CmdOnAnimationResetTriggerServerMessage(hash); // call on client right away @@ -470,7 +534,7 @@ public void ResetTrigger(int hash) { if (!isServer) { - logger.LogWarning("Tried to reset animation in the client for a server-controlled animator"); + Debug.LogWarning("Tried to reset animation in the client for a server-controlled animator", gameObject); return; } @@ -488,10 +552,10 @@ void CmdOnAnimationServerMessage(int stateHash, float normalizedTime, int layerI if (!clientAuthority) return; - if (logger.LogEnabled()) logger.Log("OnAnimationMessage for netId=" + netId); + //Debug.Log($"OnAnimationMessage for netId {netId}"); // handle and broadcast - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters)) + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(parameters)) { HandleAnimMsg(stateHash, normalizedTime, layerId, weight, networkReader); RpcOnAnimationClientMessage(stateHash, normalizedTime, layerId, weight, parameters); @@ -506,7 +570,7 @@ void CmdOnAnimationParametersServerMessage(byte[] parameters) return; // handle and broadcast - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters)) + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(parameters)) { HandleAnimParamsMsg(networkReader); RpcOnAnimationParametersClientMessage(parameters); @@ -522,8 +586,12 @@ void CmdOnAnimationTriggerServerMessage(int hash) // handle and broadcast // host should have already the trigger - if (!isClient) + bool isHostOwner = isClient && isOwned; + if (!isHostOwner) + { HandleAnimTriggerMsg(hash); + } + RpcOnAnimationTriggerClientMessage(hash); } @@ -536,11 +604,23 @@ void CmdOnAnimationResetTriggerServerMessage(int hash) // handle and broadcast // host should have already the trigger - if (!isClient) + bool isHostOwner = isClient && isOwned; + if (!isHostOwner) + { HandleAnimResetTriggerMsg(hash); + } + RpcOnAnimationResetTriggerClientMessage(hash); } + [Command] + void CmdSetAnimatorSpeed(float newSpeed) + { + // set animator + animator.speed = newSpeed; + animatorSpeed = newSpeed; + } + #endregion #region client message handlers @@ -548,32 +628,26 @@ void CmdOnAnimationResetTriggerServerMessage(int hash) [ClientRpc] void RpcOnAnimationClientMessage(int stateHash, float normalizedTime, int layerId, float weight, byte[] parameters) { - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters)) + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(parameters)) HandleAnimMsg(stateHash, normalizedTime, layerId, weight, networkReader); } [ClientRpc] void RpcOnAnimationParametersClientMessage(byte[] parameters) { - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters)) + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(parameters)) HandleAnimParamsMsg(networkReader); } - [ClientRpc] + [ClientRpc(includeOwner = false)] void RpcOnAnimationTriggerClientMessage(int hash) { - // host/owner handles this before it is sent - if (isServer || (clientAuthority && hasAuthority)) return; - HandleAnimTriggerMsg(hash); } - [ClientRpc] + [ClientRpc(includeOwner = false)] void RpcOnAnimationResetTriggerClientMessage(int hash) { - // host/owner handles this before it is sent - if (isServer || (clientAuthority && hasAuthority)) return; - HandleAnimResetTriggerMsg(hash); } diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkAnimator.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkAnimator.cs.meta index 211ce78808..9809e78dcf 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkAnimator.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/NetworkAnimator.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkAnimator.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkDiagnosticsDebugger.cs b/Assets/ImportedAssets/Mirror/Components/NetworkDiagnosticsDebugger.cs new file mode 100644 index 0000000000..d3c3632784 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkDiagnosticsDebugger.cs @@ -0,0 +1,31 @@ +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/Network Diagnostics Debugger")] + public class NetworkDiagnosticsDebugger : MonoBehaviour + { + public bool logInMessages = true; + public bool logOutMessages = true; + void OnInMessage(NetworkDiagnostics.MessageInfo msgInfo) + { + if (logInMessages) + Debug.Log(msgInfo); + } + void OnOutMessage(NetworkDiagnostics.MessageInfo msgInfo) + { + if (logOutMessages) + Debug.Log(msgInfo); + } + void OnEnable() + { + NetworkDiagnostics.InMessageEvent += OnInMessage; + NetworkDiagnostics.OutMessageEvent += OnOutMessage; + } + void OnDisable() + { + NetworkDiagnostics.InMessageEvent -= OnInMessage; + NetworkDiagnostics.OutMessageEvent -= OnOutMessage; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkDiagnosticsDebugger.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkDiagnosticsDebugger.cs.meta new file mode 100644 index 0000000000..09a866375f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkDiagnosticsDebugger.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: bc9f0a0fe4124424b8f9d4927795ee01 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkDiagnosticsDebugger.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkLobbyManager.cs b/Assets/ImportedAssets/Mirror/Components/NetworkLobbyManager.cs index 5301e39eb4..3dcd4ea3f5 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkLobbyManager.cs +++ b/Assets/ImportedAssets/Mirror/Components/NetworkLobbyManager.cs @@ -11,8 +11,8 @@ namespace Mirror /// NetworkLobbyManager is derived from NetworkManager, and so it implements many of the virtual functions provided by the NetworkManager class. To avoid accidentally replacing functionality of the NetworkLobbyManager, there are new virtual functions on the NetworkLobbyManager that begin with "OnLobby". These should be used on classes derived from NetworkLobbyManager instead of the virtual functions on NetworkManager. /// The OnLobby*() functions have empty implementations on the NetworkLobbyManager base class, so the base class functions do not have to be called. /// - [AddComponentMenu("Network/NetworkLobbyManager")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkRoomManager.html")] + [AddComponentMenu("Network/Network Lobby Manager")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-room-manager")] [Obsolete("Use / inherit from NetworkRoomManager instead")] - public class NetworkLobbyManager : NetworkRoomManager { } + public class NetworkLobbyManager : NetworkRoomManager {} } diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkLobbyManager.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkLobbyManager.cs.meta index a32c8c7c83..3082be757e 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkLobbyManager.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/NetworkLobbyManager.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkLobbyManager.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkLobbyPlayer.cs b/Assets/ImportedAssets/Mirror/Components/NetworkLobbyPlayer.cs index 2e65465fbd..95ffbbcbd5 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkLobbyPlayer.cs +++ b/Assets/ImportedAssets/Mirror/Components/NetworkLobbyPlayer.cs @@ -8,8 +8,8 @@ namespace Mirror /// The LobbyPrefab object of the NetworkLobbyManager must have this component on it. This component holds basic lobby player data required for the lobby to function. Game specific data for lobby players can be put in other components on the LobbyPrefab or in scripts derived from NetworkLobbyPlayer. /// [DisallowMultipleComponent] - [AddComponentMenu("Network/NetworkLobbyPlayer")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkRoomPlayer.html")] + [AddComponentMenu("Network/Network Lobby Player")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-room-player")] [Obsolete("Use / inherit from NetworkRoomPlayer instead")] - public class NetworkLobbyPlayer : NetworkRoomPlayer { } + public class NetworkLobbyPlayer : NetworkRoomPlayer {} } diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkLobbyPlayer.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkLobbyPlayer.cs.meta index 7a21eec503..102a09ba5e 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkLobbyPlayer.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/NetworkLobbyPlayer.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkLobbyPlayer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkMatchChecker.cs b/Assets/ImportedAssets/Mirror/Components/NetworkMatchChecker.cs deleted file mode 100644 index c3e949cd37..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/NetworkMatchChecker.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace Mirror -{ - /// - /// Component that controls visibility of networked objects based on match id. - /// Any object with this component on it will only be visible to other objects in the same match. - /// This would be used to isolate players to their respective matches within a single game server instance. - /// - [DisallowMultipleComponent] - [AddComponentMenu("Network/NetworkMatchChecker")] - [RequireComponent(typeof(NetworkIdentity))] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkMatchChecker.html")] - public class NetworkMatchChecker : NetworkVisibility - { - static readonly Dictionary> matchPlayers = new Dictionary>(); - - Guid currentMatch = Guid.Empty; - - [Header("Diagnostics")] - [SyncVar] - public string currentMatchDebug; - - /// - /// Set this to the same value on all networked objects that belong to a given match - /// - public Guid matchId - { - get { return currentMatch; } - set - { - if (currentMatch == value) return; - - // cache previous match so observers in that match can be rebuilt - Guid previousMatch = currentMatch; - - // Set this to the new match this object just entered ... - currentMatch = value; - // ... and copy the string for the inspector because Unity can't show Guid directly - currentMatchDebug = currentMatch.ToString(); - - if (previousMatch != Guid.Empty) - { - // Remove this object from the hashset of the match it just left - matchPlayers[previousMatch].Remove(netIdentity); - - // RebuildObservers of all NetworkIdentity's in the match this object just left - RebuildMatchObservers(previousMatch); - } - - if (currentMatch != Guid.Empty) - { - // Make sure this new match is in the dictionary - if (!matchPlayers.ContainsKey(currentMatch)) - matchPlayers.Add(currentMatch, new HashSet()); - - // Add this object to the hashset of the new match - matchPlayers[currentMatch].Add(netIdentity); - - // RebuildObservers of all NetworkIdentity's in the match this object just entered - RebuildMatchObservers(currentMatch); - } - else - { - // Not in any match now...RebuildObservers will clear and add self - netIdentity.RebuildObservers(false); - } - } - } - - public override void OnStartServer() - { - if (currentMatch == Guid.Empty) return; - - if (!matchPlayers.ContainsKey(currentMatch)) - matchPlayers.Add(currentMatch, new HashSet()); - - matchPlayers[currentMatch].Add(netIdentity); - - // No need to rebuild anything here. - // identity.RebuildObservers is called right after this from NetworkServer.SpawnObject - } - - void RebuildMatchObservers(Guid specificMatch) - { - foreach (NetworkIdentity networkIdentity in matchPlayers[specificMatch]) - if (networkIdentity != null) - networkIdentity.RebuildObservers(false); - } - - #region Observers - - /// - /// Callback used by the visibility system to determine if an observer (player) can see this object. - /// If this function returns true, the network connection will be added as an observer. - /// - /// Network connection of a player. - /// True if the player can see this object. - public override bool OnCheckObserver(NetworkConnection conn) - { - // Not Visible if not in a match - if (matchId == Guid.Empty) - return false; - - NetworkMatchChecker networkMatchChecker = conn.identity.GetComponent(); - - if (networkMatchChecker == null) - return false; - - return networkMatchChecker.matchId == matchId; - } - - /// - /// Callback used by the visibility system to (re)construct the set of observers that can see this object. - /// Implementations of this callback should add network connections of players that can see this object to the observers set. - /// - /// The new set of observers for this object. - /// True if the set of observers is being built for the first time. - public override void OnRebuildObservers(HashSet observers, bool initialize) - { - if (currentMatch == Guid.Empty) return; - - foreach (NetworkIdentity networkIdentity in matchPlayers[currentMatch]) - if (networkIdentity != null && networkIdentity.connectionToClient != null) - observers.Add(networkIdentity.connectionToClient); - } - - #endregion - } -} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkPingDisplay.cs b/Assets/ImportedAssets/Mirror/Components/NetworkPingDisplay.cs index 46863bfbb9..255e62dcce 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkPingDisplay.cs +++ b/Assets/ImportedAssets/Mirror/Components/NetworkPingDisplay.cs @@ -1,3 +1,4 @@ +using System; using UnityEngine; namespace Mirror @@ -6,36 +7,33 @@ namespace Mirror /// Component that will display the clients ping in milliseconds /// [DisallowMultipleComponent] - [AddComponentMenu("Network/NetworkPingDisplay")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkPingDisplay.html")] + [AddComponentMenu("Network/Network Ping Display")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-ping-display")] public class NetworkPingDisplay : MonoBehaviour { - [SerializeField] bool showPing = true; - [SerializeField] Vector2 position = new Vector2(200, 0); - [SerializeField] int fontSize = 24; - [SerializeField] Color textColor = new Color32(255, 255, 255, 80); - - GUIStyle style; - - void Awake() - { - style = new GUIStyle(); - style.alignment = TextAnchor.UpperLeft; - style.fontSize = fontSize; - style.normal.textColor = textColor; - } + public Color color = Color.white; + public int padding = 2; + public int width = 150; + public int height = 25; void OnGUI() { - if (!showPing) { return; } - - string text = string.Format("{0}ms", (int)(NetworkTime.rtt * 1000)); - - int width = Screen.width; - int height = Screen.height; - Rect rect = new Rect(position.x, position.y, width - 200, height * 2 / 100); + // only while client is active + if (!NetworkClient.active) return; - GUI.Label(rect, text, style); + // show stats in bottom right corner, right aligned + GUI.color = color; + Rect rect = new Rect(Screen.width - width - padding, Screen.height - height - padding, width, height); + GUILayout.BeginArea(rect); + GUIStyle style = GUI.skin.GetStyle("Label"); + style.alignment = TextAnchor.MiddleRight; + GUILayout.BeginHorizontal(style); + GUILayout.Label($"RTT: {Math.Round(NetworkTime.rtt * 1000)}ms"); + GUI.color = NetworkClient.connectionQuality.ColorCode(); + GUILayout.Label($"Q: {new string('-', (int)NetworkClient.connectionQuality)}"); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + GUI.color = Color.white; } } } diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkPingDisplay.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkPingDisplay.cs.meta index 221a74580b..2d378d16e2 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkPingDisplay.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/NetworkPingDisplay.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkPingDisplay.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkProximityChecker.cs b/Assets/ImportedAssets/Mirror/Components/NetworkProximityChecker.cs deleted file mode 100644 index 719ae07991..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/NetworkProximityChecker.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace Mirror -{ - /// - /// Component that controls visibility of networked objects for players. - /// Any object with this component on it will not be visible to players more than a (configurable) distance away. - /// - [AddComponentMenu("Network/NetworkProximityChecker")] - [RequireComponent(typeof(NetworkIdentity))] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkProximityChecker.html")] - public class NetworkProximityChecker : NetworkVisibility - { - /// - /// The maximim range that objects will be visible at. - /// - [Tooltip("The maximum range that objects will be visible at.")] - public int visRange = 10; - - /// - /// How often (in seconds) that this object should update the list of observers that can see it. - /// - [Tooltip("How often (in seconds) that this object should update the list of observers that can see it.")] - public float visUpdateInterval = 1; - - /// - /// Flag to force this object to be hidden for players. - /// If this object is a player object, it will not be hidden for that player. - /// - [Tooltip("Enable to force this object to be hidden from players.")] - public bool forceHidden; - - - public override void OnStartServer() - { - InvokeRepeating(nameof(RebuildObservers), 0, visUpdateInterval); - } - public override void OnStopServer() - { - CancelInvoke(nameof(RebuildObservers)); - } - - void RebuildObservers() - { - netIdentity.RebuildObservers(false); - } - - /// - /// Callback used by the visibility system to determine if an observer (player) can see this object. - /// If this function returns true, the network connection will be added as an observer. - /// - /// Network connection of a player. - /// True if the player can see this object. - public override bool OnCheckObserver(NetworkConnection conn) - { - if (forceHidden) - return false; - - return Vector3.Distance(conn.identity.transform.position, transform.position) < visRange; - } - - /// - /// Callback used by the visibility system to (re)construct the set of observers that can see this object. - /// Implementations of this callback should add network connections of players that can see this object to the observers set. - /// - /// The new set of observers for this object. - /// True if the set of observers is being built for the first time. - public override void OnRebuildObservers(HashSet observers, bool initialize) - { - // if force hidden then return without adding any observers. - if (forceHidden) - return; - - // 'transform.' calls GetComponent, only do it once - Vector3 position = transform.position; - - // brute force distance check - // -> only player connections can be observers, so it's enough if we - // go through all connections instead of all spawned identities. - // -> compared to UNET's sphere cast checking, this one is orders of - // magnitude faster. if we have 10k monsters and run a sphere - // cast 10k times, we will see a noticeable lag even with physics - // layers. but checking to every connection is fast. - foreach (NetworkConnectionToClient conn in NetworkServer.connections.Values) - { - if (conn != null && conn.identity != null) - { - // check distance - if (Vector3.Distance(conn.identity.transform.position, position) < visRange) - { - observers.Add(conn); - } - } - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody.meta b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody.meta new file mode 100644 index 0000000000..a67178e6f5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 80106690aef541a5b8e2f8fb3d5949ad +timeCreated: 1686733778 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs new file mode 100644 index 0000000000..ba17a7012e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs @@ -0,0 +1,112 @@ +using UnityEngine; + +namespace Mirror +{ + // [RequireComponent(typeof(Rigidbody))] <- OnValidate ensures this is on .target + [AddComponentMenu("Network/Network Rigidbody (Reliable)")] + public class NetworkRigidbodyReliable : NetworkTransformReliable + { + bool clientAuthority => syncDirection == SyncDirection.ClientToServer; + + Rigidbody rb; + bool wasKinematic; + + // cach Rigidbody and original isKinematic setting + protected override void Awake() + { + // we can't overwrite .target to be a Rigidbody. + // but we can use its Rigidbody component. + rb = target.GetComponent(); + if (rb == null) + { + Debug.LogError($"{name}'s NetworkRigidbody.target {target.name} is missing a Rigidbody", this); + return; + } + wasKinematic = rb.isKinematic; + base.Awake(); + } + + // reset forced isKinematic flag to original. + // otherwise the overwritten value would remain between sessions forever. + // for example, a game may run as client, set rigidbody.iskinematic=true, + // then run as server, where .iskinematic isn't touched and remains at + // the overwritten=true, even though the user set it to false originally. + public override void OnStopServer() => rb.isKinematic = wasKinematic; + public override void OnStopClient() => rb.isKinematic = wasKinematic; + + // overwriting Construct() and Apply() to set Rigidbody.MovePosition + // would give more jittery movement. + + // FixedUpdate for physics + void FixedUpdate() + { + // who ever has authority moves the Rigidbody with physics. + // everyone else simply sets it to kinematic. + // so that only the Transform component is synced. + + // host mode + if (isServer && isClient) + { + // in host mode, we own it it if: + // clientAuthority is disabled (hence server / we own it) + // clientAuthority is enabled and we have authority over this object. + bool owned = !clientAuthority || IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // client only + else if (isClient) + { + // on the client, we own it only if clientAuthority is enabled, + // and we have authority over this object. + bool owned = IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // server only + else if (isServer) + { + // on the server, we always own it if clientAuthority is disabled. + bool owned = !clientAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + } + + protected override void OnValidate() + { + base.OnValidate(); + + // we can't overwrite .target to be a Rigidbody. + // but we can ensure that .target has a Rigidbody, and use it. + if (target.GetComponent() == null) + { + Debug.LogWarning($"{name}'s NetworkRigidbody.target {target.name} is missing a Rigidbody", this); + } + } + + protected override void OnTeleport(Vector3 destination) + { + base.OnTeleport(destination); + + rb.position = transform.position; + } + + protected override void OnTeleport(Vector3 destination, Quaternion rotation) + { + base.OnTeleport(destination, rotation); + + rb.position = transform.position; + rb.rotation = transform.rotation; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs.meta new file mode 100644 index 0000000000..f0754798f7 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: cb803efbe62c34d7baece46c9ffebad9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs new file mode 100644 index 0000000000..f17bab62e0 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs @@ -0,0 +1,112 @@ +using UnityEngine; + +namespace Mirror +{ + // [RequireComponent(typeof(Rigidbody))] <- OnValidate ensures this is on .target + [AddComponentMenu("Network/Network Rigidbody 2D (Reliable)")] + public class NetworkRigidbodyReliable2D : NetworkTransformReliable + { + bool clientAuthority => syncDirection == SyncDirection.ClientToServer; + + Rigidbody2D rb; + bool wasKinematic; + + // cach Rigidbody and original isKinematic setting + protected override void Awake() + { + // we can't overwrite .target to be a Rigidbody. + // but we can use its Rigidbody component. + rb = target.GetComponent(); + if (rb == null) + { + Debug.LogError($"{name}'s NetworkRigidbody2D.target {target.name} is missing a Rigidbody2D", this); + return; + } + wasKinematic = rb.isKinematic; + base.Awake(); + } + + // reset forced isKinematic flag to original. + // otherwise the overwritten value would remain between sessions forever. + // for example, a game may run as client, set rigidbody.iskinematic=true, + // then run as server, where .iskinematic isn't touched and remains at + // the overwritten=true, even though the user set it to false originally. + public override void OnStopServer() => rb.isKinematic = wasKinematic; + public override void OnStopClient() => rb.isKinematic = wasKinematic; + + // overwriting Construct() and Apply() to set Rigidbody.MovePosition + // would give more jittery movement. + + // FixedUpdate for physics + void FixedUpdate() + { + // who ever has authority moves the Rigidbody with physics. + // everyone else simply sets it to kinematic. + // so that only the Transform component is synced. + + // host mode + if (isServer && isClient) + { + // in host mode, we own it it if: + // clientAuthority is disabled (hence server / we own it) + // clientAuthority is enabled and we have authority over this object. + bool owned = !clientAuthority || IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // client only + else if (isClient) + { + // on the client, we own it only if clientAuthority is enabled, + // and we have authority over this object. + bool owned = IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // server only + else if (isServer) + { + // on the server, we always own it if clientAuthority is disabled. + bool owned = !clientAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + } + + protected override void OnValidate() + { + base.OnValidate(); + + // we can't overwrite .target to be a Rigidbody. + // but we can ensure that .target has a Rigidbody, and use it. + if (target.GetComponent() == null) + { + Debug.LogWarning($"{name}'s NetworkRigidbody2D.target {target.name} is missing a Rigidbody2D", this); + } + } + + protected override void OnTeleport(Vector3 destination) + { + base.OnTeleport(destination); + + rb.position = transform.position; + } + + protected override void OnTeleport(Vector3 destination, Quaternion rotation) + { + base.OnTeleport(destination, rotation); + + rb.position = transform.position; + rb.rotation = transform.rotation.eulerAngles.z; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs.meta new file mode 100644 index 0000000000..34412aff50 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 7ec4f7556ca1e4b55a3381fc6a02b1bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs new file mode 100644 index 0000000000..6a347669e4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs @@ -0,0 +1,112 @@ +using UnityEngine; + +namespace Mirror +{ + // [RequireComponent(typeof(Rigidbody))] <- OnValidate ensures this is on .target + [AddComponentMenu("Network/Network Rigidbody (Unreliable)")] + public class NetworkRigidbodyUnreliable : NetworkTransformUnreliable + { + bool clientAuthority => syncDirection == SyncDirection.ClientToServer; + + Rigidbody rb; + bool wasKinematic; + + // cach Rigidbody and original isKinematic setting + protected override void Awake() + { + // we can't overwrite .target to be a Rigidbody. + // but we can use its Rigidbody component. + rb = target.GetComponent(); + if (rb == null) + { + Debug.LogError($"{name}'s NetworkRigidbody.target {target.name} is missing a Rigidbody", this); + return; + } + wasKinematic = rb.isKinematic; + base.Awake(); + } + + // reset forced isKinematic flag to original. + // otherwise the overwritten value would remain between sessions forever. + // for example, a game may run as client, set rigidbody.iskinematic=true, + // then run as server, where .iskinematic isn't touched and remains at + // the overwritten=true, even though the user set it to false originally. + public override void OnStopServer() => rb.isKinematic = wasKinematic; + public override void OnStopClient() => rb.isKinematic = wasKinematic; + + // overwriting Construct() and Apply() to set Rigidbody.MovePosition + // would give more jittery movement. + + // FixedUpdate for physics + void FixedUpdate() + { + // who ever has authority moves the Rigidbody with physics. + // everyone else simply sets it to kinematic. + // so that only the Transform component is synced. + + // host mode + if (isServer && isClient) + { + // in host mode, we own it it if: + // clientAuthority is disabled (hence server / we own it) + // clientAuthority is enabled and we have authority over this object. + bool owned = !clientAuthority || IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // client only + else if (isClient) + { + // on the client, we own it only if clientAuthority is enabled, + // and we have authority over this object. + bool owned = IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // server only + else if (isServer) + { + // on the server, we always own it if clientAuthority is disabled. + bool owned = !clientAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + } + + protected override void OnValidate() + { + base.OnValidate(); + + // we can't overwrite .target to be a Rigidbody. + // but we can ensure that .target has a Rigidbody, and use it. + if (target.GetComponent() == null) + { + Debug.LogWarning($"{name}'s NetworkRigidbody.target {target.name} is missing a Rigidbody", this); + } + } + + protected override void OnTeleport(Vector3 destination) + { + base.OnTeleport(destination); + + rb.position = transform.position; + } + + protected override void OnTeleport(Vector3 destination, Quaternion rotation) + { + base.OnTeleport(destination, rotation); + + rb.position = transform.position; + rb.rotation = transform.rotation; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs.meta new file mode 100644 index 0000000000..4629f08aa9 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 3b20dc110904e47f8a154cdcf6433eae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs new file mode 100644 index 0000000000..308ce0e701 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs @@ -0,0 +1,112 @@ +using UnityEngine; + +namespace Mirror +{ + // [RequireComponent(typeof(Rigidbody))] <- OnValidate ensures this is on .target + [AddComponentMenu("Network/Network Rigidbody 2D (Unreliable)")] + public class NetworkRigidbodyUnreliable2D : NetworkTransformUnreliable + { + bool clientAuthority => syncDirection == SyncDirection.ClientToServer; + + Rigidbody2D rb; + bool wasKinematic; + + // cach Rigidbody and original isKinematic setting + protected override void Awake() + { + // we can't overwrite .target to be a Rigidbody. + // but we can use its Rigidbody component. + rb = target.GetComponent(); + if (rb == null) + { + Debug.LogError($"{name}'s NetworkRigidbody2D.target {target.name} is missing a Rigidbody2D", this); + return; + } + wasKinematic = rb.isKinematic; + base.Awake(); + } + + // reset forced isKinematic flag to original. + // otherwise the overwritten value would remain between sessions forever. + // for example, a game may run as client, set rigidbody.iskinematic=true, + // then run as server, where .iskinematic isn't touched and remains at + // the overwritten=true, even though the user set it to false originally. + public override void OnStopServer() => rb.isKinematic = wasKinematic; + public override void OnStopClient() => rb.isKinematic = wasKinematic; + + // overwriting Construct() and Apply() to set Rigidbody.MovePosition + // would give more jittery movement. + + // FixedUpdate for physics + void FixedUpdate() + { + // who ever has authority moves the Rigidbody with physics. + // everyone else simply sets it to kinematic. + // so that only the Transform component is synced. + + // host mode + if (isServer && isClient) + { + // in host mode, we own it it if: + // clientAuthority is disabled (hence server / we own it) + // clientAuthority is enabled and we have authority over this object. + bool owned = !clientAuthority || IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // client only + else if (isClient) + { + // on the client, we own it only if clientAuthority is enabled, + // and we have authority over this object. + bool owned = IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // server only + else if (isServer) + { + // on the server, we always own it if clientAuthority is disabled. + bool owned = !clientAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + } + + protected override void OnValidate() + { + base.OnValidate(); + + // we can't overwrite .target to be a Rigidbody. + // but we can ensure that .target has a Rigidbody, and use it. + if (target.GetComponent() == null) + { + Debug.LogWarning($"{name}'s NetworkRigidbody2D.target {target.name} is missing a Rigidbody2D", this); + } + } + + protected override void OnTeleport(Vector3 destination) + { + base.OnTeleport(destination); + + rb.position = transform.position; + } + + protected override void OnTeleport(Vector3 destination, Quaternion rotation) + { + base.OnTeleport(destination, rotation); + + rb.position = transform.position; + rb.rotation = transform.rotation.eulerAngles.z; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs.meta new file mode 100644 index 0000000000..b78fc6dd3e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 1c7e12ad9b9ae443c9fdf37e9f5ecd36 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRoomManager.cs b/Assets/ImportedAssets/Mirror/Components/NetworkRoomManager.cs index 5bbab1e25b..4df69c6fa6 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkRoomManager.cs +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRoomManager.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; using UnityEngine; using UnityEngine.SceneManagement; @@ -16,34 +14,31 @@ namespace Mirror /// NetworkRoomManager is derived from NetworkManager, and so it implements many of the virtual functions provided by the NetworkManager class. To avoid accidentally replacing functionality of the NetworkRoomManager, there are new virtual functions on the NetworkRoomManager that begin with "OnRoom". These should be used on classes derived from NetworkRoomManager instead of the virtual functions on NetworkManager. /// The OnRoom*() functions have empty implementations on the NetworkRoomManager base class, so the base class functions do not have to be called. /// - [AddComponentMenu("Network/NetworkRoomManager")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkRoomManager.html")] + [AddComponentMenu("Network/Network Room Manager")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-room-manager")] public class NetworkRoomManager : NetworkManager { - static readonly ILogger logger = LogFactory.GetLogger(typeof(NetworkRoomManager)); - public struct PendingPlayer { - public NetworkConnection conn; + public NetworkConnectionToClient conn; public GameObject roomPlayer; } [Header("Room Settings")] - [FormerlySerializedAs("m_ShowRoomGUI")] [SerializeField] [Tooltip("This flag controls whether the default UI is shown for the room")] - internal bool showRoomGUI = true; + public bool showRoomGUI = true; [FormerlySerializedAs("m_MinPlayers")] [SerializeField] [Tooltip("Minimum number of players to auto-start the game")] - protected int minPlayers = 1; + public int minPlayers = 1; [FormerlySerializedAs("m_RoomPlayerPrefab")] [SerializeField] [Tooltip("Prefab to use for the Room Player")] - protected NetworkRoomPlayer roomPlayerPrefab; + public NetworkRoomPlayer roomPlayerPrefab; /// /// The scene to use for the room. This is similar to the offlineScene of the NetworkManager. @@ -61,23 +56,22 @@ public struct PendingPlayer /// List of players that are in the Room /// [FormerlySerializedAs("m_PendingPlayers")] - public List pendingPlayers = new List(); + public HashSet pendingPlayers = new HashSet(); [Header("Diagnostics")] - /// /// True when all players have submitted a Ready message /// [Tooltip("Diagnostic flag indicating all players are ready to play")] [FormerlySerializedAs("allPlayersReady")] - [SerializeField] bool _allPlayersReady; + [ReadOnly, SerializeField] bool _allPlayersReady; /// /// These slots track players that enter the room. /// The slotId on players is global to the game - across all players. /// - [Tooltip("List of Room Player objects")] - public List roomSlots = new List(); + [ReadOnly, Tooltip("List of Room Player objects")] + public HashSet roomSlots = new HashSet(); public bool allPlayersReady { @@ -105,8 +99,7 @@ public bool allPlayersReady public override void OnValidate() { - // always >= 0 - maxConnections = Mathf.Max(maxConnections, 0); + base.OnValidate(); // always <= maxConnections minPlayers = Mathf.Min(minPlayers, maxConnections); @@ -120,59 +113,16 @@ public override void OnValidate() if (identity == null) { roomPlayerPrefab = null; - logger.LogError("RoomPlayer prefab must have a NetworkIdentity component."); + Debug.LogError("RoomPlayer prefab must have a NetworkIdentity component."); } } - - base.OnValidate(); } - internal void ReadyStatusChanged() + void SceneLoadedForPlayer(NetworkConnectionToClient conn, GameObject roomPlayer) { - int CurrentPlayers = 0; - int ReadyPlayers = 0; + //Debug.Log($"NetworkRoom SceneLoadedForPlayer scene: {SceneManager.GetActiveScene().path} {conn}"); - foreach (NetworkRoomPlayer item in roomSlots) - { - if (item != null) - { - CurrentPlayers++; - if (item.readyToBegin) - ReadyPlayers++; - } - } - - if (CurrentPlayers == ReadyPlayers) - CheckReadyToBegin(); - else - allPlayersReady = false; - } - - /// - /// Called on the server when a client is ready. - /// The default implementation of this function calls NetworkServer.SetClientReady() to continue the network setup process. - /// - /// Connection from client. - public override void OnServerReady(NetworkConnection conn) - { - logger.Log("NetworkRoomManager OnServerReady"); - base.OnServerReady(conn); - - if (conn != null && conn.identity != null) - { - GameObject roomPlayer = conn.identity.gameObject; - - // if null or not a room player, dont replace it - if (roomPlayer != null && roomPlayer.GetComponent() != null) - SceneLoadedForPlayer(conn, roomPlayer); - } - } - - void SceneLoadedForPlayer(NetworkConnection conn, GameObject roomPlayer) - { - if (logger.LogEnabled()) logger.LogFormat(LogType.Log, "NetworkRoom SceneLoadedForPlayer scene: {0} {1}", SceneManager.GetActiveScene().path, conn); - - if (IsSceneActive(RoomScene)) + if (Utils.IsSceneActive(RoomScene)) { // cant be ready in room, add to ready list PendingPlayer pending; @@ -199,28 +149,6 @@ void SceneLoadedForPlayer(NetworkConnection conn, GameObject roomPlayer) NetworkServer.ReplacePlayerForConnection(conn, gamePlayer, true); } - /// - /// CheckReadyToBegin checks all of the players in the room to see if their readyToBegin flag is set. - /// If all of the players are ready, then the server switches from the RoomScene to the PlayScene, essentially starting the game. This is called automatically in response to NetworkRoomPlayer.CmdChangeReadyState. - /// - public void CheckReadyToBegin() - { - if (!IsSceneActive(RoomScene)) - return; - - int numberOfReadyPlayers = NetworkServer.connections.Count(conn => conn.Value != null && conn.Value.identity.gameObject.GetComponent().readyToBegin); - bool enoughReadyPlayers = minPlayers <= 0 || numberOfReadyPlayers >= minPlayers; - if (enoughReadyPlayers) - { - pendingPlayers.Clear(); - allPlayersReady = true; - } - else - { - allPlayersReady = false; - } - } - internal void CallOnClientEnterRoom() { OnRoomClientEnter(); @@ -231,7 +159,7 @@ internal void CallOnClientEnterRoom() } } - void CallOnClientExitRoom() + internal void CallOnClientExitRoom() { OnRoomClientExit(); foreach (NetworkRoomPlayer player in roomSlots) @@ -241,6 +169,31 @@ void CallOnClientExitRoom() } } + /// + /// CheckReadyToBegin checks all of the players in the room to see if their readyToBegin flag is set. + /// If all of the players are ready, then the server switches from the RoomScene to the PlayScene, essentially starting the game. This is called automatically in response to NetworkRoomPlayer.CmdChangeReadyState. + /// + public void CheckReadyToBegin() + { + if (!Utils.IsSceneActive(RoomScene)) + return; + + int numberOfReadyPlayers = NetworkServer.connections.Count(conn => + conn.Value != null && + conn.Value.identity != null && + conn.Value.identity.TryGetComponent(out NetworkRoomPlayer nrp) && + nrp.readyToBegin); + + bool enoughReadyPlayers = minPlayers <= 0 || numberOfReadyPlayers >= minPlayers; + if (enoughReadyPlayers) + { + pendingPlayers.Clear(); + allPlayersReady = true; + } + else + allPlayersReady = false; + } + #region server handlers /// @@ -248,17 +201,12 @@ void CallOnClientExitRoom() /// Unity calls this on the Server when a Client connects to the Server. Use an override to tell the NetworkManager what to do when a client connects to the server. /// /// Connection from client. - public override void OnServerConnect(NetworkConnection conn) + public override void OnServerConnect(NetworkConnectionToClient conn) { - if (numPlayers >= maxConnections) - { - conn.Disconnect(); - return; - } - // cannot join game in progress - if (!IsSceneActive(RoomScene)) + if (!Utils.IsSceneActive(RoomScene)) { + Debug.Log($"Not in Room scene...disconnecting {conn}"); conn.Disconnect(); return; } @@ -272,7 +220,7 @@ public override void OnServerConnect(NetworkConnection conn) /// This is called on the Server when a Client disconnects from the Server. Use an override to decide what should happen when a disconnection is detected. /// /// Connection from client. - public override void OnServerDisconnect(NetworkConnection conn) + public override void OnServerDisconnect(NetworkConnectionToClient conn) { if (conn.identity != null) { @@ -281,7 +229,7 @@ public override void OnServerDisconnect(NetworkConnection conn) if (roomPlayer != null) roomSlots.Remove(roomPlayer); - foreach (NetworkIdentity clientOwnedObject in conn.clientOwnedObjects) + foreach (NetworkIdentity clientOwnedObject in conn.owned) { roomPlayer = clientOwnedObject.GetComponent(); if (roomPlayer != null) @@ -297,28 +245,56 @@ public override void OnServerDisconnect(NetworkConnection conn) player.GetComponent().readyToBegin = false; } - if (IsSceneActive(RoomScene)) + if (Utils.IsSceneActive(RoomScene)) RecalculateRoomPlayerIndices(); OnRoomServerDisconnect(conn); base.OnServerDisconnect(conn); + + // Restart the server if we're headless and no players are connected. + // This will send server to offline scene, where auto-start will run. + if (Utils.IsHeadless() && numPlayers < 1) + StopServer(); } + // Sequential index used in round-robin deployment of players into instances and score positioning + public int clientIndex; + /// - /// Called on the server when a client adds a new player with ClientScene.AddPlayer. - /// The default implementation for this function creates a new player object from the playerPrefab. + /// Called on the server when a client is ready. + /// The default implementation of this function calls NetworkServer.SetClientReady() to continue the network setup process. /// /// Connection from client. - public override void OnServerAddPlayer(NetworkConnection conn) + public override void OnServerReady(NetworkConnectionToClient conn) { - if (IsSceneActive(RoomScene)) + //Debug.Log($"NetworkRoomManager OnServerReady {conn}"); + base.OnServerReady(conn); + + if (conn != null && conn.identity != null) { - if (roomSlots.Count == maxConnections) - return; + GameObject roomPlayer = conn.identity.gameObject; + // if null or not a room player, don't replace it + if (roomPlayer != null && roomPlayer.GetComponent() != null) + SceneLoadedForPlayer(conn, roomPlayer); + } + } + + /// + /// Called on the server when a client adds a new player with NetworkClient.AddPlayer. + /// The default implementation for this function creates a new player object from the playerPrefab. + /// + /// Connection from client. + public override void OnServerAddPlayer(NetworkConnectionToClient conn) + { + // increment the index before adding the player, so first player starts at 1 + clientIndex++; + + if (Utils.IsSceneActive(RoomScene)) + { allPlayersReady = false; - if (logger.LogEnabled()) logger.LogFormat(LogType.Log, "NetworkRoomManager.OnServerAddPlayer playerPrefab:{0}", roomPlayerPrefab.name); + //Debug.Log("NetworkRoomManager.OnServerAddPlayer playerPrefab: {roomPlayerPrefab.name}"); GameObject newRoomGameObject = OnRoomServerCreateRoomPlayer(conn); if (newRoomGameObject == null) @@ -327,23 +303,27 @@ public override void OnServerAddPlayer(NetworkConnection conn) NetworkServer.AddPlayerForConnection(conn, newRoomGameObject); } else - OnRoomServerAddPlayer(conn); + { + // Late joiners not supported...should've been kicked by OnServerDisconnect + Debug.Log($"Not in Room scene...disconnecting {conn}"); + conn.Disconnect(); + } } + [Server] public void RecalculateRoomPlayerIndices() { if (roomSlots.Count > 0) { - for (int i = 0; i < roomSlots.Count; i++) - { - roomSlots[i].index = i; - } + int i = 0; + foreach (NetworkRoomPlayer player in roomSlots) + player.index = i++; } } /// /// This causes the server to switch scenes and sets the networkSceneName. - /// Clients that connect to this server will automatically switch to this scene. This is called autmatically if onlineScene or offlineScene are set, but it can be called from user code to switch scenes again while the game is in progress. This automatically sets clients to be not-ready. The clients must call NetworkClient.Ready() again to participate in the new scene. + /// Clients that connect to this server will automatically switch to this scene. This is called automatically if onlineScene or offlineScene are set, but it can be called from user code to switch scenes again while the game is in progress. This automatically sets clients to be not-ready. The clients must call NetworkClient.Ready() again to participate in the new scene. /// /// public override void ServerChangeScene(string newSceneName) @@ -396,15 +376,15 @@ public override void OnServerSceneChanged(string sceneName) /// public override void OnStartServer() { - if (string.IsNullOrEmpty(RoomScene)) + if (string.IsNullOrWhiteSpace(RoomScene)) { - logger.LogError("NetworkRoomManager RoomScene is empty. Set the RoomScene in the inspector for the NetworkRoomMangaer"); + Debug.LogError("NetworkRoomManager RoomScene is empty. Set the RoomScene in the inspector for the NetworkRoomManager"); return; } - if (string.IsNullOrEmpty(GameplayScene)) + if (string.IsNullOrWhiteSpace(GameplayScene)) { - logger.LogError("NetworkRoomManager PlayScene is empty. Set the PlayScene in the inspector for the NetworkRoomMangaer"); + Debug.LogError("NetworkRoomManager PlayScene is empty. Set the PlayScene in the inspector for the NetworkRoomManager"); return; } @@ -447,12 +427,12 @@ public override void OnStopHost() public override void OnStartClient() { if (roomPlayerPrefab == null || roomPlayerPrefab.gameObject == null) - logger.LogError("NetworkRoomManager no RoomPlayer prefab is registered. Please add a RoomPlayer prefab."); + Debug.LogError("NetworkRoomManager no RoomPlayer prefab is registered. Please add a RoomPlayer prefab."); else - ClientScene.RegisterPrefab(roomPlayerPrefab.gameObject); + NetworkClient.RegisterPrefab(roomPlayerPrefab.gameObject); if (playerPrefab == null) - logger.LogError("NetworkRoomManager no GamePlayer prefab is registered. Please add a GamePlayer prefab."); + Debug.LogError("NetworkRoomManager no GamePlayer prefab is registered. Please add a GamePlayer prefab."); OnRoomStartClient(); } @@ -461,22 +441,20 @@ public override void OnStartClient() /// Called on the client when connected to a server. /// The default implementation of this function sets the client as ready and adds a player. Override the function to dictate what happens when the client connects. /// - /// Connection to the server. - public override void OnClientConnect(NetworkConnection conn) + public override void OnClientConnect() { - OnRoomClientConnect(conn); - base.OnClientConnect(conn); + OnRoomClientConnect(); + base.OnClientConnect(); } /// /// Called on clients when disconnected from a server. /// This is called on the client when it disconnects from the server. Override this function to decide what happens when the client disconnects. /// - /// Connection to the server. - public override void OnClientDisconnect(NetworkConnection conn) + public override void OnClientDisconnect() { - OnRoomClientDisconnect(conn); - base.OnClientDisconnect(conn); + OnRoomClientDisconnect(); + base.OnClientDisconnect(); } /// @@ -493,10 +471,9 @@ public override void OnStopClient() /// Called on clients when a scene has completed loaded, when the scene load was initiated by the server. /// Scene changes can cause player objects to be destroyed. The default implementation of OnClientSceneChanged in the NetworkManager is to add a player object for the connection if no player object exists. /// - /// Connection of the client - public override void OnClientSceneChanged(NetworkConnection conn) + public override void OnClientSceneChanged() { - if (IsSceneActive(RoomScene)) + if (Utils.IsSceneActive(RoomScene)) { if (NetworkClient.isConnected) CallOnClientEnterRoom(); @@ -504,8 +481,8 @@ public override void OnClientSceneChanged(NetworkConnection conn) else CallOnClientExitRoom(); - base.OnClientSceneChanged(conn); - OnRoomClientSceneChanged(conn); + base.OnClientSceneChanged(); + OnRoomClientSceneChanged(); } #endregion @@ -515,40 +492,40 @@ public override void OnClientSceneChanged(NetworkConnection conn) /// /// This is called on the host when a host is started. /// - public virtual void OnRoomStartHost() { } + public virtual void OnRoomStartHost() {} /// /// This is called on the host when the host is stopped. /// - public virtual void OnRoomStopHost() { } + public virtual void OnRoomStopHost() {} /// /// This is called on the server when the server is started - including when a host is started. /// - public virtual void OnRoomStartServer() { } + public virtual void OnRoomStartServer() {} /// /// This is called on the server when the server is started - including when a host is stopped. /// - public virtual void OnRoomStopServer() { } + public virtual void OnRoomStopServer() {} /// /// This is called on the server when a new client connects to the server. /// /// The new connection. - public virtual void OnRoomServerConnect(NetworkConnection conn) { } + public virtual void OnRoomServerConnect(NetworkConnectionToClient conn) {} /// /// This is called on the server when a client disconnects. /// /// The connection that disconnected. - public virtual void OnRoomServerDisconnect(NetworkConnection conn) { } + public virtual void OnRoomServerDisconnect(NetworkConnectionToClient conn) {} /// /// This is called on the server when a networked scene finishes loading. /// /// Name of the new scene. - public virtual void OnRoomServerSceneChanged(string sceneName) { } + public virtual void OnRoomServerSceneChanged(string sceneName) {} /// /// This allows customization of the creation of the room-player object on the server. @@ -556,19 +533,7 @@ public virtual void OnRoomServerSceneChanged(string sceneName) { } /// /// The connection the player object is for. /// The new room-player object. - public virtual GameObject OnRoomServerCreateRoomPlayer(NetworkConnection conn) - { - return null; - } - - // Deprecated 12/17/2019 - /// - /// Obsolete: Use OnRoomServerCreateGamePlayer(NetworkConnection, GameObject) instead. - /// - /// The connection the player object is for. - /// A new GamePlayer object. - [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use OnRoomServerCreateGamePlayer(NetworkConnection conn, GameObject roomPlayer) instead", true)] - public virtual GameObject OnRoomServerCreateGamePlayer(NetworkConnection conn) + public virtual GameObject OnRoomServerCreateRoomPlayer(NetworkConnectionToClient conn) { return null; } @@ -580,7 +545,7 @@ public virtual GameObject OnRoomServerCreateGamePlayer(NetworkConnection conn) /// The connection the player object is for. /// The room player object for this connection. /// A new GamePlayer object. - public virtual GameObject OnRoomServerCreateGamePlayer(NetworkConnection conn, GameObject roomPlayer) + public virtual GameObject OnRoomServerCreateGamePlayer(NetworkConnectionToClient conn, GameObject roomPlayer) { return null; } @@ -588,24 +553,14 @@ public virtual GameObject OnRoomServerCreateGamePlayer(NetworkConnection conn, G /// /// This allows customization of the creation of the GamePlayer object on the server. /// This is only called for subsequent GamePlay scenes after the first one. - /// See OnRoomServerCreateGamePlayer(NetworkConnection, GameObject) to customize the player object for the initial GamePlay scene. + /// See OnRoomServerCreateGamePlayer(NetworkConnection, GameObject) to customize the player object for the initial GamePlay scene. /// /// The connection the player object is for. - public virtual void OnRoomServerAddPlayer(NetworkConnection conn) + public virtual void OnRoomServerAddPlayer(NetworkConnectionToClient conn) { base.OnServerAddPlayer(conn); } - // Deprecated 02/22/2020 - /// - /// Obsolete: Use OnRoomServerSceneLoadedForPlayer(NetworkConnection, GameObject, GameObject) instead. - /// - [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use OnRoomServerSceneLoadedForPlayer(NetworkConnection conn, GameObject roomPlayer, GameObject gamePlayer) instead")] - public virtual bool OnRoomServerSceneLoadedForPlayer(GameObject roomPlayer, GameObject gamePlayer) - { - return true; - } - // for users to apply settings from their room player object to their in-game player object /// /// This is called on the server when it is told that a client has finished switching from the room scene to a game player scene. @@ -615,11 +570,35 @@ public virtual bool OnRoomServerSceneLoadedForPlayer(GameObject roomPlayer, Game /// The room player object. /// The game player object. /// False to not allow this player to replace the room player. - public virtual bool OnRoomServerSceneLoadedForPlayer(NetworkConnection conn, GameObject roomPlayer, GameObject gamePlayer) + public virtual bool OnRoomServerSceneLoadedForPlayer(NetworkConnectionToClient conn, GameObject roomPlayer, GameObject gamePlayer) { return true; } + /// + /// This is called on server from NetworkRoomPlayer.CmdChangeReadyState when client indicates change in Ready status. + /// + public virtual void ReadyStatusChanged() + { + int CurrentPlayers = 0; + int ReadyPlayers = 0; + + foreach (NetworkRoomPlayer item in roomSlots) + { + if (item != null) + { + CurrentPlayers++; + if (item.readyToBegin) + ReadyPlayers++; + } + } + + if (CurrentPlayers == ReadyPlayers) + CheckReadyToBegin(); + else + allPlayersReady = false; + } + /// /// This is called on the server when all the players in the room are ready. /// The default implementation of this function uses ServerChangeScene() to switch to the game player scene. By implementing this callback you can customize what happens when all the players in the room are ready, such as adding a countdown or a confirmation for a group leader. @@ -634,7 +613,7 @@ public virtual void OnRoomServerPlayersReady() /// This is called on the server when CheckReadyToBegin finds that players are not ready /// May be called multiple times while not ready players are joining /// - public virtual void OnRoomServerPlayersNotReady() { } + public virtual void OnRoomServerPlayersNotReady() {} #endregion @@ -643,47 +622,37 @@ public virtual void OnRoomServerPlayersNotReady() { } /// /// This is a hook to allow custom behaviour when the game client enters the room. /// - public virtual void OnRoomClientEnter() { } + public virtual void OnRoomClientEnter() {} /// /// This is a hook to allow custom behaviour when the game client exits the room. /// - public virtual void OnRoomClientExit() { } + public virtual void OnRoomClientExit() {} /// /// This is called on the client when it connects to server. /// - /// The connection that connected. - public virtual void OnRoomClientConnect(NetworkConnection conn) { } + public virtual void OnRoomClientConnect() {} /// /// This is called on the client when disconnected from a server. /// - /// The connection that disconnected. - public virtual void OnRoomClientDisconnect(NetworkConnection conn) { } + public virtual void OnRoomClientDisconnect() {} /// /// This is called on the client when a client is started. /// - /// The connection for the room. - public virtual void OnRoomStartClient() { } + public virtual void OnRoomStartClient() {} /// /// This is called on the client when the client stops. /// - public virtual void OnRoomStopClient() { } + public virtual void OnRoomStopClient() {} /// /// This is called on the client when the client is finished loading a new networked scene. /// - /// The connection that finished loading a new networked scene. - public virtual void OnRoomClientSceneChanged(NetworkConnection conn) { } - - /// - /// Called on the client when adding a player to the room fails. - /// This could be because the room is full, or the connection is not allowed to have more players. - /// - public virtual void OnRoomClientAddPlayerFailed() { } + public virtual void OnRoomClientSceneChanged() {} #endregion @@ -697,7 +666,7 @@ public virtual void OnGUI() if (!showRoomGUI) return; - if (NetworkServer.active && IsSceneActive(GameplayScene)) + if (NetworkServer.active && Utils.IsSceneActive(GameplayScene)) { GUILayout.BeginArea(new Rect(Screen.width - 150f, 10f, 140f, 30f)); if (GUILayout.Button("Return to Room")) @@ -705,7 +674,7 @@ public virtual void OnGUI() GUILayout.EndArea(); } - if (IsSceneActive(RoomScene)) + if (Utils.IsSceneActive(RoomScene)) GUI.Box(new Rect(10f, 180f, 520f, 150f), "PLAYERS"); } diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRoomManager.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkRoomManager.cs.meta index 76e7d426a4..bcb5c95d38 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkRoomManager.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRoomManager.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkRoomManager.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRoomPlayer.cs b/Assets/ImportedAssets/Mirror/Components/NetworkRoomPlayer.cs index 87271caf2e..6b7cda466f 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkRoomPlayer.cs +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRoomPlayer.cs @@ -1,5 +1,3 @@ -using System; -using System.ComponentModel; using UnityEngine; namespace Mirror @@ -9,12 +7,10 @@ namespace Mirror /// The RoomPrefab object of the NetworkRoomManager must have this component on it. This component holds basic room player data required for the room to function. Game specific data for room players can be put in other components on the RoomPrefab or in scripts derived from NetworkRoomPlayer. /// [DisallowMultipleComponent] - [AddComponentMenu("Network/NetworkRoomPlayer")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkRoomPlayer.html")] + [AddComponentMenu("Network/Network Room Player")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-room-player")] public class NetworkRoomPlayer : NetworkBehaviour { - static readonly ILogger logger = LogFactory.GetLogger(typeof(NetworkRoomPlayer)); - /// /// This flag controls whether the default UI is shown for the room player. /// As this UI is rendered using the old GUI system, it is only recommended for testing purposes. @@ -29,48 +25,51 @@ public class NetworkRoomPlayer : NetworkBehaviour /// Invoke CmdChangeReadyState method on the client to set this flag. /// When all players are ready to begin, the game will start. This should not be set directly, CmdChangeReadyState should be called on the client to set it on the server. /// - [Tooltip("Diagnostic flag indicating whether this player is ready for the game to begin")] + [ReadOnly, Tooltip("Diagnostic flag indicating whether this player is ready for the game to begin")] [SyncVar(hook = nameof(ReadyStateChanged))] public bool readyToBegin; /// /// Diagnostic index of the player, e.g. Player1, Player2, etc. /// - [Tooltip("Diagnostic index of the player, e.g. Player1, Player2, etc.")] + [ReadOnly, Tooltip("Diagnostic index of the player, e.g. Player1, Player2, etc.")] [SyncVar(hook = nameof(IndexChanged))] public int index; #region Unity Callbacks /// - /// Do not use Start - Override OnStartrHost / OnStartClient instead! + /// Do not use Start - Override OnStartHost / OnStartClient instead! /// - public void Start() + public virtual void Start() { if (NetworkManager.singleton is NetworkRoomManager room) { // NetworkRoomPlayer object must be set to DontDestroyOnLoad along with NetworkRoomManager // in server and all clients, otherwise it will be respawned in the game scene which would - // have undesireable effects. + // have undesirable effects. if (room.dontDestroyOnLoad) DontDestroyOnLoad(gameObject); room.roomSlots.Add(this); - room.RecalculateRoomPlayerIndices(); + + if (NetworkServer.active) + room.RecalculateRoomPlayerIndices(); if (NetworkClient.active) room.CallOnClientEnterRoom(); } - else - logger.LogError("RoomPlayer could not find a NetworkRoomManager. The RoomPlayer requires a NetworkRoomManager object to function. Make sure that there is one in the scene."); + else Debug.LogError("RoomPlayer could not find a NetworkRoomManager. The RoomPlayer requires a NetworkRoomManager object to function. Make sure that there is one in the scene."); } public virtual void OnDisable() { if (NetworkClient.active && NetworkManager.singleton is NetworkRoomManager room) { + // only need to call this on client as server removes it before object is destroyed room.roomSlots.Remove(this); - room.RecalculateRoomPlayerIndices(); + + room.CallOnClientExitRoom(); } } @@ -98,19 +97,14 @@ public void CmdChangeReadyState(bool readyState) /// /// The old index value /// The new index value - public virtual void IndexChanged(int oldIndex, int newIndex) { } + public virtual void IndexChanged(int oldIndex, int newIndex) {} /// /// This is a hook that is invoked on clients when a RoomPlayer switches between ready or not ready. /// This function is called when the a client player calls CmdChangeReadyState. /// /// New Ready State - public virtual void ReadyStateChanged(bool _, bool newReadyState) - { -#pragma warning disable CS0618 // Type or member is obsolete - OnClientReady(newReadyState); -#pragma warning restore CS0618 // Type or member is obsolete - } + public virtual void ReadyStateChanged(bool oldReadyState, bool newReadyState) {} #endregion @@ -120,26 +114,19 @@ public virtual void ReadyStateChanged(bool _, bool newReadyState) /// This is a hook that is invoked on clients for all room player objects when entering the room. /// Note: isLocalPlayer is not guaranteed to be set until OnStartLocalPlayer is called. /// - public virtual void OnClientEnterRoom() { } + public virtual void OnClientEnterRoom() {} /// /// This is a hook that is invoked on clients for all room player objects when exiting the room. /// - public virtual void OnClientExitRoom() { } - - // Deprecated 05/18/2020 - /// - /// Obsolete: Override ReadyStateChanged(bool, bool) instead. - /// - [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Override ReadyStateChanged(bool, bool) instead")] - public virtual void OnClientReady(bool readyState) { } + public virtual void OnClientExitRoom() {} #endregion #region Optional UI /// - /// Render a UI for the room. Override to provide your on UI + /// Render a UI for the room. Override to provide your own UI /// public virtual void OnGUI() { @@ -152,7 +139,7 @@ public virtual void OnGUI() if (!room.showRoomGUI) return; - if (!NetworkManager.IsSceneActive(room.RoomScene)) + if (!Utils.IsSceneActive(room.RoomScene)) return; DrawPlayerReadyState(); diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkRoomPlayer.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkRoomPlayer.cs.meta index 0299beac81..f06bb70867 100644 --- a/Assets/ImportedAssets/Mirror/Components/NetworkRoomPlayer.cs.meta +++ b/Assets/ImportedAssets/Mirror/Components/NetworkRoomPlayer.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkRoomPlayer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkSceneChecker.cs b/Assets/ImportedAssets/Mirror/Components/NetworkSceneChecker.cs deleted file mode 100644 index 4e50315de0..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/NetworkSceneChecker.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.SceneManagement; - -namespace Mirror -{ - /// - /// Component that controls visibility of networked objects between scenes. - /// Any object with this component on it will only be visible to other objects in the same scene - /// This would be used when the server has multiple additive subscenes loaded to isolate players to their respective subscenes - /// - [DisallowMultipleComponent] - [AddComponentMenu("Network/NetworkSceneChecker")] - [RequireComponent(typeof(NetworkIdentity))] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkSceneChecker.html")] - public class NetworkSceneChecker : NetworkVisibility - { - static readonly ILogger logger = LogFactory.GetLogger(typeof(NetworkSceneChecker)); - - /// - /// Flag to force this object to be hidden from all observers. - /// If this object is a player object, it will not be hidden for that client. - /// - [Tooltip("Enable to force this object to be hidden from all observers.")] - public bool forceHidden; - - // Use Scene instead of string scene.name because when additively loading multiples of a subscene the name won't be unique - static readonly Dictionary> sceneCheckerObjects = new Dictionary>(); - - Scene currentScene; - - [ServerCallback] - void Awake() - { - currentScene = gameObject.scene; - if (logger.LogEnabled()) logger.Log($"NetworkSceneChecker.Awake currentScene: {currentScene}"); - } - - public override void OnStartServer() - { - if (!sceneCheckerObjects.ContainsKey(currentScene)) - sceneCheckerObjects.Add(currentScene, new HashSet()); - - sceneCheckerObjects[currentScene].Add(netIdentity); - } - - [ServerCallback] - void Update() - { - if (currentScene == gameObject.scene) - return; - - // This object is in a new scene so observers in the prior scene - // and the new scene need to rebuild their respective observers lists. - - // Remove this object from the hashset of the scene it just left - sceneCheckerObjects[currentScene].Remove(netIdentity); - - // RebuildObservers of all NetworkIdentity's in the scene this object just left - RebuildSceneObservers(); - - // Set this to the new scene this object just entered - currentScene = gameObject.scene; - - // Make sure this new scene is in the dictionary - if (!sceneCheckerObjects.ContainsKey(currentScene)) - sceneCheckerObjects.Add(currentScene, new HashSet()); - - // Add this object to the hashset of the new scene - sceneCheckerObjects[currentScene].Add(netIdentity); - - // RebuildObservers of all NetworkIdentity's in the scene this object just entered - RebuildSceneObservers(); - } - - void RebuildSceneObservers() - { - foreach (NetworkIdentity networkIdentity in sceneCheckerObjects[currentScene]) - if (networkIdentity != null) - networkIdentity.RebuildObservers(false); - } - - /// - /// Callback used by the visibility system to determine if an observer (player) can see this object. - /// If this function returns true, the network connection will be added as an observer. - /// - /// Network connection of a player. - /// True if the player can see this object. - public override bool OnCheckObserver(NetworkConnection conn) - { - if (forceHidden) - return false; - - return conn.identity.gameObject.scene == gameObject.scene; - } - - /// - /// Callback used by the visibility system to (re)construct the set of observers that can see this object. - /// Implementations of this callback should add network connections of players that can see this object to the observers set. - /// - /// The new set of observers for this object. - /// True if the set of observers is being built for the first time. - public override void OnRebuildObservers(HashSet observers, bool initialize) - { - // If forceHidden then return without adding any observers. - if (forceHidden) - return; - - // Add everything in the hashset for this object's current scene - foreach (NetworkIdentity networkIdentity in sceneCheckerObjects[currentScene]) - if (networkIdentity != null && networkIdentity.connectionToClient != null) - observers.Add(networkIdentity.connectionToClient); - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkStatistics.cs b/Assets/ImportedAssets/Mirror/Components/NetworkStatistics.cs new file mode 100644 index 0000000000..c00bb19381 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkStatistics.cs @@ -0,0 +1,194 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + /// + /// Shows Network messages and bytes sent and received per second. + /// + /// + /// Add this component to the same object as Network Manager. + /// + [AddComponentMenu("Network/Network Statistics")] + [DisallowMultipleComponent] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-statistics")] + public class NetworkStatistics : MonoBehaviour + { + // update interval + double intervalStartTime; + + // --------------------------------------------------------------------- + + // CLIENT (public fields for other components to grab statistics) + // long bytes to support >2GB + [HideInInspector] public int clientIntervalReceivedPackets; + [HideInInspector] public long clientIntervalReceivedBytes; + [HideInInspector] public int clientIntervalSentPackets; + [HideInInspector] public long clientIntervalSentBytes; + + // results from last interval + // long bytes to support >2GB + [HideInInspector] public int clientReceivedPacketsPerSecond; + [HideInInspector] public long clientReceivedBytesPerSecond; + [HideInInspector] public int clientSentPacketsPerSecond; + [HideInInspector] public long clientSentBytesPerSecond; + + // --------------------------------------------------------------------- + + // SERVER (public fields for other components to grab statistics) + // capture interval + // long bytes to support >2GB + [HideInInspector] public int serverIntervalReceivedPackets; + [HideInInspector] public long serverIntervalReceivedBytes; + [HideInInspector] public int serverIntervalSentPackets; + [HideInInspector] public long serverIntervalSentBytes; + + // results from last interval + // long bytes to support >2GB + [HideInInspector] public int serverReceivedPacketsPerSecond; + [HideInInspector] public long serverReceivedBytesPerSecond; + [HideInInspector] public int serverSentPacketsPerSecond; + [HideInInspector] public long serverSentBytesPerSecond; + + // NetworkManager sets Transport.active in Awake(). + // so let's hook into it in Start(). + void Start() + { + // find available transport + Transport transport = Transport.active; + if (transport != null) + { + transport.OnClientDataReceived += OnClientReceive; + transport.OnClientDataSent += OnClientSend; + transport.OnServerDataReceived += OnServerReceive; + transport.OnServerDataSent += OnServerSend; + } + else Debug.LogError($"NetworkStatistics: no available or active Transport found on this platform: {Application.platform}"); + } + + void OnDestroy() + { + // remove transport hooks + Transport transport = Transport.active; + if (transport != null) + { + transport.OnClientDataReceived -= OnClientReceive; + transport.OnClientDataSent -= OnClientSend; + transport.OnServerDataReceived -= OnServerReceive; + transport.OnServerDataSent -= OnServerSend; + } + } + + void OnClientReceive(ArraySegment data, int channelId) + { + ++clientIntervalReceivedPackets; + clientIntervalReceivedBytes += data.Count; + } + + void OnClientSend(ArraySegment data, int channelId) + { + ++clientIntervalSentPackets; + clientIntervalSentBytes += data.Count; + } + + void OnServerReceive(int connectionId, ArraySegment data, int channelId) + { + ++serverIntervalReceivedPackets; + serverIntervalReceivedBytes += data.Count; + } + + void OnServerSend(int connectionId, ArraySegment data, int channelId) + { + ++serverIntervalSentPackets; + serverIntervalSentBytes += data.Count; + } + + void Update() + { + // calculate results every second + if (NetworkTime.localTime >= intervalStartTime + 1) + { + if (NetworkClient.active) UpdateClient(); + if (NetworkServer.active) UpdateServer(); + + intervalStartTime = NetworkTime.localTime; + } + } + + void UpdateClient() + { + clientReceivedPacketsPerSecond = clientIntervalReceivedPackets; + clientReceivedBytesPerSecond = clientIntervalReceivedBytes; + clientSentPacketsPerSecond = clientIntervalSentPackets; + clientSentBytesPerSecond = clientIntervalSentBytes; + + clientIntervalReceivedPackets = 0; + clientIntervalReceivedBytes = 0; + clientIntervalSentPackets = 0; + clientIntervalSentBytes = 0; + } + + void UpdateServer() + { + serverReceivedPacketsPerSecond = serverIntervalReceivedPackets; + serverReceivedBytesPerSecond = serverIntervalReceivedBytes; + serverSentPacketsPerSecond = serverIntervalSentPackets; + serverSentBytesPerSecond = serverIntervalSentBytes; + + serverIntervalReceivedPackets = 0; + serverIntervalReceivedBytes = 0; + serverIntervalSentPackets = 0; + serverIntervalSentBytes = 0; + } + + void OnGUI() + { + // only show if either server or client active + if (NetworkClient.active || NetworkServer.active) + { + // create main GUI area + // 120 is below NetworkManager HUD in all cases. + GUILayout.BeginArea(new Rect(10, 120, 215, 300)); + + // show client / server stats if active + if (NetworkClient.active) OnClientGUI(); + if (NetworkServer.active) OnServerGUI(); + + // end of GUI area + GUILayout.EndArea(); + } + } + + void OnClientGUI() + { + // background + GUILayout.BeginVertical("Box"); + GUILayout.Label("Client Statistics"); + + // sending ("msgs" instead of "packets" to fit larger numbers) + GUILayout.Label($"Send: {clientSentPacketsPerSecond} msgs @ {Utils.PrettyBytes(clientSentBytesPerSecond)}/s"); + + // receiving ("msgs" instead of "packets" to fit larger numbers) + GUILayout.Label($"Recv: {clientReceivedPacketsPerSecond} msgs @ {Utils.PrettyBytes(clientReceivedBytesPerSecond)}/s"); + + // end background + GUILayout.EndVertical(); + } + + void OnServerGUI() + { + // background + GUILayout.BeginVertical("Box"); + GUILayout.Label("Server Statistics"); + + // sending ("msgs" instead of "packets" to fit larger numbers) + GUILayout.Label($"Send: {serverSentPacketsPerSecond} msgs @ {Utils.PrettyBytes(serverSentBytesPerSecond)}/s"); + + // receiving ("msgs" instead of "packets" to fit larger numbers) + GUILayout.Label($"Recv: {serverReceivedPacketsPerSecond} msgs @ {Utils.PrettyBytes(serverReceivedBytesPerSecond)}/s"); + + // end background + GUILayout.EndVertical(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkStatistics.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkStatistics.cs.meta new file mode 100644 index 0000000000..6849fa52c7 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkStatistics.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 6d7da4e566d24ea7b0e12178d934b648 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkStatistics.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransform.cs deleted file mode 100644 index c6b7adcc68..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/NetworkTransform.cs +++ /dev/null @@ -1,12 +0,0 @@ -using UnityEngine; - -namespace Mirror -{ - [DisallowMultipleComponent] - [AddComponentMenu("Network/NetworkTransform")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkTransform.html")] - public class NetworkTransform : NetworkTransformBase - { - protected override Transform targetComponent => transform; - } -} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransform.cs.meta deleted file mode 100644 index a569990f7a..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/NetworkTransform.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2f74aedd71d9a4f55b3ce499326d45fb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransform.meta new file mode 100644 index 0000000000..1b6770d4ee --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 36de72d9255741659bcbd1971ed29822 +timeCreated: 1668358590 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransform.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransform.cs new file mode 100644 index 0000000000..9e6a30e42f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransform.cs @@ -0,0 +1,10 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + // DEPRECATED 2023-06-15 + [AddComponentMenu("")] + [Obsolete("NetworkTransform was renamed to NetworkTransformUnreliable.\nYou can easily swap the component's script by going into the Unity Inspector debug mode:\n1. Click the vertical dots on the top right in the Inspector tab.\n2. Find your NetworkTransform component\n3. Drag NetworkTransformUnreliable into the 'Script' field in the Inspector.\n4. Find the three dots and return to Normal mode.")] + public class NetworkTransform : NetworkTransformUnreliable {} +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransform.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransform.cs.meta new file mode 100644 index 0000000000..e07da42a05 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransform.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 2f74aedd71d9a4f55b3ce499326d45fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransform.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs new file mode 100644 index 0000000000..a30f5d9c0d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs @@ -0,0 +1,499 @@ +// Snapshot Interpolation: https://gafferongames.com/post/snapshot_interpolation/ +// +// Base class for NetworkTransform and NetworkTransformChild. +// => simple unreliable sync without any interpolation for now. +// => which means we don't need teleport detection either +// +// NOTE: several functions are virtual in case someone needs to modify a part. +// +// Channel: uses UNRELIABLE at all times. +// -> out of order packets are dropped automatically +// -> it's better than RELIABLE for several reasons: +// * head of line blocking would add delay +// * resending is mostly pointless +// * bigger data race: +// -> if we use a Cmd() at position X over reliable +// -> client gets Cmd() and X at the same time, but buffers X for bufferTime +// -> for unreliable, it would get X before the reliable Cmd(), still +// buffer for bufferTime but end up closer to the original time +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + public enum CoordinateSpace { Local, World } + + public abstract class NetworkTransformBase : NetworkBehaviour + { + // target transform to sync. can be on a child. + // TODO this field is kind of unnecessary since we now support child NetworkBehaviours + [Header("Target")] + [Tooltip("The Transform component to sync. May be on on this GameObject, or on a child.")] + public Transform target; + + // Is this a client with authority over this transform? + // This component could be on the player object or any object that has been assigned authority to this client. + protected bool IsClientWithAuthority => isClient && authority; + + // snapshots with initial capacity to avoid early resizing & allocations: see NetworkRigidbodyBenchmark example. + public readonly SortedList clientSnapshots = new SortedList(16); + public readonly SortedList serverSnapshots = new SortedList(16); + + // selective sync ////////////////////////////////////////////////////// + [Header("Selective Sync\nDon't change these at Runtime")] + public bool syncPosition = true; // do not change at runtime! + public bool syncRotation = true; // do not change at runtime! + public bool syncScale = false; // do not change at runtime! rare. off by default. + + [Header("Bandwidth Savings")] + [Tooltip("When true, changes are not sent unless greater than sensitivity values below.")] + public bool onlySyncOnChange = true; + [Tooltip("Apply smallest-three quaternion compression. This is lossy, you can disable it if the small rotation inaccuracies are noticeable in your project.")] + public bool compressRotation = true; + + // interpolation is on by default, but can be disabled to jump to + // the destination immediately. some projects need this. + [Header("Interpolation")] + [Tooltip("Set to false to have a snap-like effect on position movement.")] + public bool interpolatePosition = true; + [Tooltip("Set to false to have a snap-like effect on rotations.")] + public bool interpolateRotation = true; + [Tooltip("Set to false to remove scale smoothing. Example use-case: Instant flipping of sprites that use -X and +X for direction.")] + public bool interpolateScale = true; + + // CoordinateSpace /////////////////////////////////////////////////////////// + [Header("Coordinate Space")] + [Tooltip("Local by default. World may be better when changing hierarchy, or non-NetworkTransforms root position/rotation/scale values.")] + public CoordinateSpace coordinateSpace = CoordinateSpace.Local; + + [Header("Send Interval Multiplier")] + [Tooltip("Check/Sync every multiple of Network Manager send interval (= 1 / NM Send Rate), instead of every send interval.\n(30 NM send rate, and 3 interval, is a send every 0.1 seconds)\nA larger interval means less network sends, which has a variety of upsides. The drawbacks are delays and lower accuracy, you should find a nice balance between not sending too much, but the results looking good for your particular scenario.")] + [Range(1, 120)] + public uint sendIntervalMultiplier = 1; + + [Header("Timeline Offset")] + [Tooltip("Add a small timeline offset to account for decoupled arrival of NetworkTime and NetworkTransform snapshots.\nfixes: https://github.com/MirrorNetworking/Mirror/issues/3427")] + public bool timelineOffset = false; + + // Ninja's Notes on offset & mulitplier: + // + // In a no multiplier scenario: + // 1. Snapshots are sent every frame (frame being 1 NM send interval). + // 2. Time Interpolation is set to be 'behind' by 2 frames times. + // In theory where everything works, we probably have around 2 snapshots before we need to interpolate snapshots. From NT perspective, we should always have around 2 snapshots ready, so no stutter. + // + // In a multiplier scenario: + // 1. Snapshots are sent every 10 frames. + // 2. Time Interpolation remains 'behind by 2 frames'. + // When everything works, we are receiving NT snapshots every 10 frames, but start interpolating after 2. + // Even if I assume we had 2 snapshots to begin with to start interpolating (which we don't), by the time we reach 13th frame, we are out of snapshots, and have to wait 7 frames for next snapshot to come. This is the reason why we absolutely need the timestamp adjustment. We are starting way too early to interpolate. + // + protected double timeStampAdjustment => NetworkServer.sendInterval * (sendIntervalMultiplier - 1); + protected double offset => timelineOffset ? NetworkServer.sendInterval * sendIntervalMultiplier : 0; + + // debugging /////////////////////////////////////////////////////////// + [Header("Debug")] + public bool showGizmos; + public bool showOverlay; + public Color overlayColor = new Color(0, 0, 0, 0.5f); + + // initialization ////////////////////////////////////////////////////// + // forcec configuration of some settings + protected virtual void Configure() + { + // set target to self if none yet + if (target == null) target = transform; + + // time snapshot interpolation happens globally. + // value (transform) happens in here. + // both always need to be on the same send interval. + // force the setting to '0' in OnValidate to make it obvious that we + // actually use NetworkServer.sendInterval. + syncInterval = 0; + + // Unity doesn't support setting world scale. + // OnValidate force disables syncScale in world mode. + if (coordinateSpace == CoordinateSpace.World) syncScale = false; + } + + // make sure to call this when inheriting too! + protected virtual void Awake() + { + // sometimes OnValidate() doesn't run before launching a project. + // need to guarantee configuration runs. + Configure(); + } + + protected override void OnValidate() + { + base.OnValidate(); + + // configure in awake + Configure(); + } + + // snapshot functions ////////////////////////////////////////////////// + // get local/world position + protected virtual Vector3 GetPosition() => + coordinateSpace == CoordinateSpace.Local ? target.localPosition : target.position; + + // get local/world rotation + protected virtual Quaternion GetRotation() => + coordinateSpace == CoordinateSpace.Local ? target.localRotation : target.rotation; + + // get local/world scale + protected virtual Vector3 GetScale() => + coordinateSpace == CoordinateSpace.Local ? target.localScale : target.lossyScale; + + // set local/world position + protected virtual void SetPosition(Vector3 position) + { + if (coordinateSpace == CoordinateSpace.Local) + target.localPosition = position; + else + target.position = position; + } + + // set local/world rotation + protected virtual void SetRotation(Quaternion rotation) + { + if (coordinateSpace == CoordinateSpace.Local) + target.localRotation = rotation; + else + target.rotation = rotation; + } + + // set local/world position + protected virtual void SetScale(Vector3 scale) + { + if (coordinateSpace == CoordinateSpace.Local) + target.localScale = scale; + // Unity doesn't support setting world scale. + // OnValidate disables syncScale in world mode. + // else + // target.lossyScale = scale; // TODO + } + + // construct a snapshot of the current state + // => internal for testing + protected virtual TransformSnapshot Construct() + { + // NetworkTime.localTime for double precision until Unity has it too + return new TransformSnapshot( + // our local time is what the other end uses as remote time + NetworkTime.localTime, // Unity 2019 doesn't have timeAsDouble yet + 0, // the other end fills out local time itself + GetPosition(), + GetRotation(), + GetScale() + ); + } + + protected void AddSnapshot(SortedList snapshots, double timeStamp, Vector3? position, Quaternion? rotation, Vector3? scale) + { + // position, rotation, scale can have no value if same as last time. + // saves bandwidth. + // but we still need to feed it to snapshot interpolation. we can't + // just have gaps in there if nothing has changed. for example, if + // client sends snapshot at t=0 + // client sends nothing for 10s because not moved + // client sends snapshot at t=10 + // then the server would assume that it's one super slow move and + // replay it for 10 seconds. + + if (!position.HasValue) position = snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].position : GetPosition(); + if (!rotation.HasValue) rotation = snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].rotation : GetRotation(); + if (!scale.HasValue) scale = snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].scale : GetScale(); + + // insert transform snapshot + SnapshotInterpolation.InsertIfNotExists( + snapshots, + NetworkClient.snapshotSettings.bufferLimit, + new TransformSnapshot( + timeStamp, // arrival remote timestamp. NOT remote time. + NetworkTime.localTime, // Unity 2019 doesn't have timeAsDouble yet + position.Value, + rotation.Value, + scale.Value + ) + ); + } + + // apply a snapshot to the Transform. + // -> start, end, interpolated are all passed in caes they are needed + // -> a regular game would apply the 'interpolated' snapshot + // -> a board game might want to jump to 'goal' directly + // (it's easier to always interpolate and then apply selectively, + // instead of manually interpolating x, y, z, ... depending on flags) + // => internal for testing + // + // NOTE: stuck detection is unnecessary here. + // we always set transform.position anyway, we can't get stuck. + protected virtual void Apply(TransformSnapshot interpolated, TransformSnapshot endGoal) + { + // local position/rotation for VR support + // + // if syncPosition/Rotation/Scale is disabled then we received nulls + // -> current position/rotation/scale would've been added as snapshot + // -> we still interpolated + // -> but simply don't apply it. if the user doesn't want to sync + // scale, then we should not touch scale etc. + + // interpolate parts + if (syncPosition) SetPosition(interpolatePosition ? interpolated.position : endGoal.position); + if (syncRotation) SetRotation(interpolateRotation ? interpolated.rotation : endGoal.rotation); + if (syncScale) SetScale(interpolateScale ? interpolated.scale : endGoal.scale); + } + + // client->server teleport to force position without interpolation. + // otherwise it would interpolate to a (far away) new position. + // => manually calling Teleport is the only 100% reliable solution. + [Command] + public void CmdTeleport(Vector3 destination) + { + // client can only teleport objects that it has authority over. + if (syncDirection != SyncDirection.ClientToServer) return; + + // TODO what about host mode? + OnTeleport(destination); + + // if a client teleports, we need to broadcast to everyone else too + // TODO the teleported client should ignore the rpc though. + // otherwise if it already moved again after teleporting, + // the rpc would come a little bit later and reset it once. + // TODO or not? if client ONLY calls Teleport(pos), the position + // would only be set after the rpc. unless the client calls + // BOTH Teleport(pos) and target.position=pos + RpcTeleport(destination); + } + + // client->server teleport to force position and rotation without interpolation. + // otherwise it would interpolate to a (far away) new position. + // => manually calling Teleport is the only 100% reliable solution. + [Command] + public void CmdTeleport(Vector3 destination, Quaternion rotation) + { + // client can only teleport objects that it has authority over. + if (syncDirection != SyncDirection.ClientToServer) return; + + // TODO what about host mode? + OnTeleport(destination, rotation); + + // if a client teleports, we need to broadcast to everyone else too + // TODO the teleported client should ignore the rpc though. + // otherwise if it already moved again after teleporting, + // the rpc would come a little bit later and reset it once. + // TODO or not? if client ONLY calls Teleport(pos), the position + // would only be set after the rpc. unless the client calls + // BOTH Teleport(pos) and target.position=pos + RpcTeleport(destination, rotation); + } + + // server->client teleport to force position without interpolation. + // otherwise it would interpolate to a (far away) new position. + // => manually calling Teleport is the only 100% reliable solution. + [ClientRpc] + public void RpcTeleport(Vector3 destination) + { + // NOTE: even in client authority mode, the server is always allowed + // to teleport the player. for example: + // * CmdEnterPortal() might teleport the player + // * Some people use client authority with server sided checks + // so the server should be able to reset position if needed. + + // TODO what about host mode? + OnTeleport(destination); + } + + // server->client teleport to force position and rotation without interpolation. + // otherwise it would interpolate to a (far away) new position. + // => manually calling Teleport is the only 100% reliable solution. + [ClientRpc] + public void RpcTeleport(Vector3 destination, Quaternion rotation) + { + // NOTE: even in client authority mode, the server is always allowed + // to teleport the player. for example: + // * CmdEnterPortal() might teleport the player + // * Some people use client authority with server sided checks + // so the server should be able to reset position if needed. + + // TODO what about host mode? + OnTeleport(destination, rotation); + } + + [ClientRpc] + void RpcResetState() + { + ResetState(); + } + + // common Teleport code for client->server and server->client + protected virtual void OnTeleport(Vector3 destination) + { + // set the new position. + // interpolation will automatically continue. + target.position = destination; + + // reset interpolation to immediately jump to the new position. + // do not call Reset() here, this would cause delta compression to + // get out of sync for NetworkTransformReliable because NTReliable's + // 'override Reset()' resets lastDe/SerializedPosition: + // https://github.com/MirrorNetworking/Mirror/issues/3588 + // because client's next OnSerialize() will delta compress, + // but server's last delta will have been reset, causing offsets. + // + // instead, simply clear snapshots. + ResetState(); + + // TODO + // what if we still receive a snapshot from before the interpolation? + // it could easily happen over unreliable. + // -> maybe add destination as first entry? + } + + // common Teleport code for client->server and server->client + protected virtual void OnTeleport(Vector3 destination, Quaternion rotation) + { + // set the new position. + // interpolation will automatically continue. + target.position = destination; + target.rotation = rotation; + + // reset interpolation to immediately jump to the new position. + // do not call Reset() here, this would cause delta compression to + // get out of sync for NetworkTransformReliable because NTReliable's + // 'override Reset()' resets lastDe/SerializedPosition: + // https://github.com/MirrorNetworking/Mirror/issues/3588 + // because client's next OnSerialize() will delta compress, + // but server's last delta will have been reset, causing offsets. + // + // instead, simply clear snapshots. + ResetState(); + + // TODO + // what if we still receive a snapshot from before the interpolation? + // it could easily happen over unreliable. + // -> maybe add destination as first entry? + } + + public virtual void ResetState() + { + // disabled objects aren't updated anymore. + // so let's clear the buffers. + serverSnapshots.Clear(); + clientSnapshots.Clear(); + } + + public virtual void Reset() + { + ResetState(); + // default to ClientToServer so this works immediately for users + syncDirection = SyncDirection.ClientToServer; + } + + protected virtual void OnEnable() + { + ResetState(); + + if (NetworkServer.active) + NetworkIdentity.clientAuthorityCallback += OnClientAuthorityChanged; + } + + protected virtual void OnDisable() + { + ResetState(); + + if (NetworkServer.active) + NetworkIdentity.clientAuthorityCallback -= OnClientAuthorityChanged; + } + + [ServerCallback] + void OnClientAuthorityChanged(NetworkConnectionToClient conn, NetworkIdentity identity, bool authorityState) + { + if (identity != netIdentity) return; + + // If server gets authority or syncdirection is server to client, + // we don't reset buffers. + // This is because if syncdirection is S to C, we will never have + // snapshot issues since there is only ever 1 source. + + if (syncDirection == SyncDirection.ClientToServer) + { + ResetState(); + RpcResetState(); + } + } + + // OnGUI allocates even if it does nothing. avoid in release. +#if UNITY_EDITOR || DEVELOPMENT_BUILD + // debug /////////////////////////////////////////////////////////////// + protected virtual void OnGUI() + { + if (!showOverlay) return; + if (!Camera.main) return; + + // show data next to player for easier debugging. this is very useful! + // IMPORTANT: this is basically an ESP hack for shooter games. + // DO NOT make this available with a hotkey in release builds + if (!Debug.isDebugBuild) return; + + // project position to screen + Vector3 point = Camera.main.WorldToScreenPoint(target.position); + + // enough alpha, in front of camera and in screen? + if (point.z >= 0 && Utils.IsPointInScreen(point)) + { + GUI.color = overlayColor; + GUILayout.BeginArea(new Rect(point.x, Screen.height - point.y, 200, 100)); + + // always show both client & server buffers so it's super + // obvious if we accidentally populate both. + GUILayout.Label($"Server Buffer:{serverSnapshots.Count}"); + GUILayout.Label($"Client Buffer:{clientSnapshots.Count}"); + + GUILayout.EndArea(); + GUI.color = Color.white; + } + } + + protected virtual void DrawGizmos(SortedList buffer) + { + // only draw if we have at least two entries + if (buffer.Count < 2) return; + + // calculate threshold for 'old enough' snapshots + double threshold = NetworkTime.localTime - NetworkClient.bufferTime; + Color oldEnoughColor = new Color(0, 1, 0, 0.5f); + Color notOldEnoughColor = new Color(0.5f, 0.5f, 0.5f, 0.3f); + + // draw the whole buffer for easier debugging. + // it's worth seeing how much we have buffered ahead already + for (int i = 0; i < buffer.Count; ++i) + { + // color depends on if old enough or not + TransformSnapshot entry = buffer.Values[i]; + bool oldEnough = entry.localTime <= threshold; + Gizmos.color = oldEnough ? oldEnoughColor : notOldEnoughColor; + Gizmos.DrawWireCube(entry.position, Vector3.one); + } + + // extra: lines between start<->position<->goal + Gizmos.color = Color.green; + Gizmos.DrawLine(buffer.Values[0].position, target.position); + Gizmos.color = Color.white; + Gizmos.DrawLine(target.position, buffer.Values[1].position); + } + + protected virtual void OnDrawGizmos() + { + // This fires in edit mode but that spams NRE's so check isPlaying + if (!Application.isPlaying) return; + if (!showGizmos) return; + + if (isServer) DrawGizmos(serverSnapshots); + if (isClient) DrawGizmos(clientSnapshots); + } +#endif + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs.meta new file mode 100644 index 0000000000..8c50378e9f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 7c44135fde488424eaf28566206ce473 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs new file mode 100644 index 0000000000..a844d9d84e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs @@ -0,0 +1,12 @@ +// A component to synchronize the position of child transforms of networked objects. +// There must be a NetworkTransform on the root object of the hierarchy. There can be multiple NetworkTransformChild components on an object. This does not use physics for synchronization, it simply synchronizes the localPosition and localRotation of the child transform and lerps towards the recieved values. +using System; +using UnityEngine; + +namespace Mirror +{ + // Deprecated 2022-10-25 + [AddComponentMenu("")] + [Obsolete("NetworkTransformChild is not needed anymore. The .target is now exposed in NetworkTransform itself. Note you can open the Inspector in debug view and replace the source script instead of reassigning everything.")] + public class NetworkTransformChild : NetworkTransform {} +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs.meta new file mode 100644 index 0000000000..53722cd27c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 734b48bea0b204338958ee3d885e11f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs new file mode 100644 index 0000000000..fd87ff2c5f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs @@ -0,0 +1,421 @@ +// NetworkTransform V3 (reliable) by mischa (2022-10) +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/Network Transform (Reliable)")] + public class NetworkTransformReliable : NetworkTransformBase + { + uint sendIntervalCounter = 0; + double lastSendIntervalTime = double.MinValue; + + [Header("Additional Settings")] + [Tooltip("If we only sync on change, then we need to correct old snapshots if more time than sendInterval * multiplier has elapsed.\n\nOtherwise the first move will always start interpolating from the last move sequence's time, which will make it stutter when starting every time.")] + public float onlySyncOnChangeCorrectionMultiplier = 2; + + [Header("Rotation")] + [Tooltip("Sensitivity of changes needed before an updated state is sent over the network")] + public float rotationSensitivity = 0.01f; + + // delta compression is capable of detecting byte-level changes. + // if we scale float position to bytes, + // then small movements will only change one byte. + // this gives optimal bandwidth. + // benchmark with 0.01 precision: 130 KB/s => 60 KB/s + // benchmark with 0.1 precision: 130 KB/s => 30 KB/s + [Header("Precision")] + [Tooltip("Position is rounded in order to drastically minimize bandwidth.\n\nFor example, a precision of 0.01 rounds to a centimeter. In other words, sub-centimeter movements aren't synced until they eventually exceeded an actual centimeter.\n\nDepending on how important the object is, a precision of 0.01-0.10 (1-10 cm) is recommended.\n\nFor example, even a 1cm precision combined with delta compression cuts the Benchmark demo's bandwidth in half, compared to sending every tiny change.")] + [Range(0.00_01f, 1f)] // disallow 0 division. 1mm to 1m precision is enough range. + public float positionPrecision = 0.01f; // 1 cm + [Range(0.00_01f, 1f)] // disallow 0 division. 1mm to 1m precision is enough range. + public float scalePrecision = 0.01f; // 1 cm + + // delta compression needs to remember 'last' to compress against + protected Vector3Long lastSerializedPosition = Vector3Long.zero; + protected Vector3Long lastDeserializedPosition = Vector3Long.zero; + + protected Vector3Long lastSerializedScale = Vector3Long.zero; + protected Vector3Long lastDeserializedScale = Vector3Long.zero; + + // Used to store last sent snapshots + protected TransformSnapshot last; + + protected int lastClientCount = 1; + + // update ////////////////////////////////////////////////////////////// + void Update() + { + // if server then always sync to others. + if (isServer) UpdateServer(); + // 'else if' because host mode shouldn't send anything to server. + // it is the server. don't overwrite anything there. + else if (isClient) UpdateClient(); + } + + void LateUpdate() + { + // set dirty to trigger OnSerialize. either always, or only if changed. + // It has to be checked in LateUpdate() for onlySyncOnChange to avoid + // the possibility of Update() running first before the object's movement + // script's Update(), which then causes NT to send every alternate frame + // instead. + if (isServer || (IsClientWithAuthority && NetworkClient.ready)) + { + if (sendIntervalCounter == sendIntervalMultiplier && (!onlySyncOnChange || Changed(Construct()))) + SetDirty(); + + CheckLastSendTime(); + } + } + + protected virtual void UpdateServer() + { + // apply buffered snapshots IF client authority + // -> in server authority, server moves the object + // so no need to apply any snapshots there. + // -> don't apply for host mode player objects either, even if in + // client authority mode. if it doesn't go over the network, + // then we don't need to do anything. + // -> connectionToClient is briefly null after scene changes: + // https://github.com/MirrorNetworking/Mirror/issues/3329 + if (syncDirection == SyncDirection.ClientToServer && + connectionToClient != null && + !isOwned) + { + if (serverSnapshots.Count > 0) + { + // step the transform interpolation without touching time. + // NetworkClient is responsible for time globally. + SnapshotInterpolation.StepInterpolation( + serverSnapshots, + connectionToClient.remoteTimeline, + out TransformSnapshot from, + out TransformSnapshot to, + out double t); + + // interpolate & apply + TransformSnapshot computed = TransformSnapshot.Interpolate(from, to, t); + Apply(computed, to); + } + } + } + + protected virtual void UpdateClient() + { + // client authority, and local player (= allowed to move myself)? + if (!IsClientWithAuthority) + { + // only while we have snapshots + if (clientSnapshots.Count > 0) + { + // step the interpolation without touching time. + // NetworkClient is responsible for time globally. + SnapshotInterpolation.StepInterpolation( + clientSnapshots, + NetworkTime.time, // == NetworkClient.localTimeline from snapshot interpolation + out TransformSnapshot from, + out TransformSnapshot to, + out double t); + + // interpolate & apply + TransformSnapshot computed = TransformSnapshot.Interpolate(from, to, t); + Apply(computed, to); + } + + lastClientCount = clientSnapshots.Count; + } + } + + protected virtual void CheckLastSendTime() + { + // timeAsDouble not available in older Unity versions. + if (AccurateInterval.Elapsed(NetworkTime.localTime, NetworkServer.sendInterval, ref lastSendIntervalTime)) + { + if (sendIntervalCounter == sendIntervalMultiplier) + sendIntervalCounter = 0; + sendIntervalCounter++; + } + } + + // check if position / rotation / scale changed since last sync + protected virtual bool Changed(TransformSnapshot current) => + // position is quantized and delta compressed. + // only consider it changed if the quantized representation is changed. + // careful: don't use 'serialized / deserialized last'. as it depends on sync mode etc. + QuantizedChanged(last.position, current.position, positionPrecision) || + // rotation isn't quantized / delta compressed. + // check with sensitivity. + Quaternion.Angle(last.rotation, current.rotation) > rotationSensitivity || + // scale is quantized and delta compressed. + // only consider it changed if the quantized representation is changed. + // careful: don't use 'serialized / deserialized last'. as it depends on sync mode etc. + QuantizedChanged(last.scale, current.scale, scalePrecision); + + // helper function to compare quantized representations of a Vector3 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected bool QuantizedChanged(Vector3 u, Vector3 v, float precision) + { + Compression.ScaleToLong(u, precision, out Vector3Long uQuantized); + Compression.ScaleToLong(v, precision, out Vector3Long vQuantized); + return uQuantized != vQuantized; + } + + // NT may be used on client/server/host to Owner/Observers with + // ServerToClient or ClientToServer. + // however, OnSerialize should always delta against last. + public override void OnSerialize(NetworkWriter writer, bool initialState) + { + // get current snapshot for broadcasting. + TransformSnapshot snapshot = Construct(); + + // ClientToServer optimization: + // for interpolated client owned identities, + // always broadcast the latest known snapshot so other clients can + // interpolate immediately instead of catching up too + + // TODO dirty mask? [compression is very good w/o it already] + // each vector's component is delta compressed. + // an unchanged component would still require 1 byte. + // let's use a dirty bit mask to filter those out as well. + + // initial + if (initialState) + { + // If there is a last serialized snapshot, we use it. + // This prevents the new client getting a snapshot that is different + // from what the older clients last got. If this happens, and on the next + // regular serialisation the delta compression will get wrong values. + // Notes: + // 1. Interestingly only the older clients have it wrong, because at the end + // of this function, last = snapshot which is the initial state's snapshot + // 2. Regular NTR gets by this bug because it sends every frame anyway so initialstate + // snapshot constructed would have been the same as the last anyway. + if (last.remoteTime > 0) snapshot = last; + if (syncPosition) writer.WriteVector3(snapshot.position); + if (syncRotation) + { + // (optional) smallest three compression for now. no delta. + if (compressRotation) + writer.WriteUInt(Compression.CompressQuaternion(snapshot.rotation)); + else + writer.WriteQuaternion(snapshot.rotation); + } + if (syncScale) writer.WriteVector3(snapshot.scale); + } + // delta + else + { + // int before = writer.Position; + + if (syncPosition) + { + // quantize -> delta -> varint + Compression.ScaleToLong(snapshot.position, positionPrecision, out Vector3Long quantized); + DeltaCompression.Compress(writer, lastSerializedPosition, quantized); + } + if (syncRotation) + { + // (optional) smallest three compression for now. no delta. + if (compressRotation) + writer.WriteUInt(Compression.CompressQuaternion(snapshot.rotation)); + else + writer.WriteQuaternion(snapshot.rotation); + } + if (syncScale) + { + // quantize -> delta -> varint + Compression.ScaleToLong(snapshot.scale, scalePrecision, out Vector3Long quantized); + DeltaCompression.Compress(writer, lastSerializedScale, quantized); + } + } + + // save serialized as 'last' for next delta compression + if (syncPosition) Compression.ScaleToLong(snapshot.position, positionPrecision, out lastSerializedPosition); + if (syncScale) Compression.ScaleToLong(snapshot.scale, scalePrecision, out lastSerializedScale); + + // set 'last' + last = snapshot; + } + + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + Vector3? position = null; + Quaternion? rotation = null; + Vector3? scale = null; + + // initial + if (initialState) + { + if (syncPosition) position = reader.ReadVector3(); + if (syncRotation) + { + // (optional) smallest three compression for now. no delta. + if (compressRotation) + rotation = Compression.DecompressQuaternion(reader.ReadUInt()); + else + rotation = reader.ReadQuaternion(); + } + if (syncScale) scale = reader.ReadVector3(); + } + // delta + else + { + // varint -> delta -> quantize + if (syncPosition) + { + Vector3Long quantized = DeltaCompression.Decompress(reader, lastDeserializedPosition); + position = Compression.ScaleToFloat(quantized, positionPrecision); + } + if (syncRotation) + { + // (optional) smallest three compression for now. no delta. + if (compressRotation) + rotation = Compression.DecompressQuaternion(reader.ReadUInt()); + else + rotation = reader.ReadQuaternion(); + } + if (syncScale) + { + Vector3Long quantized = DeltaCompression.Decompress(reader, lastDeserializedScale); + scale = Compression.ScaleToFloat(quantized, scalePrecision); + } + } + + // handle depending on server / client / host. + // server has priority for host mode. + if (isServer) OnClientToServerSync(position, rotation, scale); + else if (isClient) OnServerToClientSync(position, rotation, scale); + + // save deserialized as 'last' for next delta compression + if (syncPosition) Compression.ScaleToLong(position.Value, positionPrecision, out lastDeserializedPosition); + if (syncScale) Compression.ScaleToLong(scale.Value, scalePrecision, out lastDeserializedScale); + } + + // sync //////////////////////////////////////////////////////////////// + + // local authority client sends sync message to server for broadcasting + protected virtual void OnClientToServerSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + // only apply if in client authority mode + if (syncDirection != SyncDirection.ClientToServer) return; + + // protect against ever growing buffer size attacks + if (serverSnapshots.Count >= connectionToClient.snapshotBufferSizeLimit) return; + + // 'only sync on change' needs a correction on every new move sequence. + if (onlySyncOnChange && + NeedsCorrection(serverSnapshots, connectionToClient.remoteTimeStamp, NetworkServer.sendInterval * sendIntervalMultiplier, onlySyncOnChangeCorrectionMultiplier)) + { + RewriteHistory( + serverSnapshots, + connectionToClient.remoteTimeStamp, + NetworkTime.localTime, // arrival remote timestamp. NOT remote timeline. + NetworkServer.sendInterval * sendIntervalMultiplier, // Unity 2019 doesn't have timeAsDouble yet + GetPosition(), + GetRotation(), + GetScale()); + } + + // add a small timeline offset to account for decoupled arrival of + // NetworkTime and NetworkTransform snapshots. + // needs to be sendInterval. half sendInterval doesn't solve it. + // https://github.com/MirrorNetworking/Mirror/issues/3427 + // remove this after LocalWorldState. + AddSnapshot(serverSnapshots, connectionToClient.remoteTimeStamp + timeStampAdjustment + offset, position, rotation, scale); + } + + // server broadcasts sync message to all clients + protected virtual void OnServerToClientSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + // don't apply for local player with authority + if (IsClientWithAuthority) return; + + // 'only sync on change' needs a correction on every new move sequence. + if (onlySyncOnChange && + NeedsCorrection(clientSnapshots, NetworkClient.connection.remoteTimeStamp, NetworkClient.sendInterval * sendIntervalMultiplier, onlySyncOnChangeCorrectionMultiplier)) + { + RewriteHistory( + clientSnapshots, + NetworkClient.connection.remoteTimeStamp, // arrival remote timestamp. NOT remote timeline. + NetworkTime.localTime, // Unity 2019 doesn't have timeAsDouble yet + NetworkClient.sendInterval * sendIntervalMultiplier, + GetPosition(), + GetRotation(), + GetScale()); + } + + // add a small timeline offset to account for decoupled arrival of + // NetworkTime and NetworkTransform snapshots. + // needs to be sendInterval. half sendInterval doesn't solve it. + // https://github.com/MirrorNetworking/Mirror/issues/3427 + // remove this after LocalWorldState. + AddSnapshot(clientSnapshots, NetworkClient.connection.remoteTimeStamp + timeStampAdjustment + offset, position, rotation, scale); + } + + // only sync on change ///////////////////////////////////////////////// + // snap interp. needs a continous flow of packets. + // 'only sync on change' interrupts it while not changed. + // once it restarts, snap interp. will interp from the last old position. + // this will cause very noticeable stutter for the first move each time. + // the fix is quite simple. + + // 1. detect if the remaining snapshot is too old from a past move. + static bool NeedsCorrection( + SortedList snapshots, + double remoteTimestamp, + double bufferTime, + double toleranceMultiplier) => + snapshots.Count == 1 && + remoteTimestamp - snapshots.Keys[0] >= bufferTime * toleranceMultiplier; + + // 2. insert a fake snapshot at current position, + // exactly one 'sendInterval' behind the newly received one. + static void RewriteHistory( + SortedList snapshots, + // timestamp of packet arrival, not interpolated remote time! + double remoteTimeStamp, + double localTime, + double sendInterval, + Vector3 position, + Quaternion rotation, + Vector3 scale) + { + // clear the previous snapshot + snapshots.Clear(); + + // insert a fake one at where we used to be, + // 'sendInterval' behind the new one. + SnapshotInterpolation.InsertIfNotExists( + snapshots, + NetworkClient.snapshotSettings.bufferLimit, + new TransformSnapshot( + remoteTimeStamp - sendInterval, // arrival remote timestamp. NOT remote time. + localTime - sendInterval, // Unity 2019 doesn't have timeAsDouble yet + position, + rotation, + scale + ) + ); + } + + // reset state for next session. + // do not ever call this during a session (i.e. after teleport). + // calling this will break delta compression. + public override void ResetState() + { + base.ResetState(); + + // reset delta + lastSerializedPosition = Vector3Long.zero; + lastDeserializedPosition = Vector3Long.zero; + + lastSerializedScale = Vector3Long.zero; + lastDeserializedScale = Vector3Long.zero; + + // reset 'last' for delta too + last = new TransformSnapshot(0, 0, Vector3.zero, Quaternion.identity, Vector3.zero); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs.meta new file mode 100644 index 0000000000..e961c4762d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8ff3ba0becae47b8b9381191598957c8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs new file mode 100644 index 0000000000..ab3b2d7b7e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs @@ -0,0 +1,679 @@ +// NetworkTransform V2 by mischa (2021-07) +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/Network Transform (Unreliable)")] + public class NetworkTransformUnreliable : NetworkTransformBase + { + uint sendIntervalCounter = 0; + double lastSendIntervalTime = double.MinValue; + + [Header("Additional Settings")] + // Testing under really bad network conditions, 2%-5% packet loss and 250-1200ms ping, 5 proved to eliminate any twitching, however this should not be the default as it is a rare case Developers may want to cover. + [Tooltip("How much time, as a multiple of send interval, has passed before clearing buffers.\nA larger buffer means more delay, but results in smoother movement.\nExample: 1 for faster responses minimal smoothing, 5 covers bad pings but has noticable delay, 3 is recommended for balanced results,.")] + public float bufferResetMultiplier = 3; + [Tooltip("Detect and send only changed data, such as Position X and Z, not the full Vector3 of X Y Z. Lowers network data at cost of extra calculations.")] + public bool changedDetection = true; + + [Header("Sensitivity"), Tooltip("Sensitivity of changes needed before an updated state is sent over the network")] + public float positionSensitivity = 0.01f; + public float rotationSensitivity = 0.01f; + public float scaleSensitivity = 0.01f; + + protected bool positionChanged; + protected bool rotationChanged; + protected bool scaleChanged; + + // Used to store last sent snapshots + protected TransformSnapshot lastSnapshot; + protected bool cachedSnapshotComparison; + protected Changed cachedChangedComparison; + protected bool hasSentUnchangedPosition; + + // update ////////////////////////////////////////////////////////////// + // Update applies interpolation + void Update() + { + if (isServer) UpdateServerInterpolation(); + // for all other clients (and for local player if !authority), + // we need to apply snapshots from the buffer. + // 'else if' because host mode shouldn't interpolate client + else if (isClient && !IsClientWithAuthority) UpdateClientInterpolation(); + } + + // LateUpdate broadcasts. + // movement scripts may change positions in Update. + // use LateUpdate to ensure changes are detected in the same frame. + // otherwise this may run before user update, delaying detection until next frame. + // this could cause visible jitter. + void LateUpdate() + { + // if server then always sync to others. + if (isServer) UpdateServerBroadcast(); + // client authority, and local player (= allowed to move myself)? + // 'else if' because host mode shouldn't send anything to server. + // it is the server. don't overwrite anything there. + else if (isClient && IsClientWithAuthority) UpdateClientBroadcast(); + } + + protected virtual void CheckLastSendTime() + { + // We check interval every frame, and then send if interval is reached. + // So by the time sendIntervalCounter == sendIntervalMultiplier, data is sent, + // thus we reset the counter here. + // This fixes previous issue of, if sendIntervalMultiplier = 1, we send every frame, + // because intervalCounter is always = 1 in the previous version. + + // Changing == to >= https://github.com/MirrorNetworking/Mirror/issues/3571 + + if (sendIntervalCounter >= sendIntervalMultiplier) + sendIntervalCounter = 0; + + // timeAsDouble not available in older Unity versions. + if (AccurateInterval.Elapsed(NetworkTime.localTime, NetworkServer.sendInterval, ref lastSendIntervalTime)) + sendIntervalCounter++; + } + + void UpdateServerBroadcast() + { + // broadcast to all clients each 'sendInterval' + // (client with authority will drop the rpc) + // NetworkTime.localTime for double precision until Unity has it too + // + // IMPORTANT: + // snapshot interpolation requires constant sending. + // DO NOT only send if position changed. for example: + // --- + // * client sends first position at t=0 + // * ... 10s later ... + // * client moves again, sends second position at t=10 + // --- + // * server gets first position at t=0 + // * server gets second position at t=10 + // * server moves from first to second within a time of 10s + // => would be a super slow move, instead of a wait & move. + // + // IMPORTANT: + // DO NOT send nulls if not changed 'since last send' either. we + // send unreliable and don't know which 'last send' the other end + // received successfully. + // + // Checks to ensure server only sends snapshots if object is + // on server authority(!clientAuthority) mode because on client + // authority mode snapshots are broadcasted right after the authoritative + // client updates server in the command function(see above), OR, + // since host does not send anything to update the server, any client + // authoritative movement done by the host will have to be broadcasted + // here by checking IsClientWithAuthority. + // TODO send same time that NetworkServer sends time snapshot? + CheckLastSendTime(); + + if (sendIntervalCounter == sendIntervalMultiplier && // same interval as time interpolation! + (syncDirection == SyncDirection.ServerToClient || IsClientWithAuthority)) + { + // send snapshot without timestamp. + // receiver gets it from batch timestamp to save bandwidth. + TransformSnapshot snapshot = Construct(); + + if (changedDetection) + { + cachedChangedComparison = CompareChangedSnapshots(snapshot); + + if ((cachedChangedComparison == Changed.None || cachedChangedComparison == Changed.CompressRot) && hasSentUnchangedPosition && onlySyncOnChange) { return; } + + SyncData syncData = new SyncData(cachedChangedComparison, snapshot); + + RpcServerToClientSync(syncData); + + if (cachedChangedComparison == Changed.None || cachedChangedComparison == Changed.CompressRot) + { + hasSentUnchangedPosition = true; + } + else + { + hasSentUnchangedPosition = false; + UpdateLastSentSnapshot(cachedChangedComparison, snapshot); + } + } + else + { + cachedSnapshotComparison = CompareSnapshots(snapshot); + if (cachedSnapshotComparison && hasSentUnchangedPosition && onlySyncOnChange) { return; } + + if (compressRotation) + { + RpcServerToClientSyncCompressRotation( + // only sync what the user wants to sync + syncPosition && positionChanged ? snapshot.position : default(Vector3?), + syncRotation && rotationChanged ? Compression.CompressQuaternion(snapshot.rotation) : default(uint?), + syncScale && scaleChanged ? snapshot.scale : default(Vector3?) + ); + } + else + { + RpcServerToClientSync( + // only sync what the user wants to sync + syncPosition && positionChanged ? snapshot.position : default(Vector3?), + syncRotation && rotationChanged ? snapshot.rotation : default(Quaternion?), + syncScale && scaleChanged ? snapshot.scale : default(Vector3?) + ); + } + + if (cachedSnapshotComparison) + { + hasSentUnchangedPosition = true; + } + else + { + hasSentUnchangedPosition = false; + + // Fixes https://github.com/MirrorNetworking/Mirror/issues/3572 + // This also fixes https://github.com/MirrorNetworking/Mirror/issues/3573 + // with the exception of Quaternion.Angle sensitivity has to be > 0.16. + // Unity issue, we are leaving it as is. + + if (positionChanged) lastSnapshot.position = snapshot.position; + if (rotationChanged) lastSnapshot.rotation = snapshot.rotation; + if (positionChanged) lastSnapshot.scale = snapshot.scale; + } + } + } + } + + void UpdateServerInterpolation() + { + // apply buffered snapshots IF client authority + // -> in server authority, server moves the object + // so no need to apply any snapshots there. + // -> don't apply for host mode player objects either, even if in + // client authority mode. if it doesn't go over the network, + // then we don't need to do anything. + // -> connectionToClient is briefly null after scene changes: + // https://github.com/MirrorNetworking/Mirror/issues/3329 + if (syncDirection == SyncDirection.ClientToServer && + connectionToClient != null && + !isOwned) + { + if (serverSnapshots.Count == 0) return; + + // step the transform interpolation without touching time. + // NetworkClient is responsible for time globally. + SnapshotInterpolation.StepInterpolation( + serverSnapshots, + connectionToClient.remoteTimeline, + out TransformSnapshot from, + out TransformSnapshot to, + out double t); + + // interpolate & apply + TransformSnapshot computed = TransformSnapshot.Interpolate(from, to, t); + Apply(computed, to); + } + } + + void UpdateClientBroadcast() + { + // https://github.com/vis2k/Mirror/pull/2992/ + if (!NetworkClient.ready) return; + + // send to server each 'sendInterval' + // NetworkTime.localTime for double precision until Unity has it too + // + // IMPORTANT: + // snapshot interpolation requires constant sending. + // DO NOT only send if position changed. for example: + // --- + // * client sends first position at t=0 + // * ... 10s later ... + // * client moves again, sends second position at t=10 + // --- + // * server gets first position at t=0 + // * server gets second position at t=10 + // * server moves from first to second within a time of 10s + // => would be a super slow move, instead of a wait & move. + // + // IMPORTANT: + // DO NOT send nulls if not changed 'since last send' either. we + // send unreliable and don't know which 'last send' the other end + // received successfully. + CheckLastSendTime(); + if (sendIntervalCounter == sendIntervalMultiplier) // same interval as time interpolation! + { + // send snapshot without timestamp. + // receiver gets it from batch timestamp to save bandwidth. + TransformSnapshot snapshot = Construct(); + + if (changedDetection) + { + cachedChangedComparison = CompareChangedSnapshots(snapshot); + + if ((cachedChangedComparison == Changed.None || cachedChangedComparison == Changed.CompressRot) && hasSentUnchangedPosition && onlySyncOnChange) { return; } + + SyncData syncData = new SyncData(cachedChangedComparison, snapshot); + + CmdClientToServerSync(syncData); + + if (cachedChangedComparison == Changed.None || cachedChangedComparison == Changed.CompressRot) + { + hasSentUnchangedPosition = true; + } + else + { + hasSentUnchangedPosition = false; + UpdateLastSentSnapshot(cachedChangedComparison, snapshot); + } + } + else + { + cachedSnapshotComparison = CompareSnapshots(snapshot); + if (cachedSnapshotComparison && hasSentUnchangedPosition && onlySyncOnChange) { return; } + + if (compressRotation) + { + CmdClientToServerSyncCompressRotation( + // only sync what the user wants to sync + syncPosition && positionChanged ? snapshot.position : default(Vector3?), + syncRotation && rotationChanged ? Compression.CompressQuaternion(snapshot.rotation) : default(uint?), + syncScale && scaleChanged ? snapshot.scale : default(Vector3?) + ); + } + else + { + CmdClientToServerSync( + // only sync what the user wants to sync + syncPosition && positionChanged ? snapshot.position : default(Vector3?), + syncRotation && rotationChanged ? snapshot.rotation : default(Quaternion?), + syncScale && scaleChanged ? snapshot.scale : default(Vector3?) + ); + } + + if (cachedSnapshotComparison) + { + hasSentUnchangedPosition = true; + } + else + { + hasSentUnchangedPosition = false; + + // Fixes https://github.com/MirrorNetworking/Mirror/issues/3572 + // This also fixes https://github.com/MirrorNetworking/Mirror/issues/3573 + // with the exception of Quaternion.Angle sensitivity has to be > 0.16. + // Unity issue, we are leaving it as is. + if (positionChanged) lastSnapshot.position = snapshot.position; + if (rotationChanged) lastSnapshot.rotation = snapshot.rotation; + if (positionChanged) lastSnapshot.scale = snapshot.scale; + } + } + } + } + + void UpdateClientInterpolation() + { + // only while we have snapshots + if (clientSnapshots.Count == 0) return; + + // step the interpolation without touching time. + // NetworkClient is responsible for time globally. + SnapshotInterpolation.StepInterpolation( + clientSnapshots, + NetworkTime.time, // == NetworkClient.localTimeline from snapshot interpolation + out TransformSnapshot from, + out TransformSnapshot to, + out double t); + + // interpolate & apply + TransformSnapshot computed = TransformSnapshot.Interpolate(from, to, t); + Apply(computed, to); + } + + public override void OnSerialize(NetworkWriter writer, bool initialState) + { + // sync target component's position on spawn. + // fixes https://github.com/vis2k/Mirror/pull/3051/ + // (Spawn message wouldn't sync NTChild positions either) + if (initialState) + { + if (syncPosition) writer.WriteVector3(GetPosition()); + if (syncRotation) writer.WriteQuaternion(GetRotation()); + if (syncScale) writer.WriteVector3(GetScale()); + } + } + + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + // sync target component's position on spawn. + // fixes https://github.com/vis2k/Mirror/pull/3051/ + // (Spawn message wouldn't sync NTChild positions either) + if (initialState) + { + if (syncPosition) SetPosition(reader.ReadVector3()); + if (syncRotation) SetRotation(reader.ReadQuaternion()); + if (syncScale) SetScale(reader.ReadVector3()); + } + } + + // Returns true if position, rotation AND scale are unchanged, within given sensitivity range. + protected virtual bool CompareSnapshots(TransformSnapshot currentSnapshot) + { + positionChanged = Vector3.SqrMagnitude(lastSnapshot.position - currentSnapshot.position) > positionSensitivity * positionSensitivity; + rotationChanged = Quaternion.Angle(lastSnapshot.rotation, currentSnapshot.rotation) > rotationSensitivity; + scaleChanged = Vector3.SqrMagnitude(lastSnapshot.scale - currentSnapshot.scale) > scaleSensitivity * scaleSensitivity; + + return (!positionChanged && !rotationChanged && !scaleChanged); + } + + // cmd ///////////////////////////////////////////////////////////////// + // only unreliable. see comment above of this file. + [Command(channel = Channels.Unreliable)] + void CmdClientToServerSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + OnClientToServerSync(position, rotation, scale); + //For client authority, immediately pass on the client snapshot to all other + //clients instead of waiting for server to send its snapshots. + if (syncDirection == SyncDirection.ClientToServer) + RpcServerToClientSync(position, rotation, scale); + } + + // cmd ///////////////////////////////////////////////////////////////// + // only unreliable. see comment above of this file. + [Command(channel = Channels.Unreliable)] + void CmdClientToServerSyncCompressRotation(Vector3? position, uint? rotation, Vector3? scale) + { + // A fix to not apply current interpolated GetRotation when receiving null/unchanged value, instead use last sent snapshot rotation. + Quaternion newRotation; + if (rotation.HasValue) + { + newRotation = Compression.DecompressQuaternion((uint)rotation); + } + else + { + newRotation = serverSnapshots.Count > 0 ? serverSnapshots.Values[serverSnapshots.Count - 1].rotation : GetRotation(); + } + OnClientToServerSync(position, newRotation, scale); + //For client authority, immediately pass on the client snapshot to all other + //clients instead of waiting for server to send its snapshots. + if (syncDirection == SyncDirection.ClientToServer) + RpcServerToClientSyncCompressRotation(position, rotation, scale); + } + + // local authority client sends sync message to server for broadcasting + protected virtual void OnClientToServerSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + // only apply if in client authority mode + if (syncDirection != SyncDirection.ClientToServer) return; + + // protect against ever growing buffer size attacks + if (serverSnapshots.Count >= connectionToClient.snapshotBufferSizeLimit) return; + + // only player owned objects (with a connection) can send to + // server. we can get the timestamp from the connection. + double timestamp = connectionToClient.remoteTimeStamp; + + if (onlySyncOnChange) + { + double timeIntervalCheck = bufferResetMultiplier * sendIntervalMultiplier * NetworkClient.sendInterval; + + if (serverSnapshots.Count > 0 && serverSnapshots.Values[serverSnapshots.Count - 1].remoteTime + timeIntervalCheck < timestamp) + ResetState(); + } + + AddSnapshot(serverSnapshots, connectionToClient.remoteTimeStamp + timeStampAdjustment + offset, position, rotation, scale); + } + + // rpc ///////////////////////////////////////////////////////////////// + // only unreliable. see comment above of this file. + [ClientRpc(channel = Channels.Unreliable)] + void RpcServerToClientSync(Vector3? position, Quaternion? rotation, Vector3? scale) => + OnServerToClientSync(position, rotation, scale); + + // rpc ///////////////////////////////////////////////////////////////// + // only unreliable. see comment above of this file. + [ClientRpc(channel = Channels.Unreliable)] + void RpcServerToClientSyncCompressRotation(Vector3? position, uint? rotation, Vector3? scale) + { + // A fix to not apply current interpolated GetRotation when receiving null/unchanged value, instead use last sent snapshot rotation. + Quaternion newRotation; + if (rotation.HasValue) + { + newRotation = Compression.DecompressQuaternion((uint)rotation); + } + else + { + newRotation = clientSnapshots.Count > 0 ? clientSnapshots.Values[clientSnapshots.Count - 1].rotation : GetRotation(); + } + OnServerToClientSync(position, newRotation, scale); + } + + // server broadcasts sync message to all clients + protected virtual void OnServerToClientSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + // in host mode, the server sends rpcs to all clients. + // the host client itself will receive them too. + // -> host server is always the source of truth + // -> we can ignore any rpc on the host client + // => otherwise host objects would have ever growing clientBuffers + // (rpc goes to clients. if isServer is true too then we are host) + if (isServer) return; + + // don't apply for local player with authority + if (IsClientWithAuthority) return; + + // on the client, we receive rpcs for all entities. + // not all of them have a connectionToServer. + // but all of them go through NetworkClient.connection. + // we can get the timestamp from there. + double timestamp = NetworkClient.connection.remoteTimeStamp; + + if (onlySyncOnChange) + { + double timeIntervalCheck = bufferResetMultiplier * sendIntervalMultiplier * NetworkServer.sendInterval; + + if (clientSnapshots.Count > 0 && clientSnapshots.Values[clientSnapshots.Count - 1].remoteTime + timeIntervalCheck < timestamp) + ResetState(); + } + + AddSnapshot(clientSnapshots, NetworkClient.connection.remoteTimeStamp + timeStampAdjustment + offset, position, rotation, scale); + } + + protected virtual void UpdateLastSentSnapshot(Changed change, TransformSnapshot currentSnapshot) + { + if (change == Changed.None || change == Changed.CompressRot) return; + + if ((change & Changed.PosX) > 0) lastSnapshot.position.x = currentSnapshot.position.x; + if ((change & Changed.PosY) > 0) lastSnapshot.position.y = currentSnapshot.position.y; + if ((change & Changed.PosZ) > 0) lastSnapshot.position.z = currentSnapshot.position.z; + + if (compressRotation) + { + if ((change & Changed.Rot) > 0) lastSnapshot.rotation = currentSnapshot.rotation; + } + else + { + Vector3 newRotation; + newRotation.x = (change & Changed.RotX) > 0 ? currentSnapshot.rotation.eulerAngles.x : lastSnapshot.rotation.eulerAngles.x; + newRotation.y = (change & Changed.RotY) > 0 ? currentSnapshot.rotation.eulerAngles.y : lastSnapshot.rotation.eulerAngles.y; + newRotation.z = (change & Changed.RotZ) > 0 ? currentSnapshot.rotation.eulerAngles.z : lastSnapshot.rotation.eulerAngles.z; + + lastSnapshot.rotation = Quaternion.Euler(newRotation); + } + + if ((change & Changed.Scale) > 0) lastSnapshot.scale = currentSnapshot.scale; + } + + // Returns true if position, rotation AND scale are unchanged, within given sensitivity range. + // Note the sensitivity comparison are different for pos, rot and scale. + protected virtual Changed CompareChangedSnapshots(TransformSnapshot currentSnapshot) + { + Changed change = Changed.None; + + if (syncPosition) + { + bool positionChanged = Vector3.SqrMagnitude(lastSnapshot.position - currentSnapshot.position) > positionSensitivity * positionSensitivity; + if (positionChanged) + { + if (Mathf.Abs(lastSnapshot.position.x - currentSnapshot.position.x) > positionSensitivity) change |= Changed.PosX; + if (Mathf.Abs(lastSnapshot.position.y - currentSnapshot.position.y) > positionSensitivity) change |= Changed.PosY; + if (Mathf.Abs(lastSnapshot.position.z - currentSnapshot.position.z) > positionSensitivity) change |= Changed.PosZ; + } + } + + if (syncRotation) + { + if (compressRotation) + { + bool rotationChanged = Quaternion.Angle(lastSnapshot.rotation, currentSnapshot.rotation) > rotationSensitivity; + if (rotationChanged) + { + // Here we set all Rot enum flags, to tell us if there was a change in rotation + // when using compression. If no change, we don't write the compressed Quat. + change |= Changed.CompressRot; + change |= Changed.Rot; + } + else + { + change |= Changed.CompressRot; + } + } + else + { + if (Mathf.Abs(lastSnapshot.rotation.eulerAngles.x - currentSnapshot.rotation.eulerAngles.x) > rotationSensitivity) change |= Changed.RotX; + if (Mathf.Abs(lastSnapshot.rotation.eulerAngles.y - currentSnapshot.rotation.eulerAngles.y) > rotationSensitivity) change |= Changed.RotY; + if (Mathf.Abs(lastSnapshot.rotation.eulerAngles.z - currentSnapshot.rotation.eulerAngles.z) > rotationSensitivity) change |= Changed.RotZ; + } + } + + if (syncScale) + { + if (Vector3.SqrMagnitude(lastSnapshot.scale - currentSnapshot.scale) > scaleSensitivity * scaleSensitivity) change |= Changed.Scale; + } + + return change; + } + + [Command(channel = Channels.Unreliable)] + void CmdClientToServerSync(SyncData syncData) + { + OnClientToServerSync(syncData); + //For client authority, immediately pass on the client snapshot to all other + //clients instead of waiting for server to send its snapshots. + if (syncDirection == SyncDirection.ClientToServer) + RpcServerToClientSync(syncData); + } + + protected virtual void OnClientToServerSync(SyncData syncData) + { + // only apply if in client authority mode + if (syncDirection != SyncDirection.ClientToServer) return; + + // protect against ever growing buffer size attacks + if (serverSnapshots.Count >= connectionToClient.snapshotBufferSizeLimit) return; + + // only player owned objects (with a connection) can send to + // server. we can get the timestamp from the connection. + double timestamp = connectionToClient.remoteTimeStamp; + + if (onlySyncOnChange) + { + double timeIntervalCheck = bufferResetMultiplier * sendIntervalMultiplier * NetworkClient.sendInterval; + + if (serverSnapshots.Count > 0 && serverSnapshots.Values[serverSnapshots.Count - 1].remoteTime + timeIntervalCheck < timestamp) + ResetState(); + } + + UpdateSyncData(ref syncData, serverSnapshots); + + AddSnapshot(serverSnapshots, connectionToClient.remoteTimeStamp + timeStampAdjustment + offset, syncData.position, syncData.quatRotation, syncData.scale); + } + + + [ClientRpc(channel = Channels.Unreliable)] + void RpcServerToClientSync(SyncData syncData) => + OnServerToClientSync(syncData); + + protected virtual void OnServerToClientSync(SyncData syncData) + { + // in host mode, the server sends rpcs to all clients. + // the host client itself will receive them too. + // -> host server is always the source of truth + // -> we can ignore any rpc on the host client + // => otherwise host objects would have ever growing clientBuffers + // (rpc goes to clients. if isServer is true too then we are host) + if (isServer) return; + + // don't apply for local player with authority + if (IsClientWithAuthority) return; + + // on the client, we receive rpcs for all entities. + // not all of them have a connectionToServer. + // but all of them go through NetworkClient.connection. + // we can get the timestamp from there. + double timestamp = NetworkClient.connection.remoteTimeStamp; + + if (onlySyncOnChange) + { + double timeIntervalCheck = bufferResetMultiplier * sendIntervalMultiplier * NetworkServer.sendInterval; + + if (clientSnapshots.Count > 0 && clientSnapshots.Values[clientSnapshots.Count - 1].remoteTime + timeIntervalCheck < timestamp) + ResetState(); + } + + UpdateSyncData(ref syncData, clientSnapshots); + + AddSnapshot(clientSnapshots, NetworkClient.connection.remoteTimeStamp + timeStampAdjustment + offset, syncData.position, syncData.quatRotation, syncData.scale); + } + + protected virtual void UpdateSyncData(ref SyncData syncData, SortedList snapshots) + { + if (syncData.changedDataByte == Changed.None || syncData.changedDataByte == Changed.CompressRot) + { + syncData.position = snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].position : GetPosition(); + syncData.quatRotation = snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].rotation : GetRotation(); + syncData.scale = snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].scale : GetScale(); + } + else + { + // Just going to update these without checking if syncposition or not, + // because if not syncing position, NT will not apply any position data + // to the target during Apply(). + + syncData.position.x = (syncData.changedDataByte & Changed.PosX) > 0 ? syncData.position.x : (snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].position.x : GetPosition().x); + syncData.position.y = (syncData.changedDataByte & Changed.PosY) > 0 ? syncData.position.y : (snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].position.y : GetPosition().y); + syncData.position.z = (syncData.changedDataByte & Changed.PosZ) > 0 ? syncData.position.z : (snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].position.z : GetPosition().z); + + // If compressRot is true, we already have the Quat in syncdata. + if ((syncData.changedDataByte & Changed.CompressRot) == 0) + { + syncData.vecRotation.x = (syncData.changedDataByte & Changed.RotX) > 0 ? syncData.vecRotation.x : (snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].rotation.eulerAngles.x : GetRotation().eulerAngles.x); + syncData.vecRotation.y = (syncData.changedDataByte & Changed.RotY) > 0 ? syncData.vecRotation.y : (snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].rotation.eulerAngles.y : GetRotation().eulerAngles.y); ; + syncData.vecRotation.z = (syncData.changedDataByte & Changed.RotZ) > 0 ? syncData.vecRotation.z : (snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].rotation.eulerAngles.z : GetRotation().eulerAngles.z); + + syncData.quatRotation = Quaternion.Euler(syncData.vecRotation); + } + else + { + syncData.quatRotation = (syncData.changedDataByte & Changed.Rot) > 0 ? syncData.quatRotation : (snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].rotation : GetRotation()); + } + + syncData.scale = (syncData.changedDataByte & Changed.Scale) > 0 ? syncData.scale : (snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].scale : GetScale()); + } + } + + // This is to extract position/rotation/scale data from payload. Override + // Construct and Deconstruct if you are implementing a different SyncData logic. + // Note however that snapshot interpolation still requires the basic 3 data + // position, rotation and scale, which are computed from here. + protected virtual void DeconstructSyncData(System.ArraySegment receivedPayload, out byte? changedFlagData, out Vector3? position, out Quaternion? rotation, out Vector3? scale) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(receivedPayload)) + { + SyncData syncData = reader.Read(); + changedFlagData = (byte)syncData.changedDataByte; + position = syncData.position; + rotation = syncData.quatRotation; + scale = syncData.scale; + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs.meta new file mode 100644 index 0000000000..f9354da56f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a553cb17010b2403e8523b558bffbc14 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSnapshot.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSnapshot.cs new file mode 100644 index 0000000000..01b863c8c6 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSnapshot.cs @@ -0,0 +1,68 @@ +// snapshot for snapshot interpolation +// https://gafferongames.com/post/snapshot_interpolation/ +// position, rotation, scale for compatibility for now. +using UnityEngine; + +namespace Mirror +{ + // NetworkTransform Snapshot + public struct TransformSnapshot : Snapshot + { + // time or sequence are needed to throw away older snapshots. + // + // glenn fiedler starts with a 16 bit sequence number. + // supposedly this is meant as a simplified example. + // in the end we need the remote timestamp for accurate interpolation + // and buffering over time. + // + // note: in theory, IF server sends exactly(!) at the same interval then + // the 16 bit ushort timestamp would be enough to calculate the + // remote time (sequence * sendInterval). but Unity's update is + // not guaranteed to run on the exact intervals / do catchup. + // => remote timestamp is better for now + // + // [REMOTE TIME, NOT LOCAL TIME] + // => DOUBLE for long term accuracy & batching gives us double anyway + public double remoteTime { get; set; } + + // the local timestamp (when we received it) + // used to know if the first two snapshots are old enough to start. + public double localTime { get; set; } + + public Vector3 position; + public Quaternion rotation; + public Vector3 scale; + + public TransformSnapshot(double remoteTime, double localTime, Vector3 position, Quaternion rotation, Vector3 scale) + { + this.remoteTime = remoteTime; + this.localTime = localTime; + this.position = position; + this.rotation = rotation; + this.scale = scale; + } + + public static TransformSnapshot Interpolate(TransformSnapshot from, TransformSnapshot to, double t) + { + // NOTE: + // Vector3 & Quaternion components are float anyway, so we can + // keep using the functions with 't' as float instead of double. + return new TransformSnapshot( + // interpolated snapshot is applied directly. don't need timestamps. + 0, 0, + // lerp position/rotation/scale unclamped in case we ever need + // to extrapolate. atm SnapshotInterpolation never does. + Vector3.LerpUnclamped(from.position, to.position, (float)t), + // IMPORTANT: LerpUnclamped(0, 60, 1.5) extrapolates to ~86. + // SlerpUnclamped(0, 60, 1.5) extrapolates to 90! + // (0, 90, 1.5) is even worse. for Lerp. + // => Slerp works way better for our euler angles. + Quaternion.SlerpUnclamped(from.rotation, to.rotation, (float)t), + Vector3.LerpUnclamped(from.scale, to.scale, (float)t) + ); + } + + public override string ToString() => + $"TransformSnapshot(remoteTime={remoteTime:F2}, localTime={localTime:F2}, pos={position}, rot={rotation}, scale={scale})"; + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSnapshot.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSnapshot.cs.meta new file mode 100644 index 0000000000..b17d18e368 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSnapshot.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: d3dae77b43dc4e1dbb2012924b2da79c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSnapshot.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSyncData.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSyncData.cs new file mode 100644 index 0000000000..9b6d51cb3a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSyncData.cs @@ -0,0 +1,156 @@ +using UnityEngine; +using System; +using Mirror; + +namespace Mirror +{ + [Serializable] + public struct SyncData + { + public Changed changedDataByte; + public Vector3 position; + public Quaternion quatRotation; + public Vector3 vecRotation; + public Vector3 scale; + + public SyncData(Changed _dataChangedByte, Vector3 _position, Quaternion _rotation, Vector3 _scale) + { + this.changedDataByte = _dataChangedByte; + this.position = _position; + this.quatRotation = _rotation; + this.vecRotation = quatRotation.eulerAngles; + this.scale = _scale; + } + + public SyncData(Changed _dataChangedByte, TransformSnapshot _snapshot) + { + this.changedDataByte = _dataChangedByte; + this.position = _snapshot.position; + this.quatRotation = _snapshot.rotation; + this.vecRotation = quatRotation.eulerAngles; + this.scale = _snapshot.scale; + } + + public SyncData(Changed _dataChangedByte, Vector3 _position, Vector3 _vecRotation, Vector3 _scale) + { + this.changedDataByte = _dataChangedByte; + this.position = _position; + this.vecRotation = _vecRotation; + this.quatRotation = Quaternion.Euler(vecRotation); + this.scale = _scale; + } + } + + [Flags] + public enum Changed : byte + { + None = 0, + PosX = 1 << 0, + PosY = 1 << 1, + PosZ = 1 << 2, + CompressRot = 1 << 3, + RotX = 1 << 4, + RotY = 1 << 5, + RotZ = 1 << 6, + Scale = 1 << 7, + + Pos = PosX | PosY | PosZ, + Rot = RotX | RotY | RotZ + } + + + public static class SyncDataReaderWriter + { + public static void WriteSyncData(this NetworkWriter writer, SyncData syncData) + { + writer.WriteByte((byte)syncData.changedDataByte); + + // Write position + if ((syncData.changedDataByte & Changed.PosX) > 0) + { + writer.WriteFloat(syncData.position.x); + } + + if ((syncData.changedDataByte & Changed.PosY) > 0) + { + writer.WriteFloat(syncData.position.y); + } + + if ((syncData.changedDataByte & Changed.PosZ) > 0) + { + writer.WriteFloat(syncData.position.z); + } + + // Write rotation + if ((syncData.changedDataByte & Changed.CompressRot) > 0) + { + if((syncData.changedDataByte & Changed.Rot) > 0) + { + writer.WriteUInt(Compression.CompressQuaternion(syncData.quatRotation)); + } + } + else + { + if ((syncData.changedDataByte & Changed.RotX) > 0) + { + writer.WriteFloat(syncData.quatRotation.eulerAngles.x); + } + + if ((syncData.changedDataByte & Changed.RotY) > 0) + { + writer.WriteFloat(syncData.quatRotation.eulerAngles.y); + } + + if ((syncData.changedDataByte & Changed.RotZ) > 0) + { + writer.WriteFloat(syncData.quatRotation.eulerAngles.z); + } + } + + // Write scale + if ((syncData.changedDataByte & Changed.Scale) > 0) + { + writer.WriteVector3(syncData.scale); + } + } + + public static SyncData ReadSyncData(this NetworkReader reader) + { + Changed changedData = (Changed)reader.ReadByte(); + + // If we have nothing to read here, let's say because posX is unchanged, then we can write anything + // for now, but in the NT, we will need to check changedData again, to put the right values of the axis + // back. We don't have it here. + + Vector3 position = + new Vector3( + (changedData & Changed.PosX) > 0 ? reader.ReadFloat() : 0, + (changedData & Changed.PosY) > 0 ? reader.ReadFloat() : 0, + (changedData & Changed.PosZ) > 0 ? reader.ReadFloat() : 0 + ); + + Vector3 vecRotation = new Vector3(); + Quaternion quatRotation = new Quaternion(); + + if ((changedData & Changed.CompressRot) > 0) + { + quatRotation = (changedData & Changed.RotX) > 0 ? Compression.DecompressQuaternion(reader.ReadUInt()) : new Quaternion(); + } + else + { + vecRotation = + new Vector3( + (changedData & Changed.RotX) > 0 ? reader.ReadFloat() : 0, + (changedData & Changed.RotY) > 0 ? reader.ReadFloat() : 0, + (changedData & Changed.RotZ) > 0 ? reader.ReadFloat() : 0 + ); + } + + Vector3 scale = (changedData & Changed.Scale) == Changed.Scale ? reader.ReadVector3() : new Vector3(); + + SyncData _syncData = (changedData & Changed.CompressRot) > 0 ? new SyncData(changedData, position, quatRotation, scale) : new SyncData(changedData, position, vecRotation, scale); + + return _syncData; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSyncData.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSyncData.cs.meta new file mode 100644 index 0000000000..f79da4faed --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSyncData.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a1c0832ca88e749ff96fe04cebb617ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/NetworkTransform/TransformSyncData.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransformBase.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransformBase.cs deleted file mode 100644 index 380a268b74..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/NetworkTransformBase.cs +++ /dev/null @@ -1,423 +0,0 @@ -// vis2k: -// base class for NetworkTransform and NetworkTransformChild. -// New method is simple and stupid. No more 1500 lines of code. -// -// Server sends current data. -// Client saves it and interpolates last and latest data points. -// Update handles transform movement / rotation -// FixedUpdate handles rigidbody movement / rotation -// -// Notes: -// * Built-in Teleport detection in case of lags / teleport / obstacles -// * Quaternion > EulerAngles because gimbal lock and Quaternion.Slerp -// * Syncs XYZ. Works 3D and 2D. Saving 4 bytes isn't worth 1000 lines of code. -// * Initial delay might happen if server sends packet immediately after moving -// just 1cm, hence we move 1cm and then wait 100ms for next packet -// * Only way for smooth movement is to use a fixed movement speed during -// interpolation. interpolation over time is never that good. -// -using System.ComponentModel; -using UnityEngine; - -namespace Mirror -{ - public abstract class NetworkTransformBase : NetworkBehaviour - { - [Header("Authority")] - [Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")] - public bool clientAuthority; - - // Is this a client with authority over this transform? - // This component could be on the player object or any object that has been assigned authority to this client. - bool IsClientWithAuthority => hasAuthority && clientAuthority; - - // Sensitivity is added for VR where human players tend to have micro movements so this can quiet down - // the network traffic. Additionally, rigidbody drift should send less traffic, e.g very slow sliding / rolling. - [Header("Sensitivity")] - [Tooltip("Changes to the transform must exceed these values to be transmitted on the network.")] - public float localPositionSensitivity = .01f; - [Tooltip("If rotation exceeds this angle, it will be transmitted on the network")] - public float localRotationSensitivity = .01f; - [Tooltip("Changes to the transform must exceed these values to be transmitted on the network.")] - public float localScaleSensitivity = .01f; - - // target transform to sync. can be on a child. - protected abstract Transform targetComponent { get; } - - // server - Vector3 lastPosition; - Quaternion lastRotation; - Vector3 lastScale; - - // client - public class DataPoint - { - public float timeStamp; - // use local position/rotation for VR support - public Vector3 localPosition; - public Quaternion localRotation; - public Vector3 localScale; - public float movementSpeed; - } - // interpolation start and goal - DataPoint start; - DataPoint goal; - - // local authority send time - float lastClientSendTime; - - // serialization is needed by OnSerialize and by manual sending from authority - // public only for tests - [EditorBrowsable(EditorBrowsableState.Never)] - public static void SerializeIntoWriter(NetworkWriter writer, Vector3 position, Quaternion rotation, Vector3 scale) - { - // serialize position, rotation, scale - // note: we do NOT compress rotation. - // we are CPU constrained, not bandwidth constrained. - // the code needs to WORK for the next 5-10 years of development. - writer.WriteVector3(position); - writer.WriteQuaternion(rotation); - writer.WriteVector3(scale); - } - - public override bool OnSerialize(NetworkWriter writer, bool initialState) - { - // use local position/rotation/scale for VR support - SerializeIntoWriter(writer, targetComponent.transform.localPosition, targetComponent.transform.localRotation, targetComponent.transform.localScale); - return true; - } - - // try to estimate movement speed for a data point based on how far it - // moved since the previous one - // => if this is the first time ever then we use our best guess: - // -> delta based on transform.localPosition - // -> elapsed based on send interval hoping that it roughly matches - static float EstimateMovementSpeed(DataPoint from, DataPoint to, Transform transform, float sendInterval) - { - Vector3 delta = to.localPosition - (from != null ? from.localPosition : transform.localPosition); - float elapsed = from != null ? to.timeStamp - from.timeStamp : sendInterval; - // avoid NaN - return elapsed > 0 ? delta.magnitude / elapsed : 0; - } - - // serialization is needed by OnSerialize and by manual sending from authority - void DeserializeFromReader(NetworkReader reader) - { - // put it into a data point immediately - DataPoint temp = new DataPoint - { - // deserialize position - localPosition = reader.ReadVector3() - }; - - // deserialize rotation & scale - temp.localRotation = reader.ReadQuaternion(); - temp.localScale = reader.ReadVector3(); - - temp.timeStamp = Time.time; - - // movement speed: based on how far it moved since last time - // has to be calculated before 'start' is overwritten - temp.movementSpeed = EstimateMovementSpeed(goal, temp, targetComponent.transform, syncInterval); - - // reassign start wisely - // -> first ever data point? then make something up for previous one - // so that we can start interpolation without waiting for next. - if (start == null) - { - start = new DataPoint - { - timeStamp = Time.time - syncInterval, - // local position/rotation for VR support - localPosition = targetComponent.transform.localPosition, - localRotation = targetComponent.transform.localRotation, - localScale = targetComponent.transform.localScale, - movementSpeed = temp.movementSpeed - }; - } - // -> second or nth data point? then update previous, but: - // we start at where ever we are right now, so that it's - // perfectly smooth and we don't jump anywhere - // - // example if we are at 'x': - // - // A--x->B - // - // and then receive a new point C: - // - // A--x--B - // | - // | - // C - // - // then we don't want to just jump to B and start interpolation: - // - // x - // | - // | - // C - // - // we stay at 'x' and interpolate from there to C: - // - // x..B - // \ . - // \. - // C - // - else - { - float oldDistance = Vector3.Distance(start.localPosition, goal.localPosition); - float newDistance = Vector3.Distance(goal.localPosition, temp.localPosition); - - start = goal; - - // teleport / lag / obstacle detection: only continue at current - // position if we aren't too far away - // - // local position/rotation for VR support - if (Vector3.Distance(targetComponent.transform.localPosition, start.localPosition) < oldDistance + newDistance) - { - start.localPosition = targetComponent.transform.localPosition; - start.localRotation = targetComponent.transform.localRotation; - start.localScale = targetComponent.transform.localScale; - } - } - - // set new destination in any case. new data is best data. - goal = temp; - } - - public override void OnDeserialize(NetworkReader reader, bool initialState) - { - // deserialize - DeserializeFromReader(reader); - } - - // local authority client sends sync message to server for broadcasting - [Command] - void CmdClientToServerSync(byte[] payload) - { - // Ignore messages from client if not in client authority mode - if (!clientAuthority) - return; - - // deserialize payload - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(payload)) - DeserializeFromReader(networkReader); - - // server-only mode does no interpolation to save computations, - // but let's set the position directly - if (isServer && !isClient) - ApplyPositionRotationScale(goal.localPosition, goal.localRotation, goal.localScale); - - // set dirty so that OnSerialize broadcasts it - SetDirtyBit(1UL); - } - - // where are we in the timeline between start and goal? [0,1] - static float CurrentInterpolationFactor(DataPoint start, DataPoint goal) - { - if (start != null) - { - float difference = goal.timeStamp - start.timeStamp; - - // the moment we get 'goal', 'start' is supposed to - // start, so elapsed time is based on: - float elapsed = Time.time - goal.timeStamp; - // avoid NaN - return difference > 0 ? elapsed / difference : 0; - } - return 0; - } - - static Vector3 InterpolatePosition(DataPoint start, DataPoint goal, Vector3 currentPosition) - { - if (start != null) - { - // Option 1: simply interpolate based on time. but stutter - // will happen, it's not that smooth. especially noticeable if - // the camera automatically follows the player - // float t = CurrentInterpolationFactor(); - // return Vector3.Lerp(start.position, goal.position, t); - - // Option 2: always += speed - // -> speed is 0 if we just started after idle, so always use max - // for best results - float speed = Mathf.Max(start.movementSpeed, goal.movementSpeed); - return Vector3.MoveTowards(currentPosition, goal.localPosition, speed * Time.deltaTime); - } - return currentPosition; - } - - static Quaternion InterpolateRotation(DataPoint start, DataPoint goal, Quaternion defaultRotation) - { - if (start != null) - { - float t = CurrentInterpolationFactor(start, goal); - return Quaternion.Slerp(start.localRotation, goal.localRotation, t); - } - return defaultRotation; - } - - static Vector3 InterpolateScale(DataPoint start, DataPoint goal, Vector3 currentScale) - { - if (start != null) - { - float t = CurrentInterpolationFactor(start, goal); - return Vector3.Lerp(start.localScale, goal.localScale, t); - } - return currentScale; - } - - // teleport / lag / stuck detection - // -> checking distance is not enough since there could be just a tiny - // fence between us and the goal - // -> checking time always works, this way we just teleport if we still - // didn't reach the goal after too much time has elapsed - bool NeedsTeleport() - { - // calculate time between the two data points - float startTime = start != null ? start.timeStamp : Time.time - syncInterval; - float goalTime = goal != null ? goal.timeStamp : Time.time; - float difference = goalTime - startTime; - float timeSinceGoalReceived = Time.time - goalTime; - return timeSinceGoalReceived > difference * 5; - } - - // moved since last time we checked it? - bool HasEitherMovedRotatedScaled() - { - // moved or rotated or scaled? - // local position/rotation/scale for VR support - bool moved = Vector3.Distance(lastPosition, targetComponent.transform.localPosition) > localPositionSensitivity; - bool scaled = Vector3.Distance(lastScale, targetComponent.transform.localScale) > localScaleSensitivity; - bool rotated = Quaternion.Angle(lastRotation, targetComponent.transform.localRotation) > localRotationSensitivity; - - // save last for next frame to compare - // (only if change was detected. otherwise slow moving objects might - // never sync because of C#'s float comparison tolerance. see also: - // https://github.com/vis2k/Mirror/pull/428) - bool change = moved || rotated || scaled; - if (change) - { - // local position/rotation for VR support - lastPosition = targetComponent.transform.localPosition; - lastRotation = targetComponent.transform.localRotation; - lastScale = targetComponent.transform.localScale; - } - return change; - } - - // set position carefully depending on the target component - void ApplyPositionRotationScale(Vector3 position, Quaternion rotation, Vector3 scale) - { - // local position/rotation for VR support - targetComponent.transform.localPosition = position; - targetComponent.transform.localRotation = rotation; - targetComponent.transform.localScale = scale; - } - - void Update() - { - // if server then always sync to others. - if (isServer) - { - // just use OnSerialize via SetDirtyBit only sync when position - // changed. set dirty bits 0 or 1 - SetDirtyBit(HasEitherMovedRotatedScaled() ? 1UL : 0UL); - } - - // no 'else if' since host mode would be both - if (isClient) - { - // send to server if we have local authority (and aren't the server) - // -> only if connectionToServer has been initialized yet too - if (!isServer && IsClientWithAuthority) - { - // check only each 'syncInterval' - if (Time.time - lastClientSendTime >= syncInterval) - { - if (HasEitherMovedRotatedScaled()) - { - // serialize - // local position/rotation for VR support - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) - { - SerializeIntoWriter(writer, targetComponent.transform.localPosition, targetComponent.transform.localRotation, targetComponent.transform.localScale); - - // send to server - CmdClientToServerSync(writer.ToArray()); - } - } - lastClientSendTime = Time.time; - } - } - - // apply interpolation on client for all players - // unless this client has authority over the object. could be - // himself or another object that he was assigned authority over - if (!IsClientWithAuthority) - { - // received one yet? (initialized?) - if (goal != null) - { - // teleport or interpolate - if (NeedsTeleport()) - { - // local position/rotation for VR support - ApplyPositionRotationScale(goal.localPosition, goal.localRotation, goal.localScale); - - // reset data points so we don't keep interpolating - start = null; - goal = null; - } - else - { - // local position/rotation for VR support - ApplyPositionRotationScale(InterpolatePosition(start, goal, targetComponent.transform.localPosition), - InterpolateRotation(start, goal, targetComponent.transform.localRotation), - InterpolateScale(start, goal, targetComponent.transform.localScale)); - } - } - } - } - } - - static void DrawDataPointGizmo(DataPoint data, Color color) - { - // use a little offset because transform.localPosition might be in - // the ground in many cases - Vector3 offset = Vector3.up * 0.01f; - - // draw position - Gizmos.color = color; - Gizmos.DrawSphere(data.localPosition + offset, 0.5f); - - // draw forward and up - // like unity move tool - Gizmos.color = Color.blue; - Gizmos.DrawRay(data.localPosition + offset, data.localRotation * Vector3.forward); - - // like unity move tool - Gizmos.color = Color.green; - Gizmos.DrawRay(data.localPosition + offset, data.localRotation * Vector3.up); - } - - static void DrawLineBetweenDataPoints(DataPoint data1, DataPoint data2, Color color) - { - Gizmos.color = color; - Gizmos.DrawLine(data1.localPosition, data2.localPosition); - } - - // draw the data points for easier debugging - void OnDrawGizmos() - { - // draw start and goal points - if (start != null) DrawDataPointGizmo(start, Color.gray); - if (goal != null) DrawDataPointGizmo(goal, Color.white); - - // draw line between them - if (start != null && goal != null) DrawLineBetweenDataPoints(start, goal, Color.cyan); - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransformChild.cs b/Assets/ImportedAssets/Mirror/Components/NetworkTransformChild.cs deleted file mode 100644 index 84a0d31db6..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/NetworkTransformChild.cs +++ /dev/null @@ -1,18 +0,0 @@ -using UnityEngine; - -namespace Mirror -{ - /// - /// A component to synchronize the position of child transforms of networked objects. - /// There must be a NetworkTransform on the root object of the hierarchy. There can be multiple NetworkTransformChild components on an object. This does not use physics for synchronization, it simply synchronizes the localPosition and localRotation of the child transform and lerps towards the recieved values. - /// - [AddComponentMenu("Network/NetworkTransformChild")] - [HelpURL("https://mirror-networking.com/docs/Components/NetworkTransformChild.html")] - public class NetworkTransformChild : NetworkTransformBase - { - [Header("Target")] - public Transform target; - - protected override Transform targetComponent => target; - } -} diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransformChild.cs.meta b/Assets/ImportedAssets/Mirror/Components/NetworkTransformChild.cs.meta deleted file mode 100644 index ae36756d15..0000000000 --- a/Assets/ImportedAssets/Mirror/Components/NetworkTransformChild.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 734b48bea0b204338958ee3d885e11f0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody.meta b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody.meta new file mode 100644 index 0000000000..3bd5cec488 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 09cc6745984c453a8cfb4cf4244d2570 +timeCreated: 1693576410 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/LocalGhostMaterial.mat b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/LocalGhostMaterial.mat new file mode 100644 index 0000000000..ff29a7316a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/LocalGhostMaterial.mat @@ -0,0 +1,85 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 8 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: LocalGhostMaterial + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_Parent: {fileID: 0} + m_ModifiedSerializedProperties: 0 + m_ValidKeywords: + - _ALPHAPREMULTIPLY_ON + m_InvalidKeywords: [] + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: 3000 + stringTagMap: + RenderType: Transparent + disabledShaderPasses: [] + m_LockedProperties: + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _BumpMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailAlbedoMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailMask: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailNormalMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _EmissionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MetallicGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _OcclusionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _ParallaxMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Ints: [] + m_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 10 + - _GlossMapScale: 1 + - _Glossiness: 0.92 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 3 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 0 + m_Colors: + - _Color: {r: 1, g: 0, b: 0.067070484, a: 0.15686275} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} + m_BuildTextureStacks: [] diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/LocalGhostMaterial.mat.meta b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/LocalGhostMaterial.mat.meta new file mode 100644 index 0000000000..076d3362ce --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/LocalGhostMaterial.mat.meta @@ -0,0 +1,15 @@ +fileFormatVersion: 2 +guid: 411a48b4a197d4924bec3e3809bc9320 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/LocalGhostMaterial.mat + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs new file mode 100644 index 0000000000..0fd5e6a695 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs @@ -0,0 +1,997 @@ +// PredictedRigidbody which stores & indidvidually rewinds history per Rigidbody. +// +// This brings significant performance savings because: +// - if a scene has 1000 objects +// - and a player interacts with say 3 objects at a time +// - Physics.Simulate() would resimulate 1000 objects +// - where as this component only resimulates the 3 changed objects +// +// The downside is that history rewinding is done manually via Vector math, +// instead of real physics. It's not 100% correct - but it sure is fast! +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + public enum PredictionMode { Smooth, Fast } + + // [RequireComponent(typeof(Rigidbody))] <- RB is moved out at runtime, can't require it. + public class PredictedRigidbody : NetworkBehaviour + { + Transform tf; // this component is performance critical. cache .transform getter! + + // Prediction sometimes moves the Rigidbody to a ghost object. + // .predictedRigidbody is always kept up to date to wherever the RB is. + // other components should use this when accessing Rigidbody. + public Rigidbody predictedRigidbody; + Transform predictedRigidbodyTransform; // predictedRigidbody.transform for performance (Get/SetPositionAndRotation) + + Vector3 lastPosition; + + // motion smoothing happen on-demand, because it requires moving physics components to another GameObject. + // this only starts at a given velocity and ends when stopped moving. + // to avoid constant on/off/on effects, it also stays on for a minimum time. + [Header("Motion Smoothing")] + [Tooltip("Prediction supports two different modes: Smooth and Fast:\n\nSmooth: Physics are separated from the GameObject & applied in the background. Rendering smoothly follows the physics for perfectly smooth interpolation results. Much softer, can be even too soft where sharp collisions won't look as sharp (i.e. Billiard balls avoid the wall before even hitting it).\n\nFast: Physics remain on the GameObject and corrections are applied hard. Much faster since we don't need to update a separate GameObject, a bit harsher, more precise.")] + public PredictionMode mode = PredictionMode.Smooth; + [Tooltip("Smoothing via Ghost-following only happens on demand, while moving with a minimum velocity.")] + public float motionSmoothingVelocityThreshold = 0.1f; + float motionSmoothingVelocityThresholdSqr; // ² cached in Awake + public float motionSmoothingAngularVelocityThreshold = 5.0f; // Billiards demo: 0.1 is way too small, takes forever for IsMoving()==false + float motionSmoothingAngularVelocityThresholdSqr; // ² cached in Awake + public float motionSmoothingTimeTolerance = 0.5f; + double motionSmoothingLastMovedTime; + + // client keeps state history for correction & reconciliation. + // this needs to be a SortedList because we need to be able to insert inbetween. + // => RingBuffer: see prediction_ringbuffer_2 branch, but it's slower! + [Header("State History")] + public int stateHistoryLimit = 32; // 32 x 50 ms = 1.6 seconds is definitely enough + readonly SortedList stateHistory = new SortedList(); + public float recordInterval = 0.050f; + + [Tooltip("(Optional) performance optimization where FixedUpdate.RecordState() only inserts state into history if the state actually changed.\nThis is generally a good idea.")] + public bool onlyRecordChanges = true; + + [Tooltip("(Optional) performance optimization where received state is compared to the LAST recorded state first, before sampling the whole history.\n\nThis can save significant traversal overhead for idle objects with a tiny chance of missing corrections for objects which revisisted the same position in the recent history twice.")] + public bool compareLastFirst = true; + + [Header("Reconciliation")] + [Tooltip("Correction threshold in meters. For example, 0.1 means that if the client is off by more than 10cm, it gets corrected.")] + public double positionCorrectionThreshold = 0.10; + double positionCorrectionThresholdSqr; // ² cached in Awake + [Tooltip("Correction threshold in degrees. For example, 5 means that if the client is off by more than 5 degrees, it gets corrected.")] + public double rotationCorrectionThreshold = 5; + + [Tooltip("Applying server corrections one frame ahead gives much better results. We don't know why yet, so this is an option for now.")] + public bool oneFrameAhead = true; + + [Header("Smoothing")] + [Tooltip("Snap to the server state directly when velocity is < threshold. This is useful to reduce jitter/fighting effects before coming to rest.\nNote this applies position, rotation and velocity(!) so it's still smooth.")] + public float snapThreshold = 2; // 0.5 has too much fighting-at-rest, 2 seems ideal. + + [Header("Visual Interpolation")] + [Tooltip("After creating the visual interpolation object, keep showing the original Rigidbody with a ghost (transparent) material for debugging.")] + public bool showGhost = true; + [Tooltip("Physics components are moved onto a ghost object beyond this threshold. Main object visually interpolates to it.")] + public float ghostVelocityThreshold = 0.1f; + + [Tooltip("After creating the visual interpolation object, replace this object's renderer materials with the ghost (ideally transparent) material.")] + public Material localGhostMaterial; + public Material remoteGhostMaterial; + + [Tooltip("Performance optimization: only create/destroy ghosts every n-th frame is enough.")] + public int checkGhostsEveryNthFrame = 4; + + [Tooltip("How fast to interpolate to the target position, relative to how far we are away from it.\nHigher value will be more jitter but sharper moves, lower value will be less jitter but a little too smooth / rounded moves.")] + public float positionInterpolationSpeed = 15; // 10 is a little too low for billiards at least + public float rotationInterpolationSpeed = 10; + + [Tooltip("Teleport if we are further than 'multiplier x collider size' behind.")] + public float teleportDistanceMultiplier = 10; + + [Header("Bandwidth")] + [Tooltip("Reduce sends while velocity==0. Client's objects may slightly move due to gravity/physics, so we still want to send corrections occasionally even if an object is idle on the server the whole time.")] + public bool reduceSendsWhileIdle = true; + + // Rigidbody & Collider are moved out into a separate object. + // this way the visual object can smoothly follow. + protected GameObject physicsCopy; + // protected Transform physicsCopyTransform; // caching to avoid GetComponent + // protected Rigidbody physicsCopyRigidbody => rb; // caching to avoid GetComponent + // protected Collider physicsCopyCollider; // caching to avoid GetComponent + float smoothFollowThreshold; // caching to avoid calculation in LateUpdate + float smoothFollowThresholdSqr; // caching to avoid calculation in LateUpdate + + // we also create one extra ghost for the exact known server state. + protected GameObject remoteCopy; + + // joints + Vector3 initialPosition; + Quaternion initialRotation; + // Vector3 initialScale; // don't change scale for now. causes issues with parenting. + + Color originalColor; + + protected virtual void Awake() + { + tf = transform; + predictedRigidbody = GetComponent(); + if (predictedRigidbody == null) throw new InvalidOperationException($"Prediction: {name} is missing a Rigidbody component."); + predictedRigidbodyTransform = predictedRigidbody.transform; + + // in fast mode, we need to force enable Rigidbody.interpolation. + // otherwise there's not going to be any smoothing whatsoever. + if (mode == PredictionMode.Fast) + { + predictedRigidbody.interpolation = RigidbodyInterpolation.Interpolate; + } + + // cache some threshold to avoid calculating them in LateUpdate + float colliderSize = GetComponentInChildren().bounds.size.magnitude; + smoothFollowThreshold = colliderSize * teleportDistanceMultiplier; + smoothFollowThresholdSqr = smoothFollowThreshold * smoothFollowThreshold; + + // cache initial position/rotation/scale to be used when moving physics components (configurable joints' range of motion) + initialPosition = tf.position; + initialRotation = tf.rotation; + // initialScale = tf.localScale; + + // cache ² computations + motionSmoothingVelocityThresholdSqr = motionSmoothingVelocityThreshold * motionSmoothingVelocityThreshold; + motionSmoothingAngularVelocityThresholdSqr = motionSmoothingAngularVelocityThreshold * motionSmoothingAngularVelocityThreshold; + positionCorrectionThresholdSqr = positionCorrectionThreshold * positionCorrectionThreshold; + } + + protected virtual void CopyRenderersAsGhost(GameObject destination, Material material) + { + // find the MeshRenderer component, which sometimes is on a child. + MeshRenderer originalMeshRenderer = GetComponentInChildren(true); + MeshFilter originalMeshFilter = GetComponentInChildren(true); + if (originalMeshRenderer != null && originalMeshFilter != null) + { + MeshFilter meshFilter = destination.AddComponent(); + meshFilter.mesh = originalMeshFilter.mesh; + + MeshRenderer meshRenderer = destination.AddComponent(); + meshRenderer.material = originalMeshRenderer.material; + + // renderers often have multiple materials. copy all. + if (originalMeshRenderer.materials != null) + { + Material[] materials = new Material[originalMeshRenderer.materials.Length]; + for (int i = 0; i < materials.Length; ++i) + { + materials[i] = material; + } + meshRenderer.materials = materials; // need to reassign to see it in effect + } + } + // if we didn't find a renderer, show a warning + else Debug.LogWarning($"PredictedRigidbody: {name} found no renderer to copy onto the visual object. If you are using a custom setup, please overwrite PredictedRigidbody.CreateVisualCopy()."); + } + + // instantiate a physics-only copy of the gameobject to apply corrections. + // this way the main visual object can smoothly follow. + // it's best to separate the physics instead of separating the renderers. + // some projects have complex rendering / animation setups which we can't touch. + // besides, Rigidbody+Collider are two components, where as renders may be many. + protected virtual void CreateGhosts() + { + // skip if host mode or already separated + if (isServer || physicsCopy != null) return; + + // Debug.Log($"Separating Physics for {name}"); // logging this allocates too much + + // create an empty GameObject with the same name + _Physical + // it's important to copy world position/rotation/scale, not local! + // because the original object may be a child of another. + // + // for example: + // parent (scale=1.5) + // child (scale=0.5) + // + // if we copy localScale then the copy has scale=0.5, where as the + // original would have a global scale of ~1.0. + physicsCopy = new GameObject($"{name}_Physical"); + + // assign the same Layer for the physics copy. + // games may use a custom physics collision matrix, layer matters. + physicsCopy.layer = gameObject.layer; + + // add the PredictedRigidbodyPhysical component + PredictedRigidbodyPhysicsGhost physicsGhostRigidbody = physicsCopy.AddComponent(); + physicsGhostRigidbody.target = tf; + + // when moving (Configurable)Joints, their range of motion is + // relative to the initial position. if we move them after the + // GameObject rotated, the range of motion is wrong. + // the easiest solution is to move to initial position, + // then move physics components, then move back. + // => remember previous + Vector3 position = tf.position; + Quaternion rotation = tf.rotation; + // Vector3 scale = tf.localScale; // don't change scale for now. causes issues with parenting. + // => reset to initial + physicsGhostRigidbody.transform.position = tf.position = initialPosition; + physicsGhostRigidbody.transform.rotation = tf.rotation = initialRotation; + physicsGhostRigidbody.transform.localScale = tf.lossyScale;// world scale! // = initialScale; // don't change scale for now. causes issues with parenting. + // => move physics components + PredictionUtils.MovePhysicsComponents(gameObject, physicsCopy); + // => reset previous + physicsGhostRigidbody.transform.position = tf.position = position; + physicsGhostRigidbody.transform.rotation = tf.rotation = rotation; + //physicsGhostRigidbody.transform.localScale = tf.lossyScale; // world scale! //= scale; // don't change scale for now. causes issues with parenting. + + // show ghost by copying all renderers / materials with ghost material applied + if (showGhost) + { + // one for the locally predicted rigidbody + CopyRenderersAsGhost(physicsCopy, localGhostMaterial); + + // one for the latest remote state for comparison + // it's important to copy world position/rotation/scale, not local! + // because the original object may be a child of another. + // + // for example: + // parent (scale=1.5) + // child (scale=0.5) + // + // if we copy localScale then the copy has scale=0.5, where as the + // original would have a global scale of ~1.0. + remoteCopy = new GameObject($"{name}_Remote"); + remoteCopy.transform.position = tf.position; // world position! + remoteCopy.transform.rotation = tf.rotation; // world rotation! + remoteCopy.transform.localScale = tf.lossyScale; // world scale! + CopyRenderersAsGhost(remoteCopy, remoteGhostMaterial); + } + + // assign our Rigidbody reference to the ghost + predictedRigidbody = physicsCopy.GetComponent(); + predictedRigidbodyTransform = predictedRigidbody.transform; + } + + protected virtual void DestroyGhosts() + { + // move the copy's Rigidbody back onto self. + // important for scene objects which may be reused for AOI spawn/despawn. + // otherwise next time they wouldn't have a collider anymore. + if (physicsCopy != null) + { + // when moving (Configurable)Joints, their range of motion is + // relative to the initial position. if we move them after the + // GameObject rotated, the range of motion is wrong. + // the easiest solution is to move to initial position, + // then move physics components, then move back. + // => remember previous + Vector3 position = tf.position; + Quaternion rotation = tf.rotation; + Vector3 scale = tf.localScale; + // => reset to initial + physicsCopy.transform.position = tf.position = initialPosition; + physicsCopy.transform.rotation = tf.rotation = initialRotation; + physicsCopy.transform.localScale = tf.lossyScale;// = initialScale; + // => move physics components + PredictionUtils.MovePhysicsComponents(physicsCopy, gameObject); + // => reset previous + tf.position = position; + tf.rotation = rotation; + tf.localScale = scale; + + // when moving components back, we need to undo the joints initial-delta rotation that we added. + Destroy(physicsCopy); + + // reassign our Rigidbody reference + predictedRigidbody = GetComponent(); + predictedRigidbodyTransform = predictedRigidbody.transform; + } + + // simply destroy the remote copy + if (remoteCopy != null) Destroy(remoteCopy); + } + + // this shows in profiler LateUpdates! need to make this as fast as possible! + protected virtual void SmoothFollowPhysicsCopy() + { + // hard follow: + // predictedRigidbodyTransform.GetPositionAndRotation(out Vector3 physicsPosition, out Quaternion physicsRotation); + // tf.SetPositionAndRotation(physicsPosition, physicsRotation); + + // ORIGINAL VERSION: CLEAN AND SIMPLE + /* + // if we are further than N colliders sizes behind, then teleport + float colliderSize = physicsCopyCollider.bounds.size.magnitude; + float threshold = colliderSize * teleportDistanceMultiplier; + float distance = Vector3.Distance(tf.position, physicsCopyRigidbody.position); + if (distance > threshold) + { + tf.position = physicsCopyRigidbody.position; + tf.rotation = physicsCopyRigidbody.rotation; + Debug.Log($"[PredictedRigidbody] Teleported because distance to physics copy = {distance:F2} > threshold {threshold:F2}"); + return; + } + + // smoothly interpolate to the target position. + // speed relative to how far away we are + float positionStep = distance * positionInterpolationSpeed; + tf.position = Vector3.MoveTowards(tf.position, physicsCopyRigidbody.position, positionStep * Time.deltaTime); + + // smoothly interpolate to the target rotation. + // Quaternion.RotateTowards doesn't seem to work at all, so let's use SLerp. + tf.rotation = Quaternion.Slerp(tf.rotation, physicsCopyRigidbody.rotation, rotationInterpolationSpeed * Time.deltaTime); + */ + + // FAST VERSION: this shows in profiler a lot, so cache EVERYTHING! + tf.GetPositionAndRotation(out Vector3 currentPosition, out Quaternion currentRotation); // faster than tf.position + tf.rotation + predictedRigidbodyTransform.GetPositionAndRotation(out Vector3 physicsPosition, out Quaternion physicsRotation); // faster than Rigidbody .position and .rotation + float deltaTime = Time.deltaTime; + + // slow and simple version: + // float distance = Vector3.Distance(currentPosition, physicsPosition); + // if (distance > smoothFollowThreshold) + // faster version + Vector3 delta = physicsPosition - currentPosition; + float sqrDistance = Vector3.SqrMagnitude(delta); + float distance = Mathf.Sqrt(sqrDistance); + if (sqrDistance > smoothFollowThresholdSqr) + { + tf.SetPositionAndRotation(physicsPosition, physicsRotation); // faster than .position and .rotation manually + Debug.Log($"[PredictedRigidbody] Teleported because distance to physics copy = {distance:F2} > threshold {smoothFollowThreshold:F2}"); + return; + } + + // smoothly interpolate to the target position. + // speed relative to how far away we are. + // => speed increases by distance² because the further away, the + // sooner we need to catch the fuck up + // float positionStep = (distance * distance) * interpolationSpeed; + float positionStep = distance * positionInterpolationSpeed; + + Vector3 newPosition = MoveTowardsCustom(currentPosition, physicsPosition, delta, sqrDistance, distance, positionStep * deltaTime); + + // smoothly interpolate to the target rotation. + // Quaternion.RotateTowards doesn't seem to work at all, so let's use SLerp. + // Quaternions always need to be normalized in order to be a valid rotation after operations + Quaternion newRotation = Quaternion.Slerp(currentRotation, physicsRotation, rotationInterpolationSpeed * deltaTime).normalized; + + // assign position and rotation together. faster than accessing manually. + tf.SetPositionAndRotation(newPosition, newRotation); + } + + // simple and slow version with MoveTowards, which recalculates delta and delta.sqrMagnitude: + // Vector3 newPosition = Vector3.MoveTowards(currentPosition, physicsPosition, positionStep * deltaTime); + // faster version copied from MoveTowards: + // this increases Prediction Benchmark Client's FPS from 615 -> 640. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static Vector3 MoveTowardsCustom( + Vector3 current, + Vector3 target, + Vector3 _delta, // pass this in since we already calculated it + float _sqrDistance, // pass this in since we already calculated it + float _distance, // pass this in since we already calculated it + float maxDistanceDelta) + { + if (_sqrDistance == 0.0 || maxDistanceDelta >= 0.0 && _sqrDistance <= maxDistanceDelta * maxDistanceDelta) + return target; + + float distFactor = maxDistanceDelta / _distance; // unlike Vector3.MoveTowards, we only calculate this once + return new Vector3( + // current.x + (_delta.x / _distance) * maxDistanceDelta, + // current.y + (_delta.y / _distance) * maxDistanceDelta, + // current.z + (_delta.z / _distance) * maxDistanceDelta); + current.x + _delta.x * distFactor, + current.y + _delta.y * distFactor, + current.z + _delta.z * distFactor); + } + + // destroy visual copy only in OnStopClient(). + // OnDestroy() wouldn't be called for scene objects that are only disabled instead of destroyed. + public override void OnStopClient() + { + DestroyGhosts(); + } + + void UpdateServer() + { + // bandwidth optimization while idle. + if (reduceSendsWhileIdle) + { + // while moving, always sync every frame for immediate corrections. + // while idle, only sync once per second. + // + // we still need to sync occasionally because objects on client + // may still slide or move slightly due to gravity, physics etc. + // and those still need to get corrected if not moving on server. + // + // TODO + // next round of optimizations: if client received nothing for 1s, + // force correct to last received state. then server doesn't need + // to send once per second anymore. + syncInterval = IsMoving() ? 0 : 1; + } + + // always set dirty to always serialize in next sync interval. + SetDirty(); + } + + // movement detection is virtual, in case projects want to use other methods. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected virtual bool IsMoving() => + // straight forward implementation + // predictedRigidbody.velocity.magnitude >= motionSmoothingVelocityThreshold || + // predictedRigidbody.angularVelocity.magnitude >= motionSmoothingAngularVelocityThreshold; + // faster implementation with cached ² + predictedRigidbody.velocity.sqrMagnitude >= motionSmoothingVelocityThresholdSqr || + predictedRigidbody.angularVelocity.sqrMagnitude >= motionSmoothingAngularVelocityThresholdSqr; + + // TODO maybe merge the IsMoving() checks & callbacks with UpdateState(). + void UpdateGhosting() + { + // perf: enough to check ghosts every few frames. + // PredictionBenchmark: only checking every 4th frame: 585 => 600 FPS + if (Time.frameCount % checkGhostsEveryNthFrame != 0) return; + + // client only uses ghosts on demand while interacting. + // this way 1000 GameObjects don't need +1000 Ghost GameObjects all the time! + + // no ghost at the moment + if (physicsCopy == null) + { + // faster than velocity threshold? then create the ghosts. + // with 10% buffer zone so we don't flip flop all the time. + if (IsMoving()) + { + CreateGhosts(); + OnBeginPrediction(); + } + } + // ghosting at the moment + else + { + // always set last moved time while moving. + // this way we can avoid on/off/oneffects when stopping. + if (IsMoving()) + { + motionSmoothingLastMovedTime = NetworkTime.time; + } + // slower than velocity threshold? then destroy the ghosts. + // with a minimum time since starting to move, to avoid on/off/on effects. + else + { + if (NetworkTime.time >= motionSmoothingLastMovedTime + motionSmoothingTimeTolerance) + { + DestroyGhosts(); + OnEndPrediction(); + physicsCopy = null; // TESTING + } + } + } + } + + // when using Fast mode, we don't create any ghosts. + // but we still want to check IsMoving() in order to support the same + // user callbacks. + bool lastMoving = false; + void UpdateState() + { + // perf: enough to check ghosts every few frames. + // PredictionBenchmark: only checking every 4th frame: 770 => 800 FPS + if (Time.frameCount % checkGhostsEveryNthFrame != 0) return; + + bool moving = IsMoving(); + + // started moving? + if (moving && !lastMoving) + { + OnBeginPrediction(); + lastMoving = true; + } + // stopped moving? + else if (!moving && lastMoving) + { + // ensure a minimum time since starting to move, to avoid on/off/on effects. + if (NetworkTime.time >= motionSmoothingLastMovedTime + motionSmoothingTimeTolerance) + { + OnEndPrediction(); + lastMoving = false; + } + } + } + + void Update() + { + if (isServer) UpdateServer(); + if (isClientOnly) + { + if (mode == PredictionMode.Smooth) + UpdateGhosting(); + else if (mode == PredictionMode.Fast) + UpdateState(); + } + } + + void LateUpdate() + { + // only follow on client-only, not in server or host mode + if (isClientOnly && mode == PredictionMode.Smooth && physicsCopy) SmoothFollowPhysicsCopy(); + } + + void FixedUpdate() + { + // on clients (not host) we record the current state every FixedUpdate. + // this is cheap, and allows us to keep a dense history. + if (!isClientOnly) return; + + // OPTIMIZATION: RecordState() is expensive because it inserts into a SortedList. + // only record if state actually changed! + // risks not having up to date states when correcting, + // but it doesn't matter since we'll always compare with the 'newest' anyway. + // + // we check in here instead of in RecordState() because RecordState() should definitely record if we call it! + if (onlyRecordChanges) + { + // TODO maybe don't reuse the correction thresholds? + tf.GetPositionAndRotation(out Vector3 position, out Quaternion rotation); + // clean & simple: + // if (Vector3.Distance(lastRecorded.position, position) < positionCorrectionThreshold && + // Quaternion.Angle(lastRecorded.rotation, rotation) < rotationCorrectionThreshold) + // faster: + if ((lastRecorded.position - position).sqrMagnitude < positionCorrectionThresholdSqr && + Quaternion.Angle(lastRecorded.rotation, rotation) < rotationCorrectionThreshold) + { + // Debug.Log($"FixedUpdate for {name}: taking optimized early return instead of recording state."); + return; + } + } + + RecordState(); + } + + // manually store last recorded so we can easily check against this + // without traversing the SortedList. + RigidbodyState lastRecorded; + double lastRecordTime; + void RecordState() + { + // performance optimization: only call NetworkTime.time getter once + double networkTime = NetworkTime.time; + + // instead of recording every fixedupdate, let's record in an interval. + // we don't want to record every tiny move and correct too hard. + if (networkTime < lastRecordTime + recordInterval) return; + lastRecordTime = networkTime; + + // NetworkTime.time is always behind by bufferTime. + // prediction aims to be on the exact same server time (immediately). + // use predictedTime to record state, otherwise we would record in the past. + double predictedTime = NetworkTime.predictedTime; + + // FixedUpdate may run twice in the same frame / NetworkTime.time. + // for now, simply don't record if already recorded there. + // previously we checked ContainsKey which is O(logN) for SortedList + // if (stateHistory.ContainsKey(predictedTime)) + // return; + // instead, simply store the last recorded time and don't insert if same. + if (predictedTime == lastRecorded.timestamp) return; + + // keep state history within limit + if (stateHistory.Count >= stateHistoryLimit) + stateHistory.RemoveAt(0); + + // grab current position/rotation/velocity only once. + // this is performance critical, avoid calling .transform multiple times. + tf.GetPositionAndRotation(out Vector3 currentPosition, out Quaternion currentRotation); // faster than accessing .position + .rotation manually + Vector3 currentVelocity = predictedRigidbody.velocity; + Vector3 currentAngularVelocity = predictedRigidbody.angularVelocity; + + // calculate delta to previous state (if any) + Vector3 positionDelta = Vector3.zero; + Vector3 velocityDelta = Vector3.zero; + Vector3 angularVelocityDelta = Vector3.zero; + Quaternion rotationDelta = Quaternion.identity; + int stateHistoryCount = stateHistory.Count; // perf: only grab .Count once + if (stateHistoryCount > 0) + { + RigidbodyState last = stateHistory.Values[stateHistoryCount - 1]; + positionDelta = currentPosition - last.position; + velocityDelta = currentVelocity - last.velocity; + // Quaternions always need to be normalized in order to be valid rotations after operations + rotationDelta = (currentRotation * Quaternion.Inverse(last.rotation)).normalized; + angularVelocityDelta = currentAngularVelocity - last.angularVelocity; + + // debug draw the recorded state + // Debug.DrawLine(last.position, currentPosition, Color.red, lineTime); + } + + // create state to insert + RigidbodyState state = new RigidbodyState( + predictedTime, + positionDelta, + currentPosition, + rotationDelta, + currentRotation, + velocityDelta, + currentVelocity, + angularVelocityDelta, + currentAngularVelocity + ); + + // add state to history + stateHistory.Add(predictedTime, state); + + // manually remember last inserted state for faster .Last comparisons + lastRecorded = state; + } + + // optional user callbacks, in case people need to know about events. + protected virtual void OnSnappedIntoPlace() {} + protected virtual void OnBeforeApplyState() {} + protected virtual void OnCorrected() {} + protected virtual void OnBeginPrediction() {} // when the Rigidbody moved above threshold and we created a ghost + protected virtual void OnEndPrediction() {} // when the Rigidbody came to rest and we destroyed the ghost + + void ApplyState(double timestamp, Vector3 position, Quaternion rotation, Vector3 velocity, Vector3 angularVelocity) + { + // fix rigidbodies seemingly dancing in place instead of coming to rest. + // hard snap to the position below a threshold velocity. + // this is fine because the visual object still smoothly interpolates to it. + // => consider both velocity and angular velocity (in case of Rigidbodies only rotating with joints etc.) + if (predictedRigidbody.velocity.magnitude <= snapThreshold && + predictedRigidbody.angularVelocity.magnitude <= snapThreshold) + { + // Debug.Log($"Prediction: snapped {name} into place because velocity {predictedRigidbody.velocity.magnitude:F3} <= {snapThreshold:F3}"); + + // apply server state immediately. + // important to apply velocity as well, instead of Vector3.zero. + // in case an object is still slightly moving, we don't want it + // to stop and start moving again on client - slide as well here. + predictedRigidbody.position = position; + predictedRigidbody.rotation = rotation; + // projects may keep Rigidbodies as kinematic sometimes. in that case, setting velocity would log an error + if (!predictedRigidbody.isKinematic) + { + predictedRigidbody.velocity = velocity; + predictedRigidbody.angularVelocity = angularVelocity; + } + + // clear history and insert the exact state we just applied. + // this makes future corrections more accurate. + stateHistory.Clear(); + stateHistory.Add(timestamp, new RigidbodyState( + timestamp, + Vector3.zero, + position, + Quaternion.identity, + rotation, + Vector3.zero, + velocity, + Vector3.zero, + angularVelocity + )); + + // user callback + OnSnappedIntoPlace(); + return; + } + + // we have a callback for snapping into place (above). + // we also need one for corrections without snapping into place. + // call it before applying pos/rot/vel in case we need to set kinematic etc. + OnBeforeApplyState(); + + // apply the state to the Rigidbody + if (mode == PredictionMode.Smooth) + { + // Smooth mode separates Physics from Renderering. + // Rendering smoothly follows Physics in SmoothFollowPhysicsCopy(). + // this allows us to be able to hard teleport to the correction. + // which gives most accurate results since the Rigidbody can't + // be stopped by another object when trying to correct. + predictedRigidbody.position = position; + predictedRigidbody.rotation = rotation; + } + else if (mode == PredictionMode.Fast) + { + // Fast mode doesn't separate physics from rendering. + // The only smoothing we get is from Rigidbody.MovePosition. + predictedRigidbody.MovePosition(position); + predictedRigidbody.MoveRotation(rotation); + } + + // there's only one way to set velocity. + // (projects may keep Rigidbodies as kinematic sometimes. in that case, setting velocity would log an error) + if (!predictedRigidbody.isKinematic) + { + predictedRigidbody.velocity = velocity; + predictedRigidbody.angularVelocity = angularVelocity; + } + } + + // process a received server state. + // compares it against our history and applies corrections if needed. + void OnReceivedState(double timestamp, RigidbodyState state)//, bool sleeping) + { + // always update remote state ghost + if (remoteCopy != null) + { + Transform remoteCopyTransform = remoteCopy.transform; + remoteCopyTransform.SetPositionAndRotation(state.position, state.rotation); // faster than .position + .rotation setters + remoteCopyTransform.localScale = tf.lossyScale; // world scale! see CreateGhosts comment. + } + + + // DO NOT SYNC SLEEPING! this cuts benchmark performance in half(!!!) + // color code remote sleeping objects to debug objects coming to rest + // if (showRemoteSleeping) + // { + // rend.material.color = sleeping ? Color.gray : originalColor; + // } + + // performance: get Rigidbody position & rotation only once, + // and together via its transform + predictedRigidbodyTransform.GetPositionAndRotation(out Vector3 physicsPosition, out Quaternion physicsRotation); + + // OPTIONAL performance optimization when comparing idle objects. + // even idle objects will have a history of ~32 entries. + // sampling & traversing through them is unnecessarily costly. + // instead, compare directly against the current rigidbody position! + // => this is technically not 100% correct if an object runs in + // circles where it may revisit the same position twice. + // => but practically, objects that didn't move will have their + // whole history look like the last inserted state. + // => comparing against that is free and gives us a significant + // performance saving vs. a tiny chance of incorrect results due + // to objects running in circles. + // => the RecordState() call below is expensive too, so we want to + // do this before even recording the latest state. the only way + // to do this (in case last recorded state is too old), is to + // compare against live rigidbody.position without any recording. + // this is as fast as it gets for skipping idle objects. + // + // if this ever causes issues, feel free to disable it. + float positionToStateDistanceSqr = Vector3.SqrMagnitude(state.position - physicsPosition); + if (compareLastFirst && + // Vector3.Distance(state.position, physicsPosition) < positionCorrectionThreshold && // slow comparison + positionToStateDistanceSqr < positionCorrectionThresholdSqr && // fast comparison + Quaternion.Angle(state.rotation, physicsRotation) < rotationCorrectionThreshold) + { + // Debug.Log($"OnReceivedState for {name}: taking optimized early return!"); + return; + } + + // we only capture state every 'interval' milliseconds. + // so the newest entry in 'history' may be up to 'interval' behind 'now'. + // if there's no latency, we may receive a server state for 'now'. + // sampling would fail, if we haven't recorded anything in a while. + // to solve this, always record the current state when receiving a server state. + RecordState(); + + // correction requires at least 2 existing states for 'before' and 'after'. + // if we don't have two yet, drop this state and try again next time once we recorded more. + if (stateHistory.Count < 2) return; + + RigidbodyState oldest = stateHistory.Values[0]; + RigidbodyState newest = stateHistory.Values[stateHistory.Count - 1]; + + // edge case: is the state older than the oldest state in history? + // this can happen if the client gets so far behind the server + // that it doesn't have a recored history to sample from. + // in that case, we should hard correct the client. + // otherwise it could be out of sync as long as it's too far behind. + if (state.timestamp < oldest.timestamp) + { + // when starting, client may only have 2-3 states in history. + // it's expected that server states would be behind those 2-3. + // only show a warning if it's behind the full history limit! + if (stateHistory.Count >= stateHistoryLimit) + Debug.LogWarning($"Hard correcting client object {name} because the client is too far behind the server. History of size={stateHistory.Count} @ t={timestamp:F3} oldest={oldest.timestamp:F3} newest={newest.timestamp:F3}. This would cause the client to be out of sync as long as it's behind."); + + // force apply the state + ApplyState(state.timestamp, state.position, state.rotation, state.velocity, state.angularVelocity); + return; + } + + // edge case: is it newer than the newest state in history? + // this can happen if client's predictedTime predicts too far ahead of the server. + // in that case, log a warning for now but still apply the correction. + // otherwise it could be out of sync as long as it's too far ahead. + // + // for example, when running prediction on the same machine with near zero latency. + // when applying corrections here, this looks just fine on the local machine. + if (newest.timestamp < state.timestamp) + { + // the correction is for a state in the future. + // we clamp it to 'now'. + // but only correct if off by threshold. + // TODO maybe we should interpolate this back to 'now'? + // if (Vector3.Distance(state.position, physicsPosition) >= positionCorrectionThreshold) // slow comparison + if (positionToStateDistanceSqr >= positionCorrectionThresholdSqr) // fast comparison + { + // this can happen a lot when latency is ~0. logging all the time allocates too much and is too slow. + // double ahead = state.timestamp - newest.timestamp; + // Debug.Log($"Hard correction because the client is ahead of the server by {(ahead*1000):F1}ms. History of size={stateHistory.Count} @ t={timestamp:F3} oldest={oldest.timestamp:F3} newest={newest.timestamp:F3}. This can happen when latency is near zero, and is fine unless it shows jitter."); + ApplyState(state.timestamp, state.position, state.rotation, state.velocity, state.angularVelocity); + } + return; + } + + // find the two closest client states between timestamp + if (!Prediction.Sample(stateHistory, timestamp, out RigidbodyState before, out RigidbodyState after, out int afterIndex, out double t)) + { + // something went very wrong. sampling should've worked. + // hard correct to recover the error. + Debug.LogError($"Failed to sample history of size={stateHistory.Count} @ t={timestamp:F3} oldest={oldest.timestamp:F3} newest={newest.timestamp:F3}. This should never happen because the timestamp is within history."); + ApplyState(state.timestamp, state.position, state.rotation, state.velocity, state.angularVelocity); + return; + } + + // interpolate between them to get the best approximation + RigidbodyState interpolated = RigidbodyState.Interpolate(before, after, (float)t); + + // calculate the difference between where we were and where we should be + // TODO only position for now. consider rotation etc. too later + // float positionToInterpolatedDistance = Vector3.Distance(state.position, interpolated.position); // slow comparison + float positionToInterpolatedDistanceSqr = Vector3.SqrMagnitude(state.position - interpolated.position); // fast comparison + float rotationToInterpolatedDistance = Quaternion.Angle(state.rotation, interpolated.rotation); + // Debug.Log($"Sampled history of size={stateHistory.Count} @ {timestamp:F3}: client={interpolated.position} server={state.position} difference={difference:F3} / {correctionThreshold:F3}"); + + // too far off? then correct it + if (positionToInterpolatedDistanceSqr >= positionCorrectionThresholdSqr || // fast comparison + //positionToInterpolatedDistance >= positionCorrectionThreshold || // slow comparison + rotationToInterpolatedDistance >= rotationCorrectionThreshold) + { + // Debug.Log($"CORRECTION NEEDED FOR {name} @ {timestamp:F3}: client={interpolated.position} server={state.position} difference={difference:F3}"); + + // show the received correction position + velocity for debugging. + // helps to compare with the interpolated/applied correction locally. + //Debug.DrawLine(state.position, state.position + state.velocity * 0.1f, Color.white, lineTime); + + // insert the correction and correct the history on top of it. + // returns the final recomputed state after rewinding. + RigidbodyState recomputed = Prediction.CorrectHistory(stateHistory, stateHistoryLimit, state, before, after, afterIndex); + + // log, draw & apply the final position. + // always do this here, not when iterating above, in case we aren't iterating. + // for example, on same machine with near zero latency. + // int correctedAmount = stateHistory.Count - afterIndex; + // Debug.Log($"Correcting {name}: {correctedAmount} / {stateHistory.Count} states to final position from: {rb.position} to: {last.position}"); + //Debug.DrawLine(physicsCopyRigidbody.position, recomputed.position, Color.green, lineTime); + ApplyState(recomputed.timestamp, recomputed.position, recomputed.rotation, recomputed.velocity, recomputed.angularVelocity); + + // user callback + OnCorrected(); + } + } + + // send state to clients every sendInterval. + // reliable for now. + // TODO we should use the one from FixedUpdate + public override void OnSerialize(NetworkWriter writer, bool initialState) + { + // Time.time was at the beginning of this frame. + // NetworkLateUpdate->Broadcast->OnSerialize is at the end of the frame. + // as result, client should use this to correct the _next_ frame. + // otherwise we see noticeable resets that seem off by one frame. + // + // to solve this, we can send the current deltaTime. + // server is technically supposed to be at a fixed frame rate, but this can vary. + // sending server's current deltaTime is the safest option. + // client then applies it on top of remoteTimestamp. + + + // FAST VERSION: this shows in profiler a lot, so cache EVERYTHING! + tf.GetPositionAndRotation(out Vector3 position, out Quaternion rotation); // faster than tf.position + tf.rotation. server's rigidbody is on the same transform. + + // simple but slow write: + // writer.WriteFloat(Time.deltaTime); + // writer.WriteVector3(position); + // writer.WriteQuaternion(rotation); + // writer.WriteVector3(predictedRigidbody.velocity); + // writer.WriteVector3(predictedRigidbody.angularVelocity); + + // performance optimization: write a whole struct at once via blittable: + PredictedSyncData data = new PredictedSyncData( + Time.deltaTime, + position, + rotation, + predictedRigidbody.velocity, + predictedRigidbody.angularVelocity);//, + // DO NOT SYNC SLEEPING! this cuts benchmark performance in half(!!!) + // predictedRigidbody.IsSleeping()); + writer.WritePredictedSyncData(data); + } + + // read the server's state, compare with client state & correct if necessary. + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + // deserialize data + // we want to know the time on the server when this was sent, which is remoteTimestamp. + double timestamp = NetworkClient.connection.remoteTimeStamp; + + // simple but slow read: + // double serverDeltaTime = reader.ReadFloat(); + // Vector3 position = reader.ReadVector3(); + // Quaternion rotation = reader.ReadQuaternion(); + // Vector3 velocity = reader.ReadVector3(); + // Vector3 angularVelocity = reader.ReadVector3(); + + // performance optimization: read a whole struct at once via blittable: + PredictedSyncData data = reader.ReadPredictedSyncData(); + double serverDeltaTime = data.deltaTime; + Vector3 position = data.position; + Quaternion rotation = data.rotation; + Vector3 velocity = data.velocity; + Vector3 angularVelocity = data.angularVelocity; + // DO NOT SYNC SLEEPING! this cuts benchmark performance in half(!!!) + // bool sleeping = data.sleeping != 0; + + // server sends state at the end of the frame. + // parse and apply the server's delta time to our timestamp. + // otherwise we see noticeable resets that seem off by one frame. + timestamp += serverDeltaTime; + + // however, adding yet one more frame delay gives much(!) better results. + // we don't know why yet, so keep this as an option for now. + // possibly because client captures at the beginning of the frame, + // with physics happening at the end of the frame? + if (oneFrameAhead) timestamp += serverDeltaTime; + + // process received state + OnReceivedState(timestamp, new RigidbodyState(timestamp, Vector3.zero, position, Quaternion.identity, rotation, Vector3.zero, velocity, Vector3.zero, angularVelocity));//, sleeping); + } + + protected override void OnValidate() + { + base.OnValidate(); + + // force syncDirection to be ServerToClient + syncDirection = SyncDirection.ServerToClient; + + // state should be synced immediately for now. + // later when we have prediction fully dialed in, + // then we can maybe relax this a bit. + syncInterval = 0; + } + + // helper function for Physics tests to check if a Rigidbody belongs to + // a PredictedRigidbody component (either on it, or on its ghost). + public static bool IsPredicted(Rigidbody rb, out PredictedRigidbody predictedRigidbody) + { + // by default, Rigidbody is on the PredictedRigidbody GameObject + if (rb.TryGetComponent(out predictedRigidbody)) + return true; + + // it might be on a ghost while interacting + if (rb.TryGetComponent(out PredictedRigidbodyPhysicsGhost ghost)) + { + predictedRigidbody = ghost.target.GetComponent(); + return true; + } + + // otherwise the Rigidbody does not belong to any PredictedRigidbody. + predictedRigidbody = null; + return false; + } + + // helper function for Physics tests to check if a Collider (which may be in children) belongs to + // a PredictedRigidbody component (either on it, or on its ghost). + public static bool IsPredicted(Collider co, out PredictedRigidbody predictedRigidbody) + { + // by default, Collider is on the PredictedRigidbody GameObject or it's children. + predictedRigidbody = co.GetComponentInParent(); + if (predictedRigidbody != null) + return true; + + // it might be on a ghost while interacting + PredictedRigidbodyPhysicsGhost ghost = co.GetComponentInParent(); + if (ghost != null && ghost.target != null && ghost.target.TryGetComponent(out predictedRigidbody)) + return true; + + // otherwise the Rigidbody does not belong to any PredictedRigidbody. + predictedRigidbody = null; + return false; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs.meta b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs.meta new file mode 100644 index 0000000000..df5e7209ae --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs.meta @@ -0,0 +1,22 @@ +fileFormatVersion: 2 +guid: d38927cdc6024b9682b5fe9778b9ef99 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: + - localGhostMaterial: {fileID: 2100000, guid: 411a48b4a197d4924bec3e3809bc9320, + type: 2} + - remoteGhostMaterial: {fileID: 2100000, guid: 04f0b2088c857414393bab3b80356776, + type: 2} + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyPhysicsGhost.cs b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyPhysicsGhost.cs new file mode 100644 index 0000000000..f28d49faee --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyPhysicsGhost.cs @@ -0,0 +1,15 @@ +// Prediction moves out the Rigidbody & Collider into a separate object. +// this component simply points back to the owner component. +// in case Raycasts hit it and need to know the owner, etc. +using UnityEngine; + +namespace Mirror +{ + public class PredictedRigidbodyPhysicsGhost : MonoBehaviour + { + // this is performance critical, so store target's .Transform instead of + // PredictedRigidbody, this way we don't need to call the .transform getter. + [Tooltip("The predicted rigidbody owner.")] + public Transform target; + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyPhysicsGhost.cs.meta b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyPhysicsGhost.cs.meta new file mode 100644 index 0000000000..5009478f9c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyPhysicsGhost.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 25593abc9bf0d44878a4ad6018204061 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyPhysicsGhost.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyRemoteGhost.cs b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyRemoteGhost.cs new file mode 100644 index 0000000000..636f397024 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyRemoteGhost.cs @@ -0,0 +1 @@ +// removed 2024-02-09 diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyRemoteGhost.cs.meta b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyRemoteGhost.cs.meta new file mode 100644 index 0000000000..b65402d071 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyRemoteGhost.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 62e7e9424c7e48d69b6a3517796142a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedRigidbodyRemoteGhost.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedSyncData.cs b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedSyncData.cs new file mode 100644 index 0000000000..fa652fd14d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedSyncData.cs @@ -0,0 +1,54 @@ +// this struct exists only for OnDe/Serialize performance. +// instead of WriteVector3+Quaternion+Vector3+Vector3, +// we read & write the whole struct as blittable once. +// +// struct packing can cause odd results with blittable on different platforms, +// so this is usually not recommended! +// +// in this case however, we need to squeeze everything we can out of prediction +// to support low even devices / VR. +using System.Runtime.InteropServices; +using UnityEngine; + +namespace Mirror +{ + // struct packing + + [StructLayout(LayoutKind.Sequential)] // explicitly force sequential + public struct PredictedSyncData + { + public float deltaTime; // 4 bytes (word aligned) + public Vector3 position; // 12 bytes (word aligned) + public Quaternion rotation; // 16 bytes (word aligned) + public Vector3 velocity; // 12 bytes (word aligned) + public Vector3 angularVelocity; // 12 bytes (word aligned) + // DO NOT SYNC SLEEPING! this cuts benchmark performance in half(!!!) + // public byte sleeping; // 1 byte: bool isn't blittable + + // constructor for convenience + public PredictedSyncData(float deltaTime, Vector3 position, Quaternion rotation, Vector3 velocity, Vector3 angularVelocity)//, bool sleeping) + { + this.deltaTime = deltaTime; + this.position = position; + this.rotation = rotation; + this.velocity = velocity; + this.angularVelocity = angularVelocity; + // DO NOT SYNC SLEEPING! this cuts benchmark performance in half(!!!) + // this.sleeping = sleeping ? (byte)1 : (byte)0; + } + } + + // NetworkReader/Writer extensions to write this struct + public static class PredictedSyncDataReadWrite + { + public static void WritePredictedSyncData(this NetworkWriter writer, PredictedSyncData data) + { + writer.WriteBlittable(data); + } + + public static PredictedSyncData ReadPredictedSyncData(this NetworkReader reader) + { + return reader.ReadBlittable(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedSyncData.cs.meta b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedSyncData.cs.meta new file mode 100644 index 0000000000..1fda2d891f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedSyncData.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f595f112a39e4634b670d56991b23823 +timeCreated: 1710387026 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictedSyncData.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictionUtils.cs b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictionUtils.cs new file mode 100644 index 0000000000..6c8892374e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictionUtils.cs @@ -0,0 +1,419 @@ +// standalone utility functions for PredictedRigidbody component. +using System; +using UnityEngine; + +namespace Mirror +{ + public static class PredictionUtils + { + // rigidbody /////////////////////////////////////////////////////////// + // move a Rigidbody + settings from one GameObject to another. + public static void MoveRigidbody(GameObject source, GameObject destination, bool destroySource = true) + { + // create a new Rigidbody component on destination. + // note that adding a Joint automatically adds a Rigidbody. + // so first check if one was added yet. + Rigidbody original = source.GetComponent(); + if (original == null) throw new Exception($"Prediction: attempted to move {source}'s Rigidbody to the predicted copy, but there was no component."); + Rigidbody rigidbodyCopy; + if (!destination.TryGetComponent(out rigidbodyCopy)) + rigidbodyCopy = destination.AddComponent(); + + // copy all properties + rigidbodyCopy.mass = original.mass; + rigidbodyCopy.drag = original.drag; + rigidbodyCopy.angularDrag = original.angularDrag; + rigidbodyCopy.useGravity = original.useGravity; + rigidbodyCopy.isKinematic = original.isKinematic; + rigidbodyCopy.interpolation = original.interpolation; + rigidbodyCopy.collisionDetectionMode = original.collisionDetectionMode; + rigidbodyCopy.constraints = original.constraints; + rigidbodyCopy.sleepThreshold = original.sleepThreshold; + rigidbodyCopy.freezeRotation = original.freezeRotation; + + // moving (Configurable)Joints messes up their range of motion unless + // we reset to initial position first (we do this in PredictedRigibody.cs). + // so here we don't set the Rigidbody's physics position at all. + // rigidbodyCopy.position = original.position; + // rigidbodyCopy.rotation = original.rotation; + + // projects may keep Rigidbodies as kinematic sometimes. in that case, setting velocity would log an error + if (!original.isKinematic) + { + rigidbodyCopy.velocity = original.velocity; + rigidbodyCopy.angularVelocity = original.angularVelocity; + } + + // destroy original + if (destroySource) GameObject.Destroy(original); + } + + // helper function: if a collider is on a child, copy that child first. + // this way child's relative position/rotation/scale are preserved. + public static GameObject CopyRelativeTransform(GameObject source, Transform sourceChild, GameObject destination) + { + // is this on the source root? then we want to put it on the destination root. + if (sourceChild == source.transform) return destination; + + // is this on a child? then create the same child with the same transform on destination. + // note this is technically only correct for the immediate child since + // .localPosition is relative to parent, but this is good enough. + GameObject child = new GameObject(sourceChild.name); + child.transform.SetParent(destination.transform, true); + child.transform.localPosition = sourceChild.localPosition; + child.transform.localRotation = sourceChild.localRotation; + child.transform.localScale = sourceChild.localScale; + + // assign the same Layer for the physics copy. + // games may use a custom physics collision matrix, layer matters. + child.layer = sourceChild.gameObject.layer; + + return child; + } + + // colliders /////////////////////////////////////////////////////////// + // move all BoxColliders + settings from one GameObject to another. + public static void MoveBoxColliders(GameObject source, GameObject destination, bool destroySource = true) + { + // colliders may be on children + BoxCollider[] sourceColliders = source.GetComponentsInChildren(); + foreach (BoxCollider sourceCollider in sourceColliders) + { + // copy the relative transform: + // if collider is on root, it returns destination root. + // if collider is on a child, it creates and returns a child on destination. + GameObject target = CopyRelativeTransform(source, sourceCollider.transform, destination); + BoxCollider colliderCopy = target.AddComponent(); + colliderCopy.center = sourceCollider.center; + colliderCopy.size = sourceCollider.size; + colliderCopy.isTrigger = sourceCollider.isTrigger; + colliderCopy.material = sourceCollider.material; + if (destroySource) GameObject.Destroy(sourceCollider); + } + } + + // move all SphereColliders + settings from one GameObject to another. + public static void MoveSphereColliders(GameObject source, GameObject destination, bool destroySource = true) + { + // colliders may be on children + SphereCollider[] sourceColliders = source.GetComponentsInChildren(); + foreach (SphereCollider sourceCollider in sourceColliders) + { + // copy the relative transform: + // if collider is on root, it returns destination root. + // if collider is on a child, it creates and returns a child on destination. + GameObject target = CopyRelativeTransform(source, sourceCollider.transform, destination); + SphereCollider colliderCopy = target.AddComponent(); + colliderCopy.center = sourceCollider.center; + colliderCopy.radius = sourceCollider.radius; + colliderCopy.isTrigger = sourceCollider.isTrigger; + colliderCopy.material = sourceCollider.material; + if (destroySource) GameObject.Destroy(sourceCollider); + } + } + + // move all CapsuleColliders + settings from one GameObject to another. + public static void MoveCapsuleColliders(GameObject source, GameObject destination, bool destroySource = true) + { + // colliders may be on children + CapsuleCollider[] sourceColliders = source.GetComponentsInChildren(); + foreach (CapsuleCollider sourceCollider in sourceColliders) + { + // copy the relative transform: + // if collider is on root, it returns destination root. + // if collider is on a child, it creates and returns a child on destination. + GameObject target = CopyRelativeTransform(source, sourceCollider.transform, destination); + CapsuleCollider colliderCopy = target.AddComponent(); + colliderCopy.center = sourceCollider.center; + colliderCopy.radius = sourceCollider.radius; + colliderCopy.height = sourceCollider.height; + colliderCopy.direction = sourceCollider.direction; + colliderCopy.isTrigger = sourceCollider.isTrigger; + colliderCopy.material = sourceCollider.material; + if (destroySource) GameObject.Destroy(sourceCollider); + } + } + + // move all MeshColliders + settings from one GameObject to another. + public static void MoveMeshColliders(GameObject source, GameObject destination, bool destroySource = true) + { + // colliders may be on children + MeshCollider[] sourceColliders = source.GetComponentsInChildren(); + foreach (MeshCollider sourceCollider in sourceColliders) + { + // when Models have Mesh->Read/Write disabled, it means that Unity + // uploads the mesh directly to the GPU and erases it on the CPU. + // on some platforms this makes moving a MeshCollider in builds impossible: + // + // "CollisionMeshData couldn't be created because the mesh has been marked as non-accessible." + // + // on other platforms, this works fine. + // let's show an explicit log message so in case collisions don't + // work at runtime, it's obvious why it happens and how to fix it. + if (!sourceCollider.sharedMesh.isReadable) + { + Debug.Log($"[Prediction]: MeshCollider on {sourceCollider.name} isn't readable, which may indicate that the Mesh only exists on the GPU. If {sourceCollider.name} is missing collisions, then please select the model in the Project Area, and enable Mesh->Read/Write so it's also available on the CPU!"); + // don't early return. keep trying, it may work. + } + + // copy the relative transform: + // if collider is on root, it returns destination root. + // if collider is on a child, it creates and returns a child on destination. + GameObject target = CopyRelativeTransform(source, sourceCollider.transform, destination); + MeshCollider colliderCopy = target.AddComponent(); + colliderCopy.sharedMesh = sourceCollider.sharedMesh; + colliderCopy.convex = sourceCollider.convex; + colliderCopy.isTrigger = sourceCollider.isTrigger; + colliderCopy.material = sourceCollider.material; + if (destroySource) GameObject.Destroy(sourceCollider); + } + } + + // move all Colliders + settings from one GameObject to another. + public static void MoveAllColliders(GameObject source, GameObject destination, bool destroySource = true) + { + MoveBoxColliders(source, destination, destroySource); + MoveSphereColliders(source, destination, destroySource); + MoveCapsuleColliders(source, destination, destroySource); + MoveMeshColliders(source, destination, destroySource); + } + + // joints ////////////////////////////////////////////////////////////// + // move all CharacterJoints + settings from one GameObject to another. + public static void MoveCharacterJoints(GameObject source, GameObject destination, bool destroySource = true) + { + // colliders may be on children + CharacterJoint[] sourceJoints = source.GetComponentsInChildren(); + foreach (CharacterJoint sourceJoint in sourceJoints) + { + // copy the relative transform: + // if joint is on root, it returns destination root. + // if joint is on a child, it creates and returns a child on destination. + GameObject target = CopyRelativeTransform(source, sourceJoint.transform, destination); + CharacterJoint jointCopy = target.AddComponent(); + // apply settings, in alphabetical order + jointCopy.anchor = sourceJoint.anchor; + jointCopy.autoConfigureConnectedAnchor = sourceJoint.autoConfigureConnectedAnchor; + jointCopy.axis = sourceJoint.axis; + jointCopy.breakForce = sourceJoint.breakForce; + jointCopy.breakTorque = sourceJoint.breakTorque; + jointCopy.connectedAnchor = sourceJoint.connectedAnchor; + jointCopy.connectedBody = sourceJoint.connectedBody; + jointCopy.connectedMassScale = sourceJoint.connectedMassScale; + jointCopy.enableCollision = sourceJoint.enableCollision; + jointCopy.enablePreprocessing = sourceJoint.enablePreprocessing; + jointCopy.enableProjection = sourceJoint.enableProjection; + jointCopy.highTwistLimit = sourceJoint.highTwistLimit; + jointCopy.lowTwistLimit = sourceJoint.lowTwistLimit; + jointCopy.massScale = sourceJoint.massScale; + jointCopy.projectionAngle = sourceJoint.projectionAngle; + jointCopy.projectionDistance = sourceJoint.projectionDistance; + jointCopy.swing1Limit = sourceJoint.swing1Limit; + jointCopy.swing2Limit = sourceJoint.swing2Limit; + jointCopy.swingAxis = sourceJoint.swingAxis; + jointCopy.swingLimitSpring = sourceJoint.swingLimitSpring; + jointCopy.twistLimitSpring = sourceJoint.twistLimitSpring; +#if UNITY_2020_3_OR_NEWER + jointCopy.connectedArticulationBody = sourceJoint.connectedArticulationBody; +#endif + + if (destroySource) GameObject.Destroy(sourceJoint); + } + } + + // move all ConfigurableJoints + settings from one GameObject to another. + public static void MoveConfigurableJoints(GameObject source, GameObject destination, bool destroySource = true) + { + // colliders may be on children + ConfigurableJoint[] sourceJoints = source.GetComponentsInChildren(); + foreach (ConfigurableJoint sourceJoint in sourceJoints) + { + // copy the relative transform: + // if joint is on root, it returns destination root. + // if joint is on a child, it creates and returns a child on destination. + GameObject target = CopyRelativeTransform(source, sourceJoint.transform, destination); + ConfigurableJoint jointCopy = target.AddComponent(); + // apply settings, in alphabetical order + jointCopy.anchor = sourceJoint.anchor; + jointCopy.angularXLimitSpring = sourceJoint.angularXLimitSpring; + jointCopy.angularXDrive = sourceJoint.angularXDrive; + jointCopy.angularXMotion = sourceJoint.angularXMotion; + jointCopy.angularYLimit = sourceJoint.angularYLimit; + jointCopy.angularYMotion = sourceJoint.angularYMotion; + jointCopy.angularYZDrive = sourceJoint.angularYZDrive; + jointCopy.angularYZLimitSpring = sourceJoint.angularYZLimitSpring; + jointCopy.angularZLimit = sourceJoint.angularZLimit; + jointCopy.angularZMotion = sourceJoint.angularZMotion; + jointCopy.autoConfigureConnectedAnchor = sourceJoint.autoConfigureConnectedAnchor; + jointCopy.axis = sourceJoint.axis; + jointCopy.breakForce = sourceJoint.breakForce; + jointCopy.breakTorque = sourceJoint.breakTorque; + jointCopy.configuredInWorldSpace = sourceJoint.configuredInWorldSpace; + jointCopy.connectedAnchor = sourceJoint.connectedAnchor; + jointCopy.connectedBody = sourceJoint.connectedBody; + jointCopy.connectedMassScale = sourceJoint.connectedMassScale; + jointCopy.enableCollision = sourceJoint.enableCollision; + jointCopy.enablePreprocessing = sourceJoint.enablePreprocessing; + jointCopy.highAngularXLimit = sourceJoint.highAngularXLimit; // moving this only works if the object is at initial position/rotation/scale, see PredictedRigidbody.cs + jointCopy.linearLimitSpring = sourceJoint.linearLimitSpring; + jointCopy.linearLimit = sourceJoint.linearLimit; + jointCopy.lowAngularXLimit = sourceJoint.lowAngularXLimit; // moving this only works if the object is at initial position/rotation/scale, see PredictedRigidbody.cs + jointCopy.massScale = sourceJoint.massScale; + jointCopy.projectionAngle = sourceJoint.projectionAngle; + jointCopy.projectionDistance = sourceJoint.projectionDistance; + jointCopy.projectionMode = sourceJoint.projectionMode; + jointCopy.rotationDriveMode = sourceJoint.rotationDriveMode; + jointCopy.secondaryAxis = sourceJoint.secondaryAxis; + jointCopy.slerpDrive = sourceJoint.slerpDrive; + jointCopy.swapBodies = sourceJoint.swapBodies; + jointCopy.targetAngularVelocity = sourceJoint.targetAngularVelocity; + jointCopy.targetPosition = sourceJoint.targetPosition; + jointCopy.targetRotation = sourceJoint.targetRotation; + jointCopy.targetVelocity = sourceJoint.targetVelocity; + jointCopy.xDrive = sourceJoint.xDrive; + jointCopy.xMotion = sourceJoint.xMotion; + jointCopy.yDrive = sourceJoint.yDrive; + jointCopy.yMotion = sourceJoint.yMotion; + jointCopy.zDrive = sourceJoint.zDrive; + jointCopy.zMotion = sourceJoint.zMotion; +#if UNITY_2020_3_OR_NEWER + jointCopy.connectedArticulationBody = sourceJoint.connectedArticulationBody; +#endif + + if (destroySource) GameObject.Destroy(sourceJoint); + } + } + + // move all FixedJoints + settings from one GameObject to another. + public static void MoveFixedJoints(GameObject source, GameObject destination, bool destroySource = true) + { + // colliders may be on children + FixedJoint[] sourceJoints = source.GetComponentsInChildren(); + foreach (FixedJoint sourceJoint in sourceJoints) + { + // copy the relative transform: + // if joint is on root, it returns destination root. + // if joint is on a child, it creates and returns a child on destination. + GameObject target = CopyRelativeTransform(source, sourceJoint.transform, destination); + FixedJoint jointCopy = target.AddComponent(); + // apply settings, in alphabetical order + jointCopy.anchor = sourceJoint.anchor; + jointCopy.autoConfigureConnectedAnchor = sourceJoint.autoConfigureConnectedAnchor; + jointCopy.axis = sourceJoint.axis; + jointCopy.breakForce = sourceJoint.breakForce; + jointCopy.breakTorque = sourceJoint.breakTorque; + jointCopy.connectedAnchor = sourceJoint.connectedAnchor; + jointCopy.connectedBody = sourceJoint.connectedBody; + jointCopy.connectedMassScale = sourceJoint.connectedMassScale; + jointCopy.enableCollision = sourceJoint.enableCollision; + jointCopy.enablePreprocessing = sourceJoint.enablePreprocessing; + jointCopy.massScale = sourceJoint.massScale; +#if UNITY_2020_3_OR_NEWER + jointCopy.connectedArticulationBody = sourceJoint.connectedArticulationBody; +#endif + + if (destroySource) GameObject.Destroy(sourceJoint); + } + } + + // move all HingeJoints + settings from one GameObject to another. + public static void MoveHingeJoints(GameObject source, GameObject destination, bool destroySource = true) + { + // colliders may be on children + HingeJoint[] sourceJoints = source.GetComponentsInChildren(); + foreach (HingeJoint sourceJoint in sourceJoints) + { + // copy the relative transform: + // if joint is on root, it returns destination root. + // if joint is on a child, it creates and returns a child on destination. + GameObject target = CopyRelativeTransform(source, sourceJoint.transform, destination); + HingeJoint jointCopy = target.AddComponent(); + // apply settings, in alphabetical order + jointCopy.anchor = sourceJoint.anchor; + jointCopy.autoConfigureConnectedAnchor = sourceJoint.autoConfigureConnectedAnchor; + jointCopy.axis = sourceJoint.axis; + jointCopy.breakForce = sourceJoint.breakForce; + jointCopy.breakTorque = sourceJoint.breakTorque; + jointCopy.connectedAnchor = sourceJoint.connectedAnchor; + jointCopy.connectedBody = sourceJoint.connectedBody; + jointCopy.connectedMassScale = sourceJoint.connectedMassScale; + jointCopy.enableCollision = sourceJoint.enableCollision; + jointCopy.enablePreprocessing = sourceJoint.enablePreprocessing; + jointCopy.limits = sourceJoint.limits; + jointCopy.massScale = sourceJoint.massScale; + jointCopy.motor = sourceJoint.motor; + jointCopy.spring = sourceJoint.spring; + jointCopy.useLimits = sourceJoint.useLimits; + jointCopy.useMotor = sourceJoint.useMotor; + jointCopy.useSpring = sourceJoint.useSpring; +#if UNITY_2020_3_OR_NEWER + jointCopy.connectedArticulationBody = sourceJoint.connectedArticulationBody; +#endif +#if UNITY_2022_3_OR_NEWER + jointCopy.extendedLimits = sourceJoint.extendedLimits; + jointCopy.useAcceleration = sourceJoint.useAcceleration; +#endif + + if (destroySource) GameObject.Destroy(sourceJoint); + } + } + + // move all SpringJoints + settings from one GameObject to another. + public static void MoveSpringJoints(GameObject source, GameObject destination, bool destroySource = true) + { + // colliders may be on children + SpringJoint[] sourceJoints = source.GetComponentsInChildren(); + foreach (SpringJoint sourceJoint in sourceJoints) + { + // copy the relative transform: + // if joint is on root, it returns destination root. + // if joint is on a child, it creates and returns a child on destination. + GameObject target = CopyRelativeTransform(source, sourceJoint.transform, destination); + SpringJoint jointCopy = target.AddComponent(); + // apply settings, in alphabetical order + jointCopy.anchor = sourceJoint.anchor; + jointCopy.autoConfigureConnectedAnchor = sourceJoint.autoConfigureConnectedAnchor; + jointCopy.axis = sourceJoint.axis; + jointCopy.breakForce = sourceJoint.breakForce; + jointCopy.breakTorque = sourceJoint.breakTorque; + jointCopy.connectedAnchor = sourceJoint.connectedAnchor; + jointCopy.connectedBody = sourceJoint.connectedBody; + jointCopy.connectedMassScale = sourceJoint.connectedMassScale; + jointCopy.damper = sourceJoint.damper; + jointCopy.enableCollision = sourceJoint.enableCollision; + jointCopy.enablePreprocessing = sourceJoint.enablePreprocessing; + jointCopy.massScale = sourceJoint.massScale; + jointCopy.maxDistance = sourceJoint.maxDistance; + jointCopy.minDistance = sourceJoint.minDistance; + jointCopy.spring = sourceJoint.spring; + jointCopy.tolerance = sourceJoint.tolerance; +#if UNITY_2020_3_OR_NEWER + jointCopy.connectedArticulationBody = sourceJoint.connectedArticulationBody; +#endif + + if (destroySource) GameObject.Destroy(sourceJoint); + } + } + + // move all Joints + settings from one GameObject to another. + public static void MoveAllJoints(GameObject source, GameObject destination, bool destroySource = true) + { + MoveCharacterJoints(source, destination, destroySource); + MoveConfigurableJoints(source, destination, destroySource); + MoveFixedJoints(source, destination, destroySource); + MoveHingeJoints(source, destination, destroySource); + MoveSpringJoints(source, destination, destroySource); + } + + // all ///////////////////////////////////////////////////////////////// + // move all physics components from one GameObject to another. + public static void MovePhysicsComponents(GameObject source, GameObject destination, bool destroySource = true) + { + // need to move joints first, otherwise we might see: + // 'can't move Rigidbody because a Joint depends on it' + MoveAllJoints(source, destination, destroySource); + MoveAllColliders(source, destination, destroySource); + MoveRigidbody(source, destination, destroySource); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictionUtils.cs.meta b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictionUtils.cs.meta new file mode 100644 index 0000000000..a6d99cb90d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictionUtils.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 17cfe1beb3f94a69b94bf60afc37ef7a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/PredictionUtils.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RemoteGhostMaterial.mat b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RemoteGhostMaterial.mat new file mode 100644 index 0000000000..d652a50166 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RemoteGhostMaterial.mat @@ -0,0 +1,85 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 8 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: RemoteGhostMaterial + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_Parent: {fileID: 0} + m_ModifiedSerializedProperties: 0 + m_ValidKeywords: + - _ALPHAPREMULTIPLY_ON + m_InvalidKeywords: [] + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: 3000 + stringTagMap: + RenderType: Transparent + disabledShaderPasses: [] + m_LockedProperties: + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _BumpMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailAlbedoMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailMask: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailNormalMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _EmissionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MetallicGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _OcclusionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _ParallaxMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Ints: [] + m_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 10 + - _GlossMapScale: 1 + - _Glossiness: 0.92 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 3 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 0 + m_Colors: + - _Color: {r: 0.09849727, g: 1, b: 0, a: 0.15686275} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} + m_BuildTextureStacks: [] diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RemoteGhostMaterial.mat.meta b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RemoteGhostMaterial.mat.meta new file mode 100644 index 0000000000..541e21dded --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RemoteGhostMaterial.mat.meta @@ -0,0 +1,15 @@ +fileFormatVersion: 2 +guid: 04f0b2088c857414393bab3b80356776 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RemoteGhostMaterial.mat + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RigidbodyState.cs b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RigidbodyState.cs new file mode 100644 index 0000000000..c30ce4a0ca --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RigidbodyState.cs @@ -0,0 +1,60 @@ +// PredictedRigidbody stores a history of its rigidbody states. +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + // inline everything because this is performance critical! + public struct RigidbodyState : PredictedState + { + public double timestamp { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] private set; } + + // we want to store position delta (last + delta = current), and current. + // this way we can apply deltas on top of corrected positions to get the corrected final position. + public Vector3 positionDelta { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] set; } // delta to get from last to this position + public Vector3 position { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] set; } + + public Quaternion rotationDelta { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] set; } // delta to get from last to this rotation + public Quaternion rotation { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] set; } + + public Vector3 velocityDelta { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] set; } // delta to get from last to this velocity + public Vector3 velocity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] set; } + + public Vector3 angularVelocityDelta { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] set; } // delta to get from last to this velocity + public Vector3 angularVelocity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] set; } + + public RigidbodyState( + double timestamp, + Vector3 positionDelta, + Vector3 position, + Quaternion rotationDelta, + Quaternion rotation, + Vector3 velocityDelta, + Vector3 velocity, + Vector3 angularVelocityDelta, + Vector3 angularVelocity) + { + this.timestamp = timestamp; + this.positionDelta = positionDelta; + this.position = position; + this.rotationDelta = rotationDelta; + this.rotation = rotation; + this.velocityDelta = velocityDelta; + this.velocity = velocity; + this.angularVelocityDelta = angularVelocityDelta; + this.angularVelocity = angularVelocity; + } + + public static RigidbodyState Interpolate(RigidbodyState a, RigidbodyState b, float t) + { + return new RigidbodyState + { + position = Vector3.Lerp(a.position, b.position, t), + // Quaternions always need to be normalized in order to be a valid rotation after operations + rotation = Quaternion.Slerp(a.rotation, b.rotation, t).normalized, + velocity = Vector3.Lerp(a.velocity, b.velocity, t), + angularVelocity = Vector3.Lerp(a.angularVelocity, b.angularVelocity, t) + }; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RigidbodyState.cs.meta b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RigidbodyState.cs.meta new file mode 100644 index 0000000000..c9be4bc76b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RigidbodyState.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ed0e1c0c874c4c9db6be2d5885bb7bee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/PredictedRigidbody/RigidbodyState.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Components/RemoteStatistics.cs b/Assets/ImportedAssets/Mirror/Components/RemoteStatistics.cs new file mode 100644 index 0000000000..5b3ede9cd7 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/RemoteStatistics.cs @@ -0,0 +1,441 @@ +// remote statistics panel from Mirror II to show connections, load, etc. +// server syncs statistics to clients if authenticated. +// +// attach this to a player. +// requires NetworkStatistics component on the Network object. +// +// Unity's OnGUI is the easiest to use solution at the moment. +// * playfab is super complex to set up +// * http servers would be nice, but still need to open ports, live refresh, etc +// +// for safety reasons, let's keep this read-only. +// at least until there's safe authentication. +using System; +using System.IO; +using UnityEngine; + +namespace Mirror +{ + // server -> client + struct Stats + { + // general + public int connections; + public double uptime; + public int configuredTickRate; + public int actualTickRate; + + // traffic + public long sentBytesPerSecond; + public long receiveBytesPerSecond; + + // cpu + public float serverTickInterval; + public double fullUpdateAvg; + public double serverEarlyAvg; + public double serverLateAvg; + public double transportEarlyAvg; + public double transportLateAvg; + + // C# boilerplate + public Stats( + // general + int connections, + double uptime, + int configuredTickRate, + int actualTickRate, + // traffic + long sentBytesPerSecond, + long receiveBytesPerSecond, + // cpu + float serverTickInterval, + double fullUpdateAvg, + double serverEarlyAvg, + double serverLateAvg, + double transportEarlyAvg, + double transportLateAvg + ) + { + // general + this.connections = connections; + this.uptime = uptime; + this.configuredTickRate = configuredTickRate; + this.actualTickRate = actualTickRate; + + // traffic + this.sentBytesPerSecond = sentBytesPerSecond; + this.receiveBytesPerSecond = receiveBytesPerSecond; + + // cpu + this.serverTickInterval = serverTickInterval; + this.fullUpdateAvg = fullUpdateAvg; + this.serverEarlyAvg = serverEarlyAvg; + this.serverLateAvg = serverLateAvg; + this.transportEarlyAvg = transportEarlyAvg; + this.transportLateAvg = transportLateAvg; + } + } + + // [RequireComponent(typeof(NetworkStatistics))] <- needs to be on Network GO, not on NI + public class RemoteStatistics : NetworkBehaviour + { + // components ("fake statics" for similar API) + protected NetworkStatistics NetworkStatistics; + + // broadcast to client. + // stats are quite huge, let's only send every few seconds via TargetRpc. + // instead of sending multiple times per second via NB.OnSerialize. + [Tooltip("Send stats every 'interval' seconds to client.")] + public float sendInterval = 1; + double lastSendTime; + + [Header("GUI")] + public bool showGui; + public KeyCode hotKey = KeyCode.BackQuote; + Rect windowRect = new Rect(0, 0, 400, 400); + + // password can't be stored in code or in Unity project. + // it would be available in clients otherwise. + // this is not perfectly secure. that's why RemoteStatistics is read-only. + [Header("Authentication")] + public string passwordFile = "remote_statistics.txt"; + protected bool serverAuthenticated; // client needs to authenticate + protected bool clientAuthenticated; // show GUI until authenticated + protected string serverPassword = null; // null means not found, auth impossible + protected string clientPassword = ""; // for GUI + + // statistics synced to client + Stats stats; + + void LoadPassword() + { + // TODO only load once, not for all players? + // let's avoid static state for now. + + // load the password + string path = Path.GetFullPath(passwordFile); + if (File.Exists(path)) + { + // don't spam the server logs for every player's loaded file + // Debug.Log($"RemoteStatistics: loading password file: {path}"); + try + { + serverPassword = File.ReadAllText(path); + } + catch (Exception exception) + { + Debug.LogWarning($"RemoteStatistics: failed to read password file: {exception}"); + } + } + else + { + Debug.LogWarning($"RemoteStatistics: password file has not been created. Authentication will be impossible. Please save the password in: {path}"); + } + } + + protected override void OnValidate() + { + base.OnValidate(); + syncMode = SyncMode.Owner; + } + + // make sure to call base function when overwriting! + // public so it can also be called from tests (and be overwritten by users) + public override void OnStartServer() + { + NetworkStatistics = NetworkManager.singleton.GetComponent(); + if (NetworkStatistics == null) throw new Exception($"RemoteStatistics requires a NetworkStatistics component on {NetworkManager.singleton.name}!"); + + // server needs to load the password + LoadPassword(); + } + + public override void OnStartLocalPlayer() + { + // center the window initially + windowRect.x = Screen.width / 2 - windowRect.width / 2; + windowRect.y = Screen.height / 2 - windowRect.height / 2; + } + + [TargetRpc] + void TargetRpcSync(Stats v) + { + // store stats and flag as authenticated + clientAuthenticated = true; + stats = v; + } + + [Command] + public void CmdAuthenticate(string v) + { + // was a valid password loaded on the server, + // and did the client send the correct one? + if (!string.IsNullOrWhiteSpace(serverPassword) && + serverPassword.Equals(v)) + { + serverAuthenticated = true; + Debug.Log($"RemoteStatistics: connectionId {connectionToClient.connectionId} authenticated with player {name}"); + } + } + + void UpdateServer() + { + // only sync if client has authenticated on the server + if (!serverAuthenticated) return; + + // NetworkTime.localTime has defines for 2019 / 2020 compatibility + if (NetworkTime.localTime >= lastSendTime + sendInterval) + { + lastSendTime = NetworkTime.localTime; + + // target rpc to owner client + TargetRpcSync(new Stats( + // general + NetworkServer.connections.Count, + NetworkTime.time, + NetworkServer.tickRate, + NetworkServer.actualTickRate, + + // traffic + NetworkStatistics.serverSentBytesPerSecond, + NetworkStatistics.serverReceivedBytesPerSecond, + + // cpu + NetworkServer.tickInterval, + NetworkServer.fullUpdateDuration.average, + NetworkServer.earlyUpdateDuration.average, + NetworkServer.lateUpdateDuration.average, + 0, // TODO ServerTransport.earlyUpdateDuration.average, + 0 // TODO ServerTransport.lateUpdateDuration.average + )); + } + } + + void UpdateClient() + { + if (Input.GetKeyDown(hotKey)) + showGui = !showGui; + } + + void Update() + { + if (isServer) UpdateServer(); + if (isLocalPlayer) UpdateClient(); + } + + void OnGUI() + { + if (!isLocalPlayer) return; + if (!showGui) return; + + windowRect = GUILayout.Window(0, windowRect, OnWindow, "Remote Statistics"); + windowRect = Utils.KeepInScreen(windowRect); + } + + // Text: value + void GUILayout_TextAndValue(string text, string value) + { + GUILayout.BeginHorizontal(); + GUILayout.Label(text); + GUILayout.FlexibleSpace(); + GUILayout.Label(value); + GUILayout.EndHorizontal(); + } + + // fake a progress bar via horizontal scroll bar with ratio as width + void GUILayout_ProgressBar(double ratio, int width) + { + // clamp ratio, otherwise >1 would make it extremely large + ratio = Mathd.Clamp01(ratio); + GUILayout.HorizontalScrollbar(0, (float)ratio, 0, 1, GUILayout.Width(width)); + } + + // need to specify progress bar & caption width, + // otherwise differently sized captions would always misalign the + // progress bars. + void GUILayout_TextAndProgressBar(string text, double ratio, int progressbarWidth, string caption, int captionWidth, Color captionColor) + { + GUILayout.BeginHorizontal(); + GUILayout.Label(text); + GUILayout.FlexibleSpace(); + GUILayout_ProgressBar(ratio, progressbarWidth); + + // coloring the caption is enough. otherwise it's too much. + GUI.color = captionColor; + GUILayout.Label(caption, GUILayout.Width(captionWidth)); + GUI.color = Color.white; + + GUILayout.EndHorizontal(); + } + + void GUI_Authenticate() + { + GUILayout.BeginVertical("Box"); // start general + GUILayout.Label("Authentication"); + + // warning if insecure connection + // if (ClientTransport.IsEncrypted()) + // { + // GUILayout.Label("Connection is encrypted!"); + // } + // else + // { + GUILayout.Label("Connection is not encrypted. Use with care!"); + // } + + // input + clientPassword = GUILayout.PasswordField(clientPassword, '*'); + + // button + GUI.enabled = !string.IsNullOrWhiteSpace(clientPassword); + if (GUILayout.Button("Authenticate")) + { + CmdAuthenticate(clientPassword); + } + GUI.enabled = true; + + GUILayout.EndVertical(); // end general + } + + void GUI_General( + int connections, + double uptime, + int configuredTickRate, + int actualTickRate) + { + GUILayout.BeginVertical("Box"); // start general + GUILayout.Label("General"); + + // connections + GUILayout_TextAndValue("Connections:", $"{connections}"); + + // uptime + GUILayout_TextAndValue("Uptime:", $"{Utils.PrettySeconds(uptime)}"); // TODO + + // tick rate + // might be lower under heavy load. + // might be higher in editor if targetFrameRate can't be set. + GUI.color = actualTickRate < configuredTickRate ? Color.red : Color.green; + GUILayout_TextAndValue("Tick Rate:", $"{actualTickRate} Hz / {configuredTickRate} Hz"); + GUI.color = Color.white; + + GUILayout.EndVertical(); // end general + } + + void GUI_Traffic( + long serverSentBytesPerSecond, + long serverReceivedBytesPerSecond) + { + GUILayout.BeginVertical("Box"); + GUILayout.Label("Network"); + + GUILayout_TextAndValue("Outgoing:", $"{Utils.PrettyBytes(serverSentBytesPerSecond) }/s"); + GUILayout_TextAndValue("Incoming:", $"{Utils.PrettyBytes(serverReceivedBytesPerSecond)}/s"); + + GUILayout.EndVertical(); + } + + void GUI_Cpu( + float serverTickInterval, + double fullUpdateAvg, + double serverEarlyAvg, + double serverLateAvg, + double transportEarlyAvg, + double transportLateAvg) + { + const int barWidth = 120; + const int captionWidth = 90; + + GUILayout.BeginVertical("Box"); + GUILayout.Label("CPU"); + + // unity update + // happens every 'tickInterval'. progress bar shows it in relation. + // <= 90% load is green, otherwise red + double fullRatio = fullUpdateAvg / serverTickInterval; + GUILayout_TextAndProgressBar( + "World Update Avg:", + fullRatio, + barWidth, $"{fullUpdateAvg * 1000:F1} ms", + captionWidth, + fullRatio <= 0.9 ? Color.green : Color.red); + + // server update + // happens every 'tickInterval'. progress bar shows it in relation. + // <= 90% load is green, otherwise red + double serverRatio = (serverEarlyAvg + serverLateAvg) / serverTickInterval; + GUILayout_TextAndProgressBar( + "Server Update Avg:", + serverRatio, + barWidth, $"{serverEarlyAvg * 1000:F1} + {serverLateAvg * 1000:F1} ms", + captionWidth, + serverRatio <= 0.9 ? Color.green : Color.red); + + // transport: early + late update milliseconds. + // for threaded transport, this is the thread's update time. + // happens every 'tickInterval'. progress bar shows it in relation. + // <= 90% load is green, otherwise red + // double transportRatio = (transportEarlyAvg + transportLateAvg) / serverTickInterval; + // GUILayout_TextAndProgressBar( + // "Transport Avg:", + // transportRatio, + // barWidth, + // $"{transportEarlyAvg * 1000:F1} + {transportLateAvg * 1000:F1} ms", + // captionWidth, + // transportRatio <= 0.9 ? Color.green : Color.red); + + GUILayout.EndVertical(); + } + + void GUI_Notice() + { + // for security reasons, let's keep this read-only for now. + + // single line keeps input & visuals simple + // GUILayout.BeginVertical("Box"); + // GUILayout.Label("Global Notice"); + // notice = GUILayout.TextField(notice); + // if (GUILayout.Button("Send")) + // { + // // TODO + // } + // GUILayout.EndVertical(); + } + + void OnWindow(int windowID) + { + if (!clientAuthenticated) + { + GUI_Authenticate(); + } + else + { + GUI_General( + stats.connections, + stats.uptime, + stats.configuredTickRate, + stats.actualTickRate + ); + + GUI_Traffic( + stats.sentBytesPerSecond, + stats.receiveBytesPerSecond + ); + + GUI_Cpu( + stats.serverTickInterval, + stats.fullUpdateAvg, + stats.serverEarlyAvg, + stats.serverLateAvg, + stats.transportEarlyAvg, + stats.transportLateAvg + ); + + GUI_Notice(); + } + + // dragable window in any case + GUI.DragWindow(new Rect(0, 0, 10000, 10000)); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Components/RemoteStatistics.cs.meta b/Assets/ImportedAssets/Mirror/Components/RemoteStatistics.cs.meta new file mode 100644 index 0000000000..1371d9dceb --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Components/RemoteStatistics.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ba360e4ff6b44fc6898f56322b90c6c8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Components/RemoteStatistics.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Runtime.meta b/Assets/ImportedAssets/Mirror/Core.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime.meta rename to Assets/ImportedAssets/Mirror/Core.meta diff --git a/Assets/ImportedAssets/Mirror/Core/AssemblyInfo.cs b/Assets/ImportedAssets/Mirror/Core/AssemblyInfo.cs new file mode 100644 index 0000000000..a9c64421bd --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/AssemblyInfo.cs @@ -0,0 +1,13 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Mirror.Tests.Common")] +[assembly: InternalsVisibleTo("Mirror.Tests")] +// need to use Unity.*.CodeGen assembly name to import Unity.CompilationPipeline +// for ILPostProcessor tests. +[assembly: InternalsVisibleTo("Unity.Mirror.Tests.CodeGen")] +[assembly: InternalsVisibleTo("Mirror.Tests.Generated")] +[assembly: InternalsVisibleTo("Mirror.Tests.Runtime")] +[assembly: InternalsVisibleTo("Mirror.Tests.Performance.Editor")] +[assembly: InternalsVisibleTo("Mirror.Tests.Performance.Runtime")] +[assembly: InternalsVisibleTo("Mirror.Editor")] +[assembly: InternalsVisibleTo("Mirror.Components")] diff --git a/Assets/ImportedAssets/Mirror/Core/AssemblyInfo.cs.meta b/Assets/ImportedAssets/Mirror/Core/AssemblyInfo.cs.meta new file mode 100644 index 0000000000..3827b61f05 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/AssemblyInfo.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: e28d5f410e25b42e6a76a2ffc10e4675 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/AssemblyInfo.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Attributes.cs b/Assets/ImportedAssets/Mirror/Core/Attributes.cs new file mode 100644 index 0000000000..0aebfbabe6 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Attributes.cs @@ -0,0 +1,95 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + /// + /// SyncVars are used to automatically synchronize a variable between the server and all clients. The direction of synchronization depends on the Sync Direction property, ServerToClient by default. + /// + /// When Sync Direction is equal to ServerToClient, the value should be changed on the server side and synchronized to all clients. + /// Otherwise, the value should be changed on the client side and synchronized to server and other clients. + /// + /// Hook parameter allows you to define a method to be invoked when gets an value update. Notice that the hook method will not be called on the change side. + /// + [AttributeUsage(AttributeTargets.Field)] + public class SyncVarAttribute : PropertyAttribute + { + public string hook; + } + + /// + /// Call this from a client to run this function on the server. + /// Make sure to validate input etc. It's not possible to call this from a server. + /// + [AttributeUsage(AttributeTargets.Method)] + public class CommandAttribute : Attribute + { + public int channel = Channels.Reliable; + public bool requiresAuthority = true; + } + + /// + /// The server uses a Remote Procedure Call (RPC) to run this function on clients. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ClientRpcAttribute : Attribute + { + public int channel = Channels.Reliable; + public bool includeOwner = true; + } + + /// + /// The server uses a Remote Procedure Call (RPC) to run this function on a specific client. + /// + [AttributeUsage(AttributeTargets.Method)] + public class TargetRpcAttribute : Attribute + { + public int channel = Channels.Reliable; + } + + /// + /// Prevents clients from running this method. + /// Prints a warning if a client tries to execute this method. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ServerAttribute : Attribute {} + + /// + /// Prevents clients from running this method. + /// No warning is thrown. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ServerCallbackAttribute : Attribute {} + + /// + /// Prevents the server from running this method. + /// Prints a warning if the server tries to execute this method. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ClientAttribute : Attribute {} + + /// + /// Prevents the server from running this method. + /// No warning is printed. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ClientCallbackAttribute : Attribute {} + + /// + /// Converts a string property into a Scene property in the inspector + /// + public class SceneAttribute : PropertyAttribute {} + + /// + /// Used to show private SyncList in the inspector, + /// Use instead of SerializeField for non Serializable types + /// + [AttributeUsage(AttributeTargets.Field)] + public class ShowInInspectorAttribute : Attribute {} + + /// + /// Used to make a field readonly in the inspector + /// + [AttributeUsage(AttributeTargets.Field)] + public class ReadOnlyAttribute : PropertyAttribute {} +} diff --git a/Assets/ImportedAssets/Mirror/Core/Attributes.cs.meta b/Assets/ImportedAssets/Mirror/Core/Attributes.cs.meta new file mode 100644 index 0000000000..ab715ddad8 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Attributes.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: c04c722ee2ffd49c8a56ab33667b10b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Attributes.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Batching.meta b/Assets/ImportedAssets/Mirror/Core/Batching.meta new file mode 100644 index 0000000000..bf23600c51 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Batching.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1c38e1bebe9947f8b842a8a57aa2b71c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Batching/Batcher.cs b/Assets/ImportedAssets/Mirror/Core/Batching/Batcher.cs new file mode 100644 index 0000000000..41f467dbf4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Batching/Batcher.cs @@ -0,0 +1,167 @@ +// batching functionality encapsulated into one class. +// -> less complexity +// -> easy to test +// +// IMPORTANT: we use THRESHOLD batching, not MAXED SIZE batching. +// see threshold comments below. +// +// includes timestamp for tick batching. +// -> allows NetworkTransform etc. to use timestamp without including it in +// every single message +using System; +using System.Collections.Generic; + +namespace Mirror +{ + public class Batcher + { + // batching threshold instead of max size. + // -> small messages are fit into threshold sized batches + // -> messages larger than threshold are single batches + // + // in other words, we fit up to 'threshold' but still allow larger ones + // for two reasons: + // 1.) data races: skipping batching for larger messages would send a + // large spawn message immediately, while others are batched and + // only flushed at the end of the frame + // 2) timestamp batching: if each batch is expected to contain a + // timestamp, then large messages have to be a batch too. otherwise + // they would not contain a timestamp + readonly int threshold; + + // TimeStamp header size. each batch has one. + public const int TimestampSize = sizeof(double); + + // Message header size. each message has one. + public static int MessageHeaderSize(int messageSize) => + Compression.VarUIntSize((ulong)messageSize); + + // maximum overhead for a single message. + // useful for the outside to calculate max message sizes. + public static int MaxMessageOverhead(int messageSize) => + TimestampSize + MessageHeaderSize(messageSize); + + // full batches ready to be sent. + // DO NOT queue NetworkMessage, it would box. + // DO NOT queue each serialization separately. + // it would allocate too many writers. + // https://github.com/vis2k/Mirror/pull/3127 + // => best to build batches on the fly. + readonly Queue batches = new Queue(); + + // current batch in progress + NetworkWriterPooled batch; + + public Batcher(int threshold) + { + this.threshold = threshold; + } + + // add a message for batching + // we allow any sized messages. + // caller needs to make sure they are within max packet size. + public void AddMessage(ArraySegment message, double timeStamp) + { + // predict the needed size, which is varint(size) + content + int headerSize = Compression.VarUIntSize((ulong)message.Count); + int neededSize = headerSize + message.Count; + + // when appending to a batch in progress, check final size. + // if it expands beyond threshold, then we should finalize it first. + // => less than or exactly threshold is fine. + // GetBatch() will finalize it. + // => see unit tests. + if (batch != null && + batch.Position + neededSize > threshold) + { + batches.Enqueue(batch); + batch = null; + } + + // initialize a new batch if necessary + if (batch == null) + { + // borrow from pool. we return it in GetBatch. + batch = NetworkWriterPool.Get(); + + // write timestamp first. + // -> double precision for accuracy over long periods of time + // -> batches are per-frame, it doesn't matter which message's + // timestamp we use. + batch.WriteDouble(timeStamp); + } + + // add serialization to current batch. even if > threshold. + // -> we do allow > threshold sized messages as single batch + // -> WriteBytes instead of WriteSegment because the latter + // would add a size header. we want to write directly. + // + // include size prefix as varint! + // -> fixes NetworkMessage serialization mismatch corrupting the + // next message in a batch. + // -> a _lot_ of time was wasted debugging corrupt batches. + // no easy way to figure out which NetworkMessage has a mismatch. + // -> this is worth everyone's sanity. + // -> varint means we prefix with 1 byte most of the time. + // -> the same issue in NetworkIdentity was why Mirror started! + Compression.CompressVarUInt(batch, (ulong)message.Count); + batch.WriteBytes(message.Array, message.Offset, message.Count); + } + + // helper function to copy a batch to writer and return it to pool + static void CopyAndReturn(NetworkWriterPooled batch, NetworkWriter writer) + { + // make sure the writer is fresh to avoid uncertain situations + if (writer.Position != 0) + throw new ArgumentException($"GetBatch needs a fresh writer!"); + + // copy to the target writer + ArraySegment segment = batch.ToArraySegment(); + writer.WriteBytes(segment.Array, segment.Offset, segment.Count); + + // return batch to pool for reuse + NetworkWriterPool.Return(batch); + } + + // get the next batch which is available for sending (if any). + // TODO safely get & return a batch instead of copying to writer? + // TODO could return pooled writer & use GetBatch in a 'using' statement! + public bool GetBatch(NetworkWriter writer) + { + // get first batch from queue (if any) + if (batches.TryDequeue(out NetworkWriterPooled first)) + { + CopyAndReturn(first, writer); + return true; + } + + // if queue was empty, we can send the batch in progress. + if (batch != null) + { + CopyAndReturn(batch, writer); + batch = null; + return true; + } + + // nothing was written + return false; + } + + // return all batches to the pool for cleanup + public void Clear() + { + // return batch in progress + if (batch != null) + { + NetworkWriterPool.Return(batch); + batch = null; + } + + // return all queued batches + foreach (NetworkWriterPooled queued in batches) + NetworkWriterPool.Return(queued); + + batches.Clear(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Batching/Batcher.cs.meta b/Assets/ImportedAssets/Mirror/Core/Batching/Batcher.cs.meta new file mode 100644 index 0000000000..f876204e56 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Batching/Batcher.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 0afaaa611a2142d48a07bdd03b68b2b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Batching/Batcher.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Batching/Unbatcher.cs b/Assets/ImportedAssets/Mirror/Core/Batching/Unbatcher.cs new file mode 100644 index 0000000000..6b2c405ad4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Batching/Unbatcher.cs @@ -0,0 +1,129 @@ +// un-batching functionality encapsulated into one class. +// -> less complexity +// -> easy to test +// +// includes timestamp for tick batching. +// -> allows NetworkTransform etc. to use timestamp without including it in +// every single message +using System; +using System.Collections.Generic; + +namespace Mirror +{ + public class Unbatcher + { + // supporting adding multiple batches before GetNextMessage is called. + // just in case. + readonly Queue batches = new Queue(); + + public int BatchesCount => batches.Count; + + // NetworkReader is only created once, + // then pointed to the first batch. + readonly NetworkReader reader = new NetworkReader(new byte[0]); + + // timestamp that was written into the batch remotely. + // for the batch that our reader is currently pointed at. + double readerRemoteTimeStamp; + + // helper function to start reading a batch. + void StartReadingBatch(NetworkWriterPooled batch) + { + // point reader to it + reader.SetBuffer(batch.ToArraySegment()); + + // read remote timestamp (double) + // -> AddBatch quarantees that we have at least 8 bytes to read + readerRemoteTimeStamp = reader.ReadDouble(); + } + + // add a new batch. + // returns true if valid. + // returns false if not, in which case the connection should be disconnected. + public bool AddBatch(ArraySegment batch) + { + // IMPORTANT: ArraySegment is only valid until returning. we copy it! + // + // NOTE: it's not possible to create empty ArraySegments, so we + // don't need to check against that. + + // make sure we have at least 8 bytes to read for tick timestamp + if (batch.Count < Batcher.TimestampSize) + return false; + + // put into a (pooled) writer + // -> WriteBytes instead of WriteSegment because the latter + // would add a size header. we want to write directly. + // -> will be returned to pool when sending! + NetworkWriterPooled writer = NetworkWriterPool.Get(); + writer.WriteBytes(batch.Array, batch.Offset, batch.Count); + + // first batch? then point reader there + if (batches.Count == 0) + StartReadingBatch(writer); + + // add batch + batches.Enqueue(writer); + //Debug.Log($"Adding Batch {BitConverter.ToString(batch.Array, batch.Offset, batch.Count)} => batches={batches.Count} reader={reader}"); + return true; + } + + // get next message, unpacked from batch (if any) + // message ArraySegment is only valid until the next call. + // timestamp is the REMOTE time when the batch was created remotely. + public bool GetNextMessage(out ArraySegment message, out double remoteTimeStamp) + { + message = default; + remoteTimeStamp = 0; + + // do nothing if we don't have any batches. + // otherwise the below queue.Dequeue() would throw an + // InvalidOperationException if operating on empty queue. + if (batches.Count == 0) + return false; + + // was our reader pointed to anything yet? + if (reader.Capacity == 0) + return false; + + // no more data to read? + if (reader.Remaining == 0) + { + // retire the batch + NetworkWriterPooled writer = batches.Dequeue(); + NetworkWriterPool.Return(writer); + + // do we have another batch? + if (batches.Count > 0) + { + // point reader to the next batch. + // we'll return the reader below. + NetworkWriterPooled next = batches.Peek(); + StartReadingBatch(next); + } + // otherwise there's nothing more to read + else return false; + } + + // use the current batch's remote timestamp + // AFTER potentially moving to the next batch ABOVE! + remoteTimeStamp = readerRemoteTimeStamp; + + // enough data to read the size prefix? + if (reader.Remaining == 0) + return false; + + // read the size prefix as varint + // see Batcher.AddMessage comments for explanation. + int size = (int)Compression.DecompressVarUInt(reader); + + // validate size prefix, in case attackers send malicious data + if (reader.Remaining < size) + return false; + + // return the message of size + message = reader.ReadBytesSegment(size); + return true; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Batching/Unbatcher.cs.meta b/Assets/ImportedAssets/Mirror/Core/Batching/Unbatcher.cs.meta new file mode 100644 index 0000000000..b74a2c2283 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Batching/Unbatcher.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 328562d71e1c45c58581b958845aa7a4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Batching/Unbatcher.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/ConnectionQuality.cs b/Assets/ImportedAssets/Mirror/Core/ConnectionQuality.cs new file mode 100644 index 0000000000..ee0720a20b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/ConnectionQuality.cs @@ -0,0 +1,74 @@ +// standalone, Unity-independent connection-quality algorithm & enum. +// don't need to use this directly, it's built into Mirror's NetworkClient. +using UnityEngine; + +namespace Mirror +{ + public enum ConnectionQuality : byte + { + ESTIMATING, // still estimating + POOR, // unplayable + FAIR, // very noticeable latency, not very enjoyable anymore + GOOD, // very playable for everyone but high level competitors + EXCELLENT // ideal experience for high level competitors + } + + public enum ConnectionQualityMethod : byte + { + Simple, // simple estimation based on rtt and jitter + Pragmatic // based on snapshot interpolation adjustment + } + + // provide different heuristics for users to choose from. + // simple heuristics to get started. + // this will be iterated on over time based on user feedback. + public static class ConnectionQualityHeuristics + { + // convenience extension to color code Connection Quality + public static Color ColorCode(this ConnectionQuality quality) + { + switch (quality) + { + case ConnectionQuality.POOR: return Color.red; + case ConnectionQuality.FAIR: return new Color(1.0f, 0.647f, 0.0f); + case ConnectionQuality.GOOD: return Color.yellow; + case ConnectionQuality.EXCELLENT: return Color.green; + default: return Color.gray; // ESTIMATING + } + } + + // straight forward estimation + // rtt: average round trip time in seconds. + // jitter: average latency variance. + public static ConnectionQuality Simple(double rtt, double jitter) + { + if (rtt <= 0.100 && jitter <= 0.10) return ConnectionQuality.EXCELLENT; + if (rtt <= 0.200 && jitter <= 0.20) return ConnectionQuality.GOOD; + if (rtt <= 0.400 && jitter <= 0.50) return ConnectionQuality.FAIR; + return ConnectionQuality.POOR; + } + + // snapshot interpolation based estimation. + // snap. interp. adjusts buffer time based on connection quality. + // based on this, we can measure how far away we are from the ideal. + // the returned quality will always directly correlate with gameplay. + // => requires SnapshotInterpolation dynamicAdjustment to be enabled! + public static ConnectionQuality Pragmatic(double targetBufferTime, double currentBufferTime) + { + // buffer time is set by the game developer. + // estimating in multiples is a great way to be game independent. + // for example, a fast paced shooter and a slow paced RTS will both + // have poor connection if the multiplier is >10. + double multiplier = currentBufferTime / targetBufferTime; + + // empirically measured with Tanks demo + LatencySimulation. + // it's not obvious to estimate on paper. + if (multiplier <= 1.15) return ConnectionQuality.EXCELLENT; + if (multiplier <= 1.25) return ConnectionQuality.GOOD; + if (multiplier <= 1.50) return ConnectionQuality.FAIR; + + // anything else is poor + return ConnectionQuality.POOR; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/ConnectionQuality.cs.meta b/Assets/ImportedAssets/Mirror/Core/ConnectionQuality.cs.meta new file mode 100644 index 0000000000..8bee8cb5ce --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/ConnectionQuality.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ff663b880e33e4606b545c8b497041c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/ConnectionQuality.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty.meta b/Assets/ImportedAssets/Mirror/Core/Empty.meta new file mode 100644 index 0000000000..e7024022aa --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a99666a026b14cf6ba1a2b65946b1b27 +timeCreated: 1615288671 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/ClientScene.cs b/Assets/ImportedAssets/Mirror/Core/Empty/ClientScene.cs new file mode 100644 index 0000000000..0d1b96e78c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/ClientScene.cs @@ -0,0 +1 @@ +// moved into NetworkClient on 2021-03-07 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/ClientScene.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/ClientScene.cs.meta new file mode 100644 index 0000000000..82b617e3ac --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/ClientScene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96fc7967f813e4960b9119d7c2118494 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Cloud.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiConnector.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiConnector.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiConnector.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/ApiConnector.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiConnector.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/ApiConnector.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiConnector.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiUpdater.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiUpdater.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiUpdater.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiUpdater.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiUpdater.cs.meta new file mode 100644 index 0000000000..98a4c110c8 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ApiUpdater.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f6e5d5acb5879f45a2235ae0f44dc92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Ball.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Ball.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Ball.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Ball.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Ball.cs.meta new file mode 100644 index 0000000000..a6fc272404 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Ball.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4e9cc0829b13e54594a80883836bda7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BallManager.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BallManager.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BallManager.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BallManager.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BallManager.cs.meta new file mode 100644 index 0000000000..b914a33ebe --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BallManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9cc796972dc396a42ba3686bd952e329 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BaseApi.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BaseApi.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BaseApi.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/BaseApi.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BaseApi.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/Core/BaseApi.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/BaseApi.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Events.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Events.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Events.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/Events.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Events.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/Core/Events.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Events.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Extensions.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Extensions.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Extensions.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/Extensions.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Extensions.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/Core/Extensions.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Extensions.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/ICoroutineRunner.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/Core/ICoroutineRunner.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IRequestCreator.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IRequestCreator.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IRequestCreator.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/IRequestCreator.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IRequestCreator.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/Core/IRequestCreator.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IRequestCreator.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/IUnityEqualCheck.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/Core/IUnityEqualCheck.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs.meta new file mode 100644 index 0000000000..4b7219bee0 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dbabb497385c20346a3c8bda4ae69508 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/JsonStructs.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/JsonStructs.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/JsonStructs.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/JsonStructs.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/JsonStructs.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/Core/JsonStructs.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/JsonStructs.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServer.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServer.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServer.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServer.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServer.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServer.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServer.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerBaseApi.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerBaseApi.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerClientApi.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerClientApi.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerJson.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerJson.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerJson.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerJson.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerJson.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerJson.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerJson.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerServerApi.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/ListServer/ListServerServerApi.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Logger.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Logger.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Logger.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/Logger.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Logger.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/Core/Logger.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Logger.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs.meta new file mode 100644 index 0000000000..86775dfdee --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 95bebb8e810e2954485291a26324f7d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs.meta new file mode 100644 index 0000000000..5c4294f739 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 068feff770f710141afa4a90063a5e6c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Player.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Player.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Player.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Player.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Player.cs.meta new file mode 100644 index 0000000000..1c8582810d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/Player.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b6cfd54b79bb464dbc6ae7f331ed45f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs.meta new file mode 100644 index 0000000000..4a2256546c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 07d1ea5260bc06e4d831c4b61d494bff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs.meta new file mode 100644 index 0000000000..67341ea81d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 76dab753e7255254687cd57985d8d675 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/RequestCreator.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/RequestCreator.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/RequestCreator.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Cloud/Core/RequestCreator.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/RequestCreator.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Cloud/Core/RequestCreator.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Cloud/RequestCreator.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListManager.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListManager.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListManager.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListManager.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListManager.cs.meta new file mode 100644 index 0000000000..74c6a0f219 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bfc354d4a7f63ca45a653bf5d479afa0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUI.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUI.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUI.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUI.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUI.cs.meta new file mode 100644 index 0000000000..f7fe4f2e62 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed11184fcffcdc04c9850d82c8014926 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs new file mode 100644 index 0000000000..2f11787775 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs.meta new file mode 100644 index 0000000000..d8857e805b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c67eda1b451338a428df87fda1e3a7c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/DotNetCompatibility.cs b/Assets/ImportedAssets/Mirror/Core/Empty/DotNetCompatibility.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/DotNetCompatibility.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Runtime/DotNetCompatibility.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/DotNetCompatibility.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/DotNetCompatibility.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/DotNetCompatibility.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/FallbackTransport.cs b/Assets/ImportedAssets/Mirror/Core/Empty/FallbackTransport.cs new file mode 100644 index 0000000000..57f3344b75 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/FallbackTransport.cs @@ -0,0 +1 @@ +// removed 2021-05-13 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Runtime/Transport/FallbackTransport.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/FallbackTransport.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/Transport/FallbackTransport.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/FallbackTransport.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/LogFactory.cs b/Assets/ImportedAssets/Mirror/Core/Empty/LogFactory.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/LogFactory.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Runtime/LogFactory.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/LogFactory.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/LogFactory.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/LogFactory.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/LogFilter.cs b/Assets/ImportedAssets/Mirror/Core/Empty/LogFilter.cs new file mode 100644 index 0000000000..391c5bdbf5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/LogFilter.cs @@ -0,0 +1 @@ +// removed 2021-03-08 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/LogFilter.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/LogFilter.cs.meta new file mode 100644 index 0000000000..aab4fa0027 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/LogFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f6928b080072948f7b2909b4025fcc79 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Runtime/Logging.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Logging.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/Logging.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Logging.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Runtime/Logging/ConsoleColorLogHandler.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/Logging/ConsoleColorLogHandler.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Runtime/Logging/EditorLogSettingsLoader.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/Logging/EditorLogSettingsLoader.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogFactory.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogFactory.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogFactory.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Runtime/Logging/LogFactory.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogFactory.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/Logging/LogFactory.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogFactory.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogSettings.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogSettings.cs new file mode 100644 index 0000000000..264a1cda7f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogSettings.cs @@ -0,0 +1,2 @@ +// removed 2021-02-16 + diff --git a/Assets/ImportedAssets/Mirror/Runtime/Logging/LogSettings.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogSettings.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/Logging/LogSettings.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Logging/LogSettings.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Runtime/Logging/NetworkHeadlessLogger.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/Logging/NetworkHeadlessLogger.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Runtime/Logging/NetworkLogSettings.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/Logging/NetworkLogSettings.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/NetworkMatchChecker.cs b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkMatchChecker.cs new file mode 100644 index 0000000000..379762020b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkMatchChecker.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkMatchChecker.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkMatchChecker.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Components/NetworkMatchChecker.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/NetworkMatchChecker.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/NetworkOwnerChecker.cs b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkOwnerChecker.cs new file mode 100644 index 0000000000..712833c94f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkOwnerChecker.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/NetworkOwnerChecker.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkOwnerChecker.cs.meta new file mode 100644 index 0000000000..fee7725c8c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkOwnerChecker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 25fd0c51bbe07c140bc30978b91e9182 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/NetworkProximityChecker.cs b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkProximityChecker.cs new file mode 100644 index 0000000000..379762020b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkProximityChecker.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkProximityChecker.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkProximityChecker.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Components/NetworkProximityChecker.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/NetworkProximityChecker.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/NetworkSceneChecker.cs b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkSceneChecker.cs new file mode 100644 index 0000000000..379762020b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkSceneChecker.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkSceneChecker.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkSceneChecker.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Components/NetworkSceneChecker.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/NetworkSceneChecker.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/NetworkTransformBase.cs b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkTransformBase.cs new file mode 100644 index 0000000000..79e858f62f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkTransformBase.cs @@ -0,0 +1 @@ +// removed 2022-10-24 diff --git a/Assets/ImportedAssets/Mirror/Components/NetworkTransformBase.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkTransformBase.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Components/NetworkTransformBase.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/NetworkTransformBase.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/NetworkVisibility.cs b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkVisibility.cs new file mode 100644 index 0000000000..379762020b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkVisibility.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/NetworkVisibility.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkVisibility.cs.meta new file mode 100644 index 0000000000..f71b7bed8d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/NetworkVisibility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c08f1a030234d49d391d7223a8592f15 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/StringHash.cs b/Assets/ImportedAssets/Mirror/Core/Empty/StringHash.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/StringHash.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Runtime/StringHash.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/StringHash.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Runtime/StringHash.cs.meta rename to Assets/ImportedAssets/Mirror/Core/Empty/StringHash.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/SyncVar.cs b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVar.cs new file mode 100644 index 0000000000..aaa3b9d67a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVar.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/SyncVar.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVar.cs.meta new file mode 100644 index 0000000000..fffb472cc4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVar.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e87cb681af8459fbbb1f467e1c7632c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarGameObject.cs b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarGameObject.cs new file mode 100644 index 0000000000..aaa3b9d67a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarGameObject.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarGameObject.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarGameObject.cs.meta new file mode 100644 index 0000000000..4e924f098f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarGameObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 84da90dae05442e3a149753c9b25ae98 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs new file mode 100644 index 0000000000..aaa3b9d67a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs.meta new file mode 100644 index 0000000000..0ceab50587 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c0fff77f1a624ba8ad6e4bdef6c14a8b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs new file mode 100644 index 0000000000..aaa3b9d67a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs.meta b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs.meta new file mode 100644 index 0000000000..53271d4305 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f9a6d4d2741477999ad9588261870fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/HostMode.cs b/Assets/ImportedAssets/Mirror/Core/HostMode.cs new file mode 100644 index 0000000000..3054b3c826 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/HostMode.cs @@ -0,0 +1,44 @@ +// host mode related helper functions. +// usually they set up both server & client. +// it's cleaner to keep them in one place, instead of only in server / client. +using System; + +namespace Mirror +{ + public static class HostMode + { + // keep the local connections setup in one function. + // makes host setup easier to follow. + internal static void SetupConnections() + { + // create local connections pair, both are connected + Utils.CreateLocalConnections( + out LocalConnectionToClient connectionToClient, + out LocalConnectionToServer connectionToServer); + + // set client connection + NetworkClient.connection = connectionToServer; + + // set server connection + NetworkServer.SetLocalConnection(connectionToClient); + } + + // call OnConnected on server & client. + // public because NetworkClient.ConnectLocalServer was public before too. + public static void InvokeOnConnected() + { + // call server OnConnected with server's connection to client + NetworkServer.OnConnected(NetworkServer.localConnection); + + // call client OnConnected with client's connection to server + // => previously we used to send a ConnectMessage to + // NetworkServer.localConnection. this would queue the message + // until NetworkClient.Update processes it. + // => invoking the client's OnConnected event directly here makes + // tests fail. so let's do it exactly the same order as before by + // queueing the event for next Update! + //OnConnectedEvent?.Invoke(connection); + ((LocalConnectionToServer)NetworkClient.connection).QueueConnectedEvent(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/HostMode.cs.meta b/Assets/ImportedAssets/Mirror/Core/HostMode.cs.meta new file mode 100644 index 0000000000..32b1f281c3 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/HostMode.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: d27175a08d5341fc97645b49ee533d5a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/HostMode.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/InterestManagement.cs b/Assets/ImportedAssets/Mirror/Core/InterestManagement.cs new file mode 100644 index 0000000000..88ead0ffb4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/InterestManagement.cs @@ -0,0 +1,146 @@ +// interest management component for custom solutions like +// distance based, spatial hashing, raycast based, etc. + +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public abstract class InterestManagement : InterestManagementBase + { + // allocate newObservers helper HashSet + readonly HashSet newObservers = + new HashSet(); + + // rebuild observers for the given NetworkIdentity. + // Server will automatically spawn/despawn added/removed ones. + // newObservers: cached hashset to put the result into + // initialize: true if being rebuilt for the first time + // + // IMPORTANT: + // => global rebuild would be more simple, BUT + // => local rebuild is way faster for spawn/despawn because we can + // simply rebuild a select NetworkIdentity only + // => having both .observers and .observing is necessary for local + // rebuilds + // + // in other words, this is the perfect solution even though it's not + // completely simple (due to .observers & .observing). + // + // Mirror maintains .observing automatically in the background. best of + // both worlds without any worrying now! + public abstract void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers); + + // helper function to trigger a full rebuild. + // most implementations should call this in a certain interval. + // some might call this all the time, or only on team changes or + // scene changes and so on. + // + // IMPORTANT: check if NetworkServer.active when using Update()! + [ServerCallback] + protected void RebuildAll() + { + foreach (NetworkIdentity identity in NetworkServer.spawned.Values) + { + NetworkServer.RebuildObservers(identity, false); + } + } + + public override void Rebuild(NetworkIdentity identity, bool initialize) + { + // clear newObservers hashset before using it + newObservers.Clear(); + + // not force hidden? + if (identity.visibility != Visibility.ForceHidden) + { + OnRebuildObservers(identity, newObservers); + } + + // IMPORTANT: AFTER rebuilding add own player connection in any case + // to ensure player always sees himself no matter what. + // -> OnRebuildObservers might clear observers, so we need to add + // the player's own connection AFTER. 100% fail safe. + // -> fixes https://github.com/vis2k/Mirror/issues/692 where a + // player might teleport out of the ProximityChecker's cast, + // losing the own connection as observer. + if (identity.connectionToClient != null) + { + newObservers.Add(identity.connectionToClient); + } + + bool changed = false; + + // add all newObservers that aren't in .observers yet + foreach (NetworkConnectionToClient conn in newObservers) + { + // only add ready connections. + // otherwise the player might not be in the world yet or anymore + if (conn != null && conn.isReady) + { + if (initialize || !identity.observers.ContainsKey(conn.connectionId)) + { + // new observer + conn.AddToObserving(identity); + // Debug.Log($"New Observer for {gameObject} {conn}"); + changed = true; + } + } + } + + // remove all old .observers that aren't in newObservers anymore + foreach (NetworkConnectionToClient conn in identity.observers.Values) + { + if (!newObservers.Contains(conn)) + { + // removed observer + conn.RemoveFromObserving(identity, false); + // Debug.Log($"Removed Observer for {gameObject} {conn}"); + changed = true; + } + } + + // copy new observers to observers + if (changed) + { + identity.observers.Clear(); + foreach (NetworkConnectionToClient conn in newObservers) + { + if (conn != null && conn.isReady) + identity.observers.Add(conn.connectionId, conn); + } + } + + // special case for host mode: we use SetHostVisibility to hide + // NetworkIdentities that aren't in observer range from host. + // this is what games like Dota/Counter-Strike do too, where a host + // does NOT see all players by default. they are in memory, but + // hidden to the host player. + // + // this code is from UNET, it's a bit strange but it works: + // * it hides newly connected identities in host mode + // => that part was the intended behaviour + // * it hides ALL NetworkIdentities in host mode when the host + // connects but hasn't selected a character yet + // => this only works because we have no .localConnection != null + // check. at this stage, localConnection is null because + // StartHost starts the server first, then calls this code, + // then starts the client and sets .localConnection. so we can + // NOT add a null check without breaking host visibility here. + // * it hides ALL NetworkIdentities in server-only mode because + // observers never contain the 'null' .localConnection + // => that was not intended, but let's keep it as it is so we + // don't break anything in host mode. it's way easier than + // iterating all identities in a special function in StartHost. + if (initialize) + { + if (!newObservers.Contains(NetworkServer.localConnection)) + { + SetHostVisibility(identity, false); + } + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/InterestManagement.cs.meta b/Assets/ImportedAssets/Mirror/Core/InterestManagement.cs.meta new file mode 100644 index 0000000000..fe957ca87b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/InterestManagement.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 41d809934003479f97e992eebb7ed6af +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/InterestManagement.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/InterestManagementBase.cs b/Assets/ImportedAssets/Mirror/Core/InterestManagementBase.cs new file mode 100644 index 0000000000..ec60d640e8 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/InterestManagementBase.cs @@ -0,0 +1,77 @@ +// interest management component for custom solutions like +// distance based, spatial hashing, raycast based, etc. +// low level base class allows for low level spatial hashing etc., which is 3-5x faster. +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public abstract class InterestManagementBase : MonoBehaviour + { + // initialize NetworkServer/Client .aoi. + // previously we did this in Awake(), but that's called for disabled + // components too. if we do it OnEnable(), then it's not set for + // disabled components. + protected virtual void OnEnable() + { + // do not check if == null or error if already set. + // users may enabled/disable components randomly, + // causing this to be called multiple times. + NetworkServer.aoi = this; + NetworkClient.aoi = this; + } + + [ServerCallback] + public virtual void ResetState() {} + + // Callback used by the visibility system to determine if an observer + // (player) can see the NetworkIdentity. If this function returns true, + // the network connection will be added as an observer. + // conn: Network connection of a player. + // returns True if the player can see this object. + public abstract bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver); + + + // Callback used by the visibility system for objects on a host. + // Objects on a host (with a local client) cannot be disabled or + // destroyed when they are not visible to the local client. So this + // function is called to allow custom code to hide these objects. A + // typical implementation will disable renderer components on the + // object. This is only called on local clients on a host. + // => need the function in here and virtual so people can overwrite! + // => not everyone wants to hide renderers! + [ServerCallback] + public virtual void SetHostVisibility(NetworkIdentity identity, bool visible) + { + foreach (Renderer rend in identity.GetComponentsInChildren()) + rend.enabled = visible; + } + + /// Called on the server when a new networked object is spawned. + // (useful for 'only rebuild if changed' interest management algorithms) + [ServerCallback] + public virtual void OnSpawned(NetworkIdentity identity) {} + + /// Called on the server when a networked object is destroyed. + // (useful for 'only rebuild if changed' interest management algorithms) + [ServerCallback] + public virtual void OnDestroyed(NetworkIdentity identity) {} + + public abstract void Rebuild(NetworkIdentity identity, bool initialize); + + /// Adds the specified connection to the observers of identity + protected void AddObserver(NetworkConnectionToClient connection, NetworkIdentity identity) + { + connection.AddToObserving(identity); + identity.observers.Add(connection.connectionId, connection); + } + + /// Removes the specified connection from the observers of identity + protected void RemoveObserver(NetworkConnectionToClient connection, NetworkIdentity identity) + { + connection.RemoveFromObserving(identity, false); + identity.observers.Remove(connection.connectionId); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/InterestManagementBase.cs.meta b/Assets/ImportedAssets/Mirror/Core/InterestManagementBase.cs.meta new file mode 100644 index 0000000000..1446332ed2 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/InterestManagementBase.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 18bd2ffe65a444f3b13d59bdac7f2228 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/InterestManagementBase.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation.meta b/Assets/ImportedAssets/Mirror/Core/LagCompensation.meta new file mode 100644 index 0000000000..b5583efc07 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d2656015ded44e83a24f4c4776bafd40 +timeCreated: 1687920405 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/Capture.cs b/Assets/ImportedAssets/Mirror/Core/LagCompensation/Capture.cs new file mode 100644 index 0000000000..e4fdabea01 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/Capture.cs @@ -0,0 +1,13 @@ +namespace Mirror +{ + public interface Capture + { + // server timestamp at time of capture. + double timestamp { get; set; } + + // optional gizmo drawing for visual debugging. + // history is only known on the server, which usually doesn't render. + // showing Gizmos in the Editor is enough. + void DrawGizmo(); + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/Capture.cs.meta b/Assets/ImportedAssets/Mirror/Core/LagCompensation/Capture.cs.meta new file mode 100644 index 0000000000..fc37457f34 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/Capture.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 347e831952e943a49095cadd39a5aeb2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/LagCompensation/Capture.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/HistoryBounds.cs b/Assets/ImportedAssets/Mirror/Core/LagCompensation/HistoryBounds.cs new file mode 100644 index 0000000000..29ebc2ef76 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/HistoryBounds.cs @@ -0,0 +1,139 @@ +// HistoryBounds keeps a bounding box of all the object's bounds in the past N seconds. +// useful to decide which objects to rollback, instead of rolling back all of them. +// https://www.youtube.com/watch?v=zrIY0eIyqmI (37:00) +// standalone C# implementation to be engine (and language) agnostic. + +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // FakeByte: gather bounds in smaller buckets. + // for example, bucket(t0,t1,t2), bucket(t3,t4,t5), ... + // instead of removing old bounds t0, t1, ... + // we remove a whole bucket every 3 times: bucket(t0,t1,t2) + // and when building total bounds, we encapsulate a few larger buckets + // instead of many smaller bounds. + // + // => a bucket is encapsulate(bounds0, bounds1, bounds2) so we don't + // need a custom struct, simply reuse bounds but remember that each + // entry includes N timestamps. + // + // => note that simply reducing capture interval is _not_ the same. + // we want to capture in detail in case players run in zig-zag. + // but still grow larger buckets internally. + public class HistoryBounds + { + // mischa: use MinMaxBounds to avoid Unity Bounds.Encapsulate conversions. + readonly int boundsPerBucket; + readonly Queue fullBuckets; + + // full bucket limit. older ones will be removed. + readonly int bucketLimit; + + // bucket in progress, contains 0..boundsPerBucket bounds encapsulated. + MinMaxBounds? currentBucket; + int currentBucketSize; + + // amount of total bounds, including bounds in full buckets + current + public int boundsCount { get; private set; } + + // total bounds encapsulating all of the bounds history. + // totalMinMax is used for internal calculations. + // public total is used for Unity representation. + MinMaxBounds totalMinMax; + public Bounds total + { + get + { + Bounds bounds = new Bounds(); + bounds.SetMinMax(totalMinMax.min, totalMinMax.max); + return bounds; + } + } + + public HistoryBounds(int boundsLimit, int boundsPerBucket) + { + // bucketLimit via '/' cuts off remainder. + // that's what we want, since we always have a 'currentBucket'. + this.boundsPerBucket = boundsPerBucket; + this.bucketLimit = (boundsLimit / boundsPerBucket); + + // initialize queue with maximum capacity to avoid runtime resizing + // capacity +1 because it makes the code easier if we insert first, and then remove. + fullBuckets = new Queue(bucketLimit + 1); + } + + // insert new bounds into history. calculates new total bounds. + // Queue.Dequeue() always has the oldest bounds. + public void Insert(Bounds bounds) + { + // convert to MinMax representation for faster .Encapsulate() + MinMaxBounds minmax = new MinMaxBounds + { + min = bounds.min, + max = bounds.max + }; + + // initialize 'total' if not initialized yet. + // we don't want to call (0,0).Encapsulate(bounds). + if (boundsCount == 0) + { + totalMinMax = minmax; + } + + // add to current bucket: + // either initialize new one, or encapsulate into existing one + if (currentBucket == null) + { + currentBucket = minmax; + } + else + { + currentBucket.Value.Encapsulate(minmax); + } + + // current bucket has one more bounds. + // total bounds increased as well. + currentBucketSize += 1; + boundsCount += 1; + + // always encapsulate into total immediately. + // this is free. + totalMinMax.Encapsulate(minmax); + + // current bucket full? + if (currentBucketSize == boundsPerBucket) + { + // move it to full buckets + fullBuckets.Enqueue(currentBucket.Value); + currentBucket = null; + currentBucketSize = 0; + + // full bucket capacity reached? + if (fullBuckets.Count > bucketLimit) + { + // remove oldest bucket + fullBuckets.Dequeue(); + boundsCount -= boundsPerBucket; + + // recompute total bounds + // instead of iterating N buckets, we iterate N / boundsPerBucket buckets. + // TODO technically we could reuse 'currentBucket' before clearing instead of encapsulating again + totalMinMax = minmax; + foreach (MinMaxBounds bucket in fullBuckets) + totalMinMax.Encapsulate(bucket); + } + } + } + + public void Reset() + { + fullBuckets.Clear(); + currentBucket = null; + currentBucketSize = 0; + boundsCount = 0; + totalMinMax = new MinMaxBounds(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/HistoryBounds.cs.meta b/Assets/ImportedAssets/Mirror/Core/LagCompensation/HistoryBounds.cs.meta new file mode 100644 index 0000000000..17380d0800 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/HistoryBounds.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ca9ea58b98a34f73801b162cd5de724e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/LagCompensation/HistoryBounds.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensation.cs b/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensation.cs new file mode 100644 index 0000000000..ae37a3f167 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensation.cs @@ -0,0 +1,144 @@ +// standalone lag compensation algorithm +// based on the Valve Networking Model: +// https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking +using System.Collections.Generic; + +namespace Mirror +{ + public static class LagCompensation + { + // history is of . + // Queue allows for fast 'remove first' and 'append last'. + // + // make sure to always insert in order. + // inserting out of order like [1,2,4,3] would cause issues. + // can't safeguard this because Queue doesn't have .Last access. + public static void Insert( + Queue> history, + int historyLimit, + double timestamp, + T capture) + where T : Capture + { + // make space according to history limit. + // do this before inserting, to avoid resizing past capacity. + if (history.Count >= historyLimit) + history.Dequeue(); + + // insert + history.Enqueue(new KeyValuePair(timestamp, capture)); + } + + // get the two snapshots closest to a given timestamp. + // those can be used to interpolate the exact snapshot at that time. + // if timestamp is newer than the newest history entry, then we extrapolate. + // 't' will be between 1 and 2, before is second last, after is last. + // callers should Lerp(before, after, t=1.5) to extrapolate the hit. + // see comments below for extrapolation. + public static bool Sample( + Queue> history, + double timestamp, // current server time + double interval, // capture interval + out T before, + out T after, + out double t) // interpolation factor + where T : Capture + { + before = default; + after = default; + t = 0; + + // can't sample an empty history + // interpolation needs at least one entry. + // extrapolation needs at least two entries. + // can't Lerp(A, A, 1.5). dist(A, A) * 1.5 is always 0. + if(history.Count < 2) { + return false; + } + + // older than oldest + if (timestamp < history.Peek().Key) { + return false; + } + + // iterate through the history + // TODO faster version: guess start index by how many 'intervals' we are behind. + // search around that area. + // should be O(1) most of the time, unless sampling was off. + KeyValuePair prev = new KeyValuePair(); + KeyValuePair prevPrev = new KeyValuePair(); + foreach(KeyValuePair entry in history) { + // exact match? + if (timestamp == entry.Key) { + before = entry.Value; + after = entry.Value; + t = Mathd.InverseLerp(before.timestamp, after.timestamp, timestamp); + return true; + } + + // did we check beyond timestamp? then return the previous two. + if (entry.Key > timestamp) { + before = prev.Value; + after = entry.Value; + t = Mathd.InverseLerp(before.timestamp, after.timestamp, timestamp); + return true; + } + + // remember the last two for extrapolation. + // Queue doesn't have access to .Last. + prevPrev = prev; + prev = entry; + } + + // newer than newest: extrapolate up to one interval. + // let's say we capture every 100 ms: + // 100, 200, 300, 400 + // and the server is at 499 + // if a client sends CmdFire at time 480, then there's no history entry. + // => adding the current entry every time would be too expensive. + // worst case we would capture at 401, 402, 403, 404, ... 100 times + // => not extrapolating isn't great. low latency clients would be + // punished by missing their targets since no entry at 'time' was found. + // => extrapolation is the best solution. make sure this works as + // expected and within limits. + if (prev.Key < timestamp && timestamp <= prev.Key + interval) { + // return the last two valid snapshots. + // can't just return (after, after) because we can't extrapolate + // if their distance is 0. + before = prevPrev.Value; + after = prev.Value; + + // InverseLerp will give [after, after+interval]. + // but we return [before, after, t]. + // so add +1 for the distance from before->after + t = 1 + Mathd.InverseLerp(after.timestamp, after.timestamp + interval, timestamp); + return true; + } + + return false; + } + + // never trust the client. + // we estimate when a message was sent. + // don't trust the client to tell us the time. + // https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking + // Command Execution Time = Current Server Time - Packet Latency - Client View Interpolation + // => lag compensation demo estimation is off by only ~6ms + public static double EstimateTime(double serverTime, double rtt, double bufferTime) + { + // packet latency is one trip from client to server, so rtt / 2 + // client view interpolation is the snapshot interpolation buffer time + double latency = rtt / 2; + return serverTime - latency - bufferTime; + } + + // convenience function to draw all history gizmos. + // this should be called from OnDrawGizmos. + public static void DrawGizmos(Queue> history) + where T : Capture + { + foreach (KeyValuePair entry in history) + entry.Value.DrawGizmo(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensation.cs.meta b/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensation.cs.meta new file mode 100644 index 0000000000..b7e9ba09a1 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensation.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ad53cc7d12144d0ba3a8b0a4515e5d17 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensation.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensationSettings.cs b/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensationSettings.cs new file mode 100644 index 0000000000..a7ec944495 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensationSettings.cs @@ -0,0 +1,19 @@ +// snapshot interpolation settings struct. +// can easily be exposed in Unity inspectors. +using System; +using UnityEngine; + +namespace Mirror +{ + // class so we can define defaults easily + [Serializable] + public class LagCompensationSettings + { + [Header("Buffering")] + [Tooltip("Keep this many past snapshots in the buffer. The larger this is, the further we can rewind into the past.\nMaximum rewind time := historyAmount * captureInterval")] + public int historyLimit = 6; + + [Tooltip("Capture state every 'captureInterval' seconds. Larger values will space out the captures more, which gives a longer history but with possible gaps inbetween.\nSmaller values will have fewer gaps, with shorter history.")] + public float captureInterval = 0.100f; // 100 ms + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensationSettings.cs.meta b/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensationSettings.cs.meta new file mode 100644 index 0000000000..5f3400ac9d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensationSettings.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: fa80bec245f94bf8a28ec78777992a1c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/LagCompensation/LagCompensationSettings.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/MinMaxBounds.cs b/Assets/ImportedAssets/Mirror/Core/LagCompensation/MinMaxBounds.cs new file mode 100644 index 0000000000..b1b487416a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/MinMaxBounds.cs @@ -0,0 +1,73 @@ +// Unity's Bounds struct is represented as (center, extents). +// HistoryBounds make heavy use of .Encapsulate(), which has to convert +// Unity's (center, extents) to (min, max) every time, and then convert back. +// +// It's faster to use a (min, max) representation directly instead. +using System; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + public struct MinMaxBounds: IEquatable + { + public Vector3 min; + public Vector3 max; + + // encapsulate a single point + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Encapsulate(Vector3 point) + { + min = Vector3.Min(this.min, point); + max = Vector3.Max(this.max, point); + } + + // encapsulate another bounds + public void Encapsulate(MinMaxBounds bounds) + { + Encapsulate(bounds.min); + Encapsulate(bounds.max); + } + + // convenience comparison with Unity's bounds, for unit tests etc. + public static bool operator ==(MinMaxBounds lhs, Bounds rhs) => + lhs.min == rhs.min && + lhs.max == rhs.max; + + public static bool operator !=(MinMaxBounds lhs, Bounds rhs) => + !(lhs == rhs); + + public override bool Equals(object obj) => + obj is MinMaxBounds other && + min == other.min && + max == other.max; + + public bool Equals(MinMaxBounds other) => + min.Equals(other.min) && max.Equals(other.max); + + public bool Equals(Bounds other) => + min.Equals(other.min) && max.Equals(other.max); + +#if UNITY_2021_3_OR_NEWER + // Unity 2019/2020 don't have HashCode.Combine yet. + // this is only to avoid reflection. without defining, it works too. + // default generated by rider + public override int GetHashCode() => HashCode.Combine(min, max); +#else + public override int GetHashCode() + { + // return HashCode.Combine(min, max); without using .Combine for older Unity versions + unchecked + { + int hash = 17; + hash = hash * 23 + min.GetHashCode(); + hash = hash * 23 + max.GetHashCode(); + return hash; + } + } +#endif + + // tostring + public override string ToString() => $"({min}, {max})"; + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/LagCompensation/MinMaxBounds.cs.meta b/Assets/ImportedAssets/Mirror/Core/LagCompensation/MinMaxBounds.cs.meta new file mode 100644 index 0000000000..fee61fecd5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LagCompensation/MinMaxBounds.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 4372b1e1a1cc4c669cc7bf0925f59d29 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/LagCompensation/MinMaxBounds.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/LocalConnectionToClient.cs b/Assets/ImportedAssets/Mirror/Core/LocalConnectionToClient.cs new file mode 100644 index 0000000000..c41c6ae29c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LocalConnectionToClient.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; + +namespace Mirror +{ + // a server's connection TO a LocalClient. + // sending messages on this connection causes the client's handler function to be invoked directly + public class LocalConnectionToClient : NetworkConnectionToClient + { + internal LocalConnectionToServer connectionToServer; + + // packet queue + internal readonly Queue queue = new Queue(); + + public LocalConnectionToClient() : base(LocalConnectionId) {} + + public override string address => "localhost"; + + internal override void Send(ArraySegment segment, int channelId = Channels.Reliable) + { + // instead of invoking it directly, we enqueue and process next update. + // this way we can simulate a similar call flow as with remote clients. + // the closer we get to simulating host as remote, the better! + // both directions do this, so [Command] and [Rpc] behave the same way. + + //Debug.Log($"Enqueue {BitConverter.ToString(segment.Array, segment.Offset, segment.Count)}"); + NetworkWriterPooled writer = NetworkWriterPool.Get(); + writer.WriteBytes(segment.Array, segment.Offset, segment.Count); + connectionToServer.queue.Enqueue(writer); + } + + // true because local connections never timeout + internal override bool IsAlive(float timeout) => true; + + // don't ping host client in host mode + protected override void UpdatePing() {} + + internal override void Update() + { + base.Update(); + + // process internal messages so they are applied at the correct time + while (queue.Count > 0) + { + // call receive on queued writer's content, return to pool + NetworkWriterPooled writer = queue.Dequeue(); + ArraySegment message = writer.ToArraySegment(); + + // OnTransportData assumes a proper batch with timestamp etc. + // let's make a proper batch and pass it to OnTransportData. + Batcher batcher = GetBatchForChannelId(Channels.Reliable); + batcher.AddMessage(message, NetworkTime.localTime); + + using (NetworkWriterPooled batchWriter = NetworkWriterPool.Get()) + { + // make a batch with our local time (double precision) + if (batcher.GetBatch(batchWriter)) + { + NetworkServer.OnTransportData(connectionId, batchWriter.ToArraySegment(), Channels.Reliable); + } + } + + NetworkWriterPool.Return(writer); + } + } + + internal void DisconnectInternal() + { + // set not ready and handle clientscene disconnect in any case + // (might be client or host mode here) + isReady = false; + RemoveFromObservingsObservers(); + } + + /// Disconnects this connection. + public override void Disconnect() + { + DisconnectInternal(); + connectionToServer.DisconnectInternal(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/LocalConnectionToClient.cs.meta b/Assets/ImportedAssets/Mirror/Core/LocalConnectionToClient.cs.meta new file mode 100644 index 0000000000..d1f068375a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LocalConnectionToClient.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a88758df7db2043d6a9d926e0b6d4191 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/LocalConnectionToClient.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/LocalConnectionToServer.cs b/Assets/ImportedAssets/Mirror/Core/LocalConnectionToServer.cs new file mode 100644 index 0000000000..15669c785d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LocalConnectionToServer.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // a localClient's connection TO a server. + // send messages on this connection causes the server's handler function to be invoked directly. + public class LocalConnectionToServer : NetworkConnectionToServer + { + internal LocalConnectionToClient connectionToClient; + + // packet queue + internal readonly Queue queue = new Queue(); + + // see caller for comments on why we need this + bool connectedEventPending; + bool disconnectedEventPending; + internal void QueueConnectedEvent() => connectedEventPending = true; + internal void QueueDisconnectedEvent() => disconnectedEventPending = true; + + // Send stage two: serialized NetworkMessage as ArraySegment + internal override void Send(ArraySegment segment, int channelId = Channels.Reliable) + { + if (segment.Count == 0) + { + Debug.LogError("LocalConnection.SendBytes cannot send zero bytes"); + return; + } + + // instead of invoking it directly, we enqueue and process next update. + // this way we can simulate a similar call flow as with remote clients. + // the closer we get to simulating host as remote, the better! + // both directions do this, so [Command] and [Rpc] behave the same way. + + //Debug.Log($"Enqueue {BitConverter.ToString(segment.Array, segment.Offset, segment.Count)}"); + NetworkWriterPooled writer = NetworkWriterPool.Get(); + writer.WriteBytes(segment.Array, segment.Offset, segment.Count); + connectionToClient.queue.Enqueue(writer); + } + + internal override void Update() + { + base.Update(); + + // should we still process a connected event? + if (connectedEventPending) + { + connectedEventPending = false; + NetworkClient.OnConnectedEvent?.Invoke(); + } + + // process internal messages so they are applied at the correct time + while (queue.Count > 0) + { + // call receive on queued writer's content, return to pool + NetworkWriterPooled writer = queue.Dequeue(); + ArraySegment message = writer.ToArraySegment(); + + // OnTransportData assumes a proper batch with timestamp etc. + // let's make a proper batch and pass it to OnTransportData. + Batcher batcher = GetBatchForChannelId(Channels.Reliable); + batcher.AddMessage(message, NetworkTime.localTime); + + using (NetworkWriterPooled batchWriter = NetworkWriterPool.Get()) + { + // make a batch with our local time (double precision) + if (batcher.GetBatch(batchWriter)) + { + NetworkClient.OnTransportData(batchWriter.ToArraySegment(), Channels.Reliable); + } + } + + NetworkWriterPool.Return(writer); + } + + // should we still process a disconnected event? + if (disconnectedEventPending) + { + disconnectedEventPending = false; + NetworkClient.OnDisconnectedEvent?.Invoke(); + } + } + + /// Disconnects this connection. + internal void DisconnectInternal() + { + // set not ready and handle clientscene disconnect in any case + // (might be client or host mode here) + // TODO remove redundant state. have one source of truth for .ready! + isReady = false; + NetworkClient.ready = false; + } + + /// Disconnects this connection. + public override void Disconnect() + { + connectionToClient.DisconnectInternal(); + DisconnectInternal(); + + // simulate what a true remote connection would do: + // first, the server should remove it: + // TODO should probably be in connectionToClient.DisconnectInternal + // because that's the NetworkServer's connection! + NetworkServer.RemoveLocalConnection(); + + // then call OnTransportDisconnected for proper disconnect handling, + // callbacks & cleanups. + // => otherwise OnClientDisconnected() is never called! + // => see NetworkClientTests.DisconnectCallsOnClientDisconnect_HostMode() + NetworkClient.OnTransportDisconnected(); + } + + // true because local connections never timeout + internal override bool IsAlive(float timeout) => true; + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/LocalConnectionToServer.cs.meta b/Assets/ImportedAssets/Mirror/Core/LocalConnectionToServer.cs.meta new file mode 100644 index 0000000000..8b5104cfee --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/LocalConnectionToServer.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: cdfff390c3504158a269e8b8662e2a40 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/LocalConnectionToServer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Messages.cs b/Assets/ImportedAssets/Mirror/Core/Messages.cs new file mode 100644 index 0000000000..62888c07e6 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Messages.cs @@ -0,0 +1,140 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + // need to send time every sendInterval. + // batching automatically includes remoteTimestamp. + // all we need to do is ensure that an empty message is sent. + // and react to it. + // => we don't want to insert a snapshot on every batch. + // => do it exactly every sendInterval on every TimeSnapshotMessage. + public struct TimeSnapshotMessage : NetworkMessage {} + + public struct ReadyMessage : NetworkMessage {} + + public struct NotReadyMessage : NetworkMessage {} + + public struct AddPlayerMessage : NetworkMessage {} + + public struct SceneMessage : NetworkMessage + { + public string sceneName; + // Normal = 0, LoadAdditive = 1, UnloadAdditive = 2 + public SceneOperation sceneOperation; + public bool customHandling; + } + + public enum SceneOperation : byte + { + Normal, + LoadAdditive, + UnloadAdditive + } + + public struct CommandMessage : NetworkMessage + { + public uint netId; + public byte componentIndex; + public ushort functionHash; + // the parameters for the Cmd function + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + } + + public struct RpcMessage : NetworkMessage + { + public uint netId; + public byte componentIndex; + public ushort functionHash; + // the parameters for the Cmd function + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + } + + public struct SpawnMessage : NetworkMessage + { + // netId of new or existing object + public uint netId; + public bool isLocalPlayer; + // Sets hasAuthority on the spawned object + public bool isOwner; + public ulong sceneId; + // If sceneId != 0 then it is used instead of assetId + public uint assetId; + // Local position + public Vector3 position; + // Local rotation + public Quaternion rotation; + // Local scale + public Vector3 scale; + // serialized component data + // ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + } + + public struct ChangeOwnerMessage : NetworkMessage + { + public uint netId; + public bool isOwner; + public bool isLocalPlayer; + } + + public struct ObjectSpawnStartedMessage : NetworkMessage {} + + public struct ObjectSpawnFinishedMessage : NetworkMessage {} + + public struct ObjectDestroyMessage : NetworkMessage + { + public uint netId; + } + + public struct ObjectHideMessage : NetworkMessage + { + public uint netId; + } + + public struct EntityStateMessage : NetworkMessage + { + public uint netId; + // the serialized component data + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + } + + // whoever wants to measure rtt, sends this to the other end. + public struct NetworkPingMessage : NetworkMessage + { + // local time is used to calculate round trip time, + // and to calculate the predicted time offset. + public double localTime; + + // predicted time is sent to compare the final error, for debugging only + public double predictedTimeAdjusted; + + public NetworkPingMessage(double localTime, double predictedTimeAdjusted) + { + this.localTime = localTime; + this.predictedTimeAdjusted = predictedTimeAdjusted; + } + } + + // the other end responds with this message. + // we can use this to calculate rtt. + public struct NetworkPongMessage : NetworkMessage + { + // local time is used to calculate round trip time. + public double localTime; + + // predicted error is used to adjust the predicted timeline. + public double predictionErrorUnadjusted; + public double predictionErrorAdjusted; // for debug purposes + + public NetworkPongMessage(double localTime, double predictionErrorUnadjusted, double predictionErrorAdjusted) + { + this.localTime = localTime; + this.predictionErrorUnadjusted = predictionErrorUnadjusted; + this.predictionErrorAdjusted = predictionErrorAdjusted; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Messages.cs.meta b/Assets/ImportedAssets/Mirror/Core/Messages.cs.meta new file mode 100644 index 0000000000..e41af9215e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Messages.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 938f6f28a6c5b48a0bbd7782342d763b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Messages.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Mirror.asmdef b/Assets/ImportedAssets/Mirror/Core/Mirror.asmdef new file mode 100644 index 0000000000..2fa8d95226 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Mirror.asmdef @@ -0,0 +1,16 @@ +{ + "name": "Mirror", + "rootNamespace": "", + "references": [ + "GUID:325984b52e4128546bc7558552f8b1d2" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Core/Mirror.asmdef.meta b/Assets/ImportedAssets/Mirror/Core/Mirror.asmdef.meta new file mode 100644 index 0000000000..6766765e99 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Mirror.asmdef.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 30817c1a0e6d646d99c048fc403f5979 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Mirror.asmdef + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkAuthenticator.cs b/Assets/ImportedAssets/Mirror/Core/NetworkAuthenticator.cs new file mode 100644 index 0000000000..aa1e7f7a59 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkAuthenticator.cs @@ -0,0 +1,84 @@ +using System; +using UnityEngine; +using UnityEngine.Events; + +namespace Mirror +{ + [Serializable] public class UnityEventNetworkConnection : UnityEvent {} + + /// Base class for implementing component-based authentication during the Connect phase + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-authenticators")] + public abstract class NetworkAuthenticator : MonoBehaviour + { + /// Notify subscribers on the server when a client is authenticated + [Header("Event Listeners (optional)")] + [Tooltip("Mirror has an internal subscriber to this event. You can add your own here.")] + public UnityEventNetworkConnection OnServerAuthenticated = new UnityEventNetworkConnection(); + + /// Notify subscribers on the client when the client is authenticated + [Tooltip("Mirror has an internal subscriber to this event. You can add your own here.")] + public UnityEvent OnClientAuthenticated = new UnityEvent(); + + /// Called when server starts, used to register message handlers if needed. + public virtual void OnStartServer() {} + + /// Called when server stops, used to unregister message handlers if needed. + public virtual void OnStopServer() {} + + /// Called on server from OnServerConnectInternal when a client needs to authenticate + public virtual void OnServerAuthenticate(NetworkConnectionToClient conn) {} + + protected void ServerAccept(NetworkConnectionToClient conn) + { + OnServerAuthenticated.Invoke(conn); + } + + protected void ServerReject(NetworkConnectionToClient conn) + { + conn.Disconnect(); + } + + /// Called when client starts, used to register message handlers if needed. + public virtual void OnStartClient() {} + + /// Called when client stops, used to unregister message handlers if needed. + public virtual void OnStopClient() {} + + /// Called on client from OnClientConnectInternal when a client needs to authenticate + public virtual void OnClientAuthenticate() {} + + protected void ClientAccept() + { + OnClientAuthenticated.Invoke(); + } + + protected void ClientReject() + { + // Set this on the client for local reference + NetworkClient.connection.isAuthenticated = false; + + // disconnect the client + NetworkClient.connection.Disconnect(); + } + + // Reset() instead of OnValidate(): + // Any NetworkAuthenticator assigns itself to the NetworkManager, this is fine on first adding it, + // but if someone intentionally sets Authenticator to null on the NetworkManager again then the + // Authenticator will reassign itself if a value in the inspector is changed. + // My change switches OnValidate to Reset since Reset is only called when the component is first + // added (or reset is pressed). + void Reset() + { +#if UNITY_EDITOR + // automatically assign authenticator field if we add this to NetworkManager + NetworkManager manager = GetComponent(); + if (manager != null && manager.authenticator == null) + { + // undo has to be called before the change happens + UnityEditor.Undo.RecordObject(manager, "Assigned NetworkManager authenticator"); + manager.authenticator = this; + } +#endif + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkAuthenticator.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkAuthenticator.cs.meta new file mode 100644 index 0000000000..07ac3480ab --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkAuthenticator.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 407fc95d4a8257f448799f26cdde0c2a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkAuthenticator.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkBehaviour.cs b/Assets/ImportedAssets/Mirror/Core/NetworkBehaviour.cs new file mode 100644 index 0000000000..52ca522f3e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkBehaviour.cs @@ -0,0 +1,1379 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + // SyncMode decides if a component is synced to all observers, or only owner + public enum SyncMode { Observers, Owner } + + // SyncDirection decides if a component is synced from: + // * server to all clients + // * owner client, to server, to all other clients + // + // naming: 'ClientToServer' etc. instead of 'ClientAuthority', because + // that wouldn't be accurate. server's OnDeserialize can still validate + // client data before applying. it's really about direction, not authority. + public enum SyncDirection { ServerToClient, ClientToServer } + + /// Base class for networked components. + // [RequireComponent(typeof(NetworkIdentity))] disabled to allow child NetworkBehaviours + [AddComponentMenu("")] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/networkbehaviour")] + public abstract class NetworkBehaviour : MonoBehaviour + { + /// Sync direction for OnSerialize. ServerToClient by default. ClientToServer for client authority. + [Tooltip("Server Authority calls OnSerialize on the server and syncs it to clients.\n\nClient Authority calls OnSerialize on the owning client, syncs it to server, which then broadcasts it to all other clients.\n\nUse server authority for cheat safety.")] + [HideInInspector] public SyncDirection syncDirection = SyncDirection.ServerToClient; + + /// sync mode for OnSerialize + // hidden because NetworkBehaviourInspector shows it only if has OnSerialize. + [Tooltip("By default synced data is sent from the server to all Observers of the object.\nChange this to Owner to only have the server update the client that has ownership authority for this object")] + [HideInInspector] public SyncMode syncMode = SyncMode.Observers; + + /// sync interval for OnSerialize (in seconds) + // hidden because NetworkBehaviourInspector shows it only if has OnSerialize. + // [0,2] should be enough. anything >2s is too laggy anyway. + // + // NetworkServer & NetworkClient broadcast() are behind a sendInterval timer now. + // it makes sense to keep every component's syncInterval setting at '0' by default. + // otherwise, the overlapping timers could introduce unexpected latency. + // careful: default of '0.1' may + [Tooltip("Time in seconds until next change is synchronized to the client. '0' means send immediately if changed. '0.5' means only send changes every 500ms.\n(This is for state synchronization like SyncVars, SyncLists, OnSerialize. Not for Cmds, Rpcs, etc.)")] + [Range(0, 2)] + [HideInInspector] public float syncInterval = 0; + internal double lastSyncTime; + + /// True if this object is on the server and has been spawned. + // This is different from NetworkServer.active, which is true if the + // server itself is active rather than this object being active. + public bool isServer => netIdentity.isServer; + + /// True if this object is on the client and has been spawned by the server. + public bool isClient => netIdentity.isClient; + + /// True if this object is the the client's own local player. + public bool isLocalPlayer => netIdentity.isLocalPlayer; + + /// True if this object is on the server-only, not host. + public bool isServerOnly => netIdentity.isServerOnly; + + /// True if this object is on the client-only, not host. + public bool isClientOnly => netIdentity.isClientOnly; + + /// isOwned is true on the client if this NetworkIdentity is one of the .owned entities of our connection on the server. + // for example: main player & pets are owned. monsters & npcs aren't. + public bool isOwned => netIdentity.isOwned; + + /// authority is true if we are allowed to modify this component's state. On server, it's true if SyncDirection is ServerToClient. On client, it's true if SyncDirection is ClientToServer and(!) if this object is owned by the client. + // on the client: if Client->Server SyncDirection and owned + // on the server: if Server->Client SyncDirection + // on the host: if Server->Client SyncDirection (= server owns it), or if Client->Server and owned (=host client owns it) + // in host mode: always true because either server or client always has authority, and host is both. + // + // for example, NetworkTransform: + // client may modify position if ClientAuthority mode and owned + // server may modify position only if server authority + // + // note that in original Mirror, hasAuthority only meant 'isOwned'. + // there was no syncDirection to check. + // + // also note that this is a per-NetworkBehaviour flag. + // another component may not be client authoritative, etc. + public bool authority + { + get + { + // host mode needs to be checked explicitly + if (isClient && isServer) return syncDirection == SyncDirection.ServerToClient || isOwned; + + // client-only + if (isClient) return syncDirection == SyncDirection.ClientToServer && isOwned; + + // server-only + return syncDirection == SyncDirection.ServerToClient; + } + } + + /// The unique network Id of this object (unique at runtime). + public uint netId => netIdentity.netId; + + /// Client's network connection to the server. This is only valid for player objects on the client. + // TODO change to NetworkConnectionToServer, but might cause some breaking + public NetworkConnection connectionToServer => netIdentity.connectionToServer; + + /// Server's network connection to the client. This is only valid for player objects on the server. + public NetworkConnectionToClient connectionToClient => netIdentity.connectionToClient; + + // SyncLists, SyncSets, etc. + protected readonly List syncObjects = new List(); + + // NetworkBehaviourInspector needs to know if we have SyncObjects + internal bool HasSyncObjects() => syncObjects.Count > 0; + + // NetworkIdentity based values set from NetworkIdentity.Awake(), + // which is way more simple and way faster than trying to figure out + // component index from in here by searching all NetworkComponents. + + /// Returns the NetworkIdentity of this object + public NetworkIdentity netIdentity { get; internal set; } + + /// Returns the index of the component on this object + public byte ComponentIndex { get; internal set; } + + // to avoid fully serializing entities every time, we have two options: + // * run a delta compression algorithm + // -> for fixed size types this is as easy as varint(b-a) for all + // -> for dynamically sized types like strings this is not easy. + // algorithms need to detect inserts/deletions, i.e. Myers Diff. + // those are very cpu intensive and barely fast enough for large + // scale multiplayer games (in Unity) + // * or we use dirty bits as meta data about which fields have changed + // -> spares us from running delta algorithms + // -> still supports dynamically sized types + // + // 64 bit mask, tracking up to 64 SyncVars. + // protected since NB child classes read this field in the weaver generated SerializeSyncVars method + protected ulong syncVarDirtyBits; + // 64 bit mask, tracking up to 64 sync collections. + // internal for tests, field for faster access (instead of property) + // TODO 64 SyncLists are too much. consider smaller mask later. + internal ulong syncObjectDirtyBits; + + // Weaver replaces '[SyncVar] int health' with 'Networkhealth' property. + // setter calls the hook if value changed. + // if we then modify the [SyncVar] from inside the setter, + // the setter would call the hook and we deadlock. + // hook guard prevents that. + ulong syncVarHookGuard; + + // USED BY WEAVER to set syncvars in host mode without deadlocking + protected bool GetSyncVarHookGuard(ulong dirtyBit) => + (syncVarHookGuard & dirtyBit) != 0UL; + + // USED BY WEAVER to set syncvars in host mode without deadlocking + protected void SetSyncVarHookGuard(ulong dirtyBit, bool value) + { + // set the bit + if (value) + syncVarHookGuard |= dirtyBit; + // clear the bit + else + syncVarHookGuard &= ~dirtyBit; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void SetSyncObjectDirtyBit(ulong dirtyBit) + { + syncObjectDirtyBits |= dirtyBit; + } + + /// Set as dirty so that it's synced to clients again. + // these are masks, not bit numbers, ie. 110011b not '2' for 2nd bit. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetSyncVarDirtyBit(ulong dirtyBit) + { + syncVarDirtyBits |= dirtyBit; + } + + /// Set as dirty to trigger OnSerialize & send. Dirty bits are cleared after the send. + // previously one had to use SetSyncVarDirtyBit(1), which is confusing. + // simply reuse SetSyncVarDirtyBit for now. + // instead of adding another field. + // syncVarDirtyBits does trigger OnSerialize as well. + // + // it's important to set _all_ bits as dirty. + // for example, server needs to broadcast ClientToServer components. + // if we only set the first bit, only that SyncVar would be broadcast. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetDirty() => SetSyncVarDirtyBit(ulong.MaxValue); + + // true if syncInterval elapsed and any SyncVar or SyncObject is dirty + // OR both bitmasks. != 0 if either was dirty. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsDirty() => + // check bits first. this is basically free. + (syncVarDirtyBits | syncObjectDirtyBits) != 0UL && + // only check time if bits were dirty. this is more expensive. + NetworkTime.localTime - lastSyncTime >= syncInterval; + + /// Clears all the dirty bits that were set by SetSyncVarDirtyBit() (formally SetDirtyBits) + // automatically invoked when an update is sent for this object, but can + // be called manually as well. + public void ClearAllDirtyBits() + { + lastSyncTime = NetworkTime.localTime; + syncVarDirtyBits = 0L; + syncObjectDirtyBits = 0L; + + // clear all unsynchronized changes in syncobjects + // (Linq allocates, use for instead) + for (int i = 0; i < syncObjects.Count; ++i) + { + syncObjects[i].ClearChanges(); + } + } + + // this gets called in the constructor by the weaver + // for every SyncObject in the component (e.g. SyncLists). + // We collect all of them and we synchronize them with OnSerialize/OnDeserialize + protected void InitSyncObject(SyncObject syncObject) + { + if (syncObject == null) + { + Debug.LogError("Uninitialized SyncObject. Manually call the constructor on your SyncList, SyncSet, SyncDictionary or SyncField"); + return; + } + + // add it, remember the index in list (if Count=0, index=0 etc.) + int index = syncObjects.Count; + syncObjects.Add(syncObject); + + // OnDirty needs to set nth bit in our dirty mask + ulong nthBit = 1UL << index; + syncObject.OnDirty = () => SetSyncObjectDirtyBit(nthBit); + + // who is allowed to modify SyncList/SyncSet/etc.: + // on client: only if owned ClientToserver + // on server: only if ServerToClient. + // but also for initial state when spawning. + // need to set a lambda because 'isClient' isn't available in + // InitSyncObject yet, which is called from the constructor. + syncObject.IsWritable = () => + { + // carefully check each mode separately to ensure correct results. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3342 + + // normally we would check isServer / isClient here. + // users may add to SyncLists before the object was spawned. + // isServer / isClient would still be false. + // so we need to check NetworkServer/Client.active here instead. + + // host mode: any ServerToClient and any local client owned + if (NetworkServer.active && NetworkClient.active) + return syncDirection == SyncDirection.ServerToClient || isOwned; + + // server only: any ServerToClient + if (NetworkServer.active) + return syncDirection == SyncDirection.ServerToClient; + + // client only: only ClientToServer and owned + if (NetworkClient.active) + { + // spawned: only ClientToServer and owned + if (netId != 0) return syncDirection == SyncDirection.ClientToServer && isOwned; + + // not spawned (character selection previews, etc.): always allow + // fixes https://github.com/MirrorNetworking/Mirror/issues/3343 + return true; + } + + // undefined behaviour should throw to make it very obvious + throw new Exception("InitSyncObject: IsWritable: neither NetworkServer nor NetworkClient are active."); + }; + + // when do we record changes: + // on client: only if owned ClientToServer + // on server: only if we have observers. + // prevents ever growing .changes lists: + // if a monster has no observers but we keep modifing a SyncObject, + // then the changes would never be flushed and keep growing, + // because OnSerialize isn't called without observers. + syncObject.IsRecording = () => + { + // carefully check each mode separately to ensure correct results. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3342 + + // host mode: only if observed + if (isServer && isClient) return netIdentity.observers.Count > 0; + + // server only: only if observed + if (isServer) return netIdentity.observers.Count > 0; + + // client only: only ClientToServer and owned + if (isClient) return syncDirection == SyncDirection.ClientToServer && isOwned; + + // users may add to SyncLists before the object was spawned. + // isServer / isClient would still be false. + // in that case, allow modifying but don't record changes yet. + return false; + }; + } + + protected virtual void OnValidate() + { + // we now allow child NetworkBehaviours. + // we can not [RequireComponent(typeof(NetworkIdentity))] anymore. + // instead, we need to ensure a NetworkIdentity is somewhere in the + // parents. + // only run this in Editor. don't add more runtime overhead. + + // GetComponentInParent(includeInactive) is needed because Prefabs are not + // considered active, so this check requires to scan inactive. +#if UNITY_EDITOR +#if UNITY_2021_3_OR_NEWER // 2021 has GetComponentInParent(bool includeInactive = false) + if (GetComponent() == null && + GetComponentInParent(true) == null) + { + Debug.LogError($"{GetType()} on {name} requires a NetworkIdentity. Please add a NetworkIdentity component to {name} or it's parents.", this); + } +#elif UNITY_2020_3_OR_NEWER // 2020 only has GetComponentsInParent(bool includeInactive = false), we can use this too + NetworkIdentity[] parentsIds = GetComponentsInParent(true); + int parentIdsCount = parentsIds != null ? parentsIds.Length : 0; + if (GetComponent() == null && parentIdsCount == 0) + { + Debug.LogError($"{GetType()} on {name} requires a NetworkIdentity. Please add a NetworkIdentity component to {name} or it's parents.", this); + } +#endif +#endif + } + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + protected void SendCommandInternal(string functionFullName, int functionHashCode, NetworkWriter writer, int channelId, bool requiresAuthority = true) + { + // this was in Weaver before + // NOTE: we could remove this later to allow calling Cmds on Server + // to avoid Wrapper functions. a lot of people requested this. + if (!NetworkClient.active) + { + Debug.LogError($"Command {functionFullName} called on {name} without an active client.", gameObject); + return; + } + + // previously we used NetworkClient.readyConnection. + // now we check .ready separately. + if (!NetworkClient.ready) + { + // Unreliable Cmds from NetworkTransform may be generated, + // or client may have been set NotReady intentionally, so + // only warn if on the reliable channel. + if (channelId == Channels.Reliable) + Debug.LogWarning($"Command {functionFullName} called on {name} while NetworkClient is not ready.\nThis may be ignored if client intentionally set NotReady.", gameObject); + return; + } + + // local players can always send commands, regardless of authority, + // other objects must have authority. + if (!(!requiresAuthority || isLocalPlayer || isOwned)) + { + Debug.LogWarning($"Command {functionFullName} called on {name} without authority.", gameObject); + return; + } + + // IMPORTANT: can't use .connectionToServer here because calling + // a command on other objects is allowed if requireAuthority is + // false. other objects don't have a .connectionToServer. + // => so we always need to use NetworkClient.connection instead. + // => see also: https://github.com/vis2k/Mirror/issues/2629 + if (NetworkClient.connection == null) + { + Debug.LogError($"Command {functionFullName} called on {name} with no client running.", gameObject); + return; + } + + // construct the message + CommandMessage message = new CommandMessage + { + netId = netId, + componentIndex = ComponentIndex, + // type+func so Inventory.RpcUse != Equipment.RpcUse + functionHash = (ushort)functionHashCode, + // segment to avoid reader allocations + payload = writer.ToArraySegment() + }; + + // IMPORTANT: can't use .connectionToServer here because calling + // a command on other objects is allowed if requireAuthority is + // false. other objects don't have a .connectionToServer. + // => so we always need to use NetworkClient.connection instead. + // => see also: https://github.com/vis2k/Mirror/issues/2629 + // This bypasses the null check in NetworkClient.Send but we have + // a null check above with a detailed error log. + NetworkClient.connection.Send(message, channelId); + } + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + protected void SendRPCInternal(string functionFullName, int functionHashCode, NetworkWriter writer, int channelId, bool includeOwner) + { + // this was in Weaver before + if (!NetworkServer.active) + { + Debug.LogError($"RPC Function {functionFullName} called without an active server.", gameObject); + return; + } + + // This cannot use NetworkServer.active, as that is not specific to this object. + if (!isServer) + { + Debug.LogWarning($"ClientRpc {functionFullName} called on un-spawned object: {name}", gameObject); + return; + } + + // construct the message + RpcMessage message = new RpcMessage + { + netId = netId, + componentIndex = ComponentIndex, + // type+func so Inventory.RpcUse != Equipment.RpcUse + functionHash = (ushort)functionHashCode, + // segment to avoid reader allocations + payload = writer.ToArraySegment() + }; + + // serialize it to each ready observer's connection's rpc buffer. + // send them all at once, instead of sending one message per rpc. + // NetworkServer.SendToReadyObservers(netIdentity, message, includeOwner, channelId); + + // safety check used to be in SendToReadyObservers. keep it for now. + if (netIdentity.observers == null || netIdentity.observers.Count == 0) + return; + + // serialize the message only once + using (NetworkWriterPooled serialized = NetworkWriterPool.Get()) + { + serialized.Write(message); + + // send to every observer. + // batching buffers this automatically. + foreach (NetworkConnectionToClient conn in netIdentity.observers.Values) + { + bool isOwner = conn == netIdentity.connectionToClient; + if ((!isOwner || includeOwner) && conn.isReady) + { + conn.Send(message, channelId); + } + } + } + } + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + protected void SendTargetRPCInternal(NetworkConnection conn, string functionFullName, int functionHashCode, NetworkWriter writer, int channelId) + { + if (!NetworkServer.active) + { + Debug.LogError($"TargetRPC {functionFullName} was called on {name} when server not active.", gameObject); + return; + } + + if (!isServer) + { + Debug.LogWarning($"TargetRpc {functionFullName} called on {name} but that object has not been spawned or has been unspawned.", gameObject); + return; + } + + // connection parameter is optional. assign if null. + if (conn is null) + { + conn = connectionToClient; + } + + // if still null + if (conn is null) + { + Debug.LogError($"TargetRPC {functionFullName} can't be sent because it was given a null connection. Make sure {name} is owned by a connection, or if you pass a connection manually then make sure it's not null. For example, TargetRpcs can be called on Player/Pet which are owned by a connection. However, they can not be called on Monsters/Npcs which don't have an owner connection.", gameObject); + return; + } + + // TODO change conn type to NetworkConnectionToClient to begin with. + if (!(conn is NetworkConnectionToClient connToClient)) + { + Debug.LogError($"TargetRPC {functionFullName} called on {name} requires a NetworkConnectionToClient but was given {conn.GetType().Name}", gameObject); + return; + } + + // construct the message + RpcMessage message = new RpcMessage + { + netId = netId, + componentIndex = ComponentIndex, + // type+func so Inventory.RpcUse != Equipment.RpcUse + functionHash = (ushort)functionHashCode, + // segment to avoid reader allocations + payload = writer.ToArraySegment() + }; + + // send it to the connection. + // batching buffers this automatically. + conn.Send(message, channelId); + } + + // move the [SyncVar] generated property's .set into C# to avoid much IL + // + // public int health = 42; + // + // public int Networkhealth + // { + // get + // { + // return health; + // } + // [param: In] + // set + // { + // if (!NetworkBehaviour.SyncVarEqual(value, ref health)) + // { + // int oldValue = health; + // SetSyncVar(value, ref health, 1uL); + // if (NetworkServer.activeHost && !GetSyncVarHookGuard(1uL)) + // { + // SetSyncVarHookGuard(1uL, value: true); + // OnChanged(oldValue, value); + // SetSyncVarHookGuard(1uL, value: false); + // } + // } + // } + // } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GeneratedSyncVarSetter(T value, ref T field, ulong dirtyBit, Action OnChanged) + { + if (!SyncVarEqual(value, ref field)) + { + T oldValue = field; + SetSyncVar(value, ref field, dirtyBit); + + // call hook (if any) + if (OnChanged != null) + { + // in host mode, setting a SyncVar calls the hook directly. + // in client-only mode, OnDeserialize would call it. + // we use hook guard to protect against deadlock where hook + // changes syncvar, calling hook again. + if (NetworkServer.activeHost && !GetSyncVarHookGuard(dirtyBit)) + { + SetSyncVarHookGuard(dirtyBit, true); + OnChanged(oldValue, value); + SetSyncVarHookGuard(dirtyBit, false); + } + } + } + } + + // GameObject needs custom handling for persistence via netId. + // has one extra parameter. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GeneratedSyncVarSetter_GameObject(GameObject value, ref GameObject field, ulong dirtyBit, Action OnChanged, ref uint netIdField) + { + if (!SyncVarGameObjectEqual(value, netIdField)) + { + GameObject oldValue = field; + SetSyncVarGameObject(value, ref field, dirtyBit, ref netIdField); + + // call hook (if any) + if (OnChanged != null) + { + // in host mode, setting a SyncVar calls the hook directly. + // in client-only mode, OnDeserialize would call it. + // we use hook guard to protect against deadlock where hook + // changes syncvar, calling hook again. + if (NetworkServer.activeHost && !GetSyncVarHookGuard(dirtyBit)) + { + SetSyncVarHookGuard(dirtyBit, true); + OnChanged(oldValue, value); + SetSyncVarHookGuard(dirtyBit, false); + } + } + } + } + + // NetworkIdentity needs custom handling for persistence via netId. + // has one extra parameter. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GeneratedSyncVarSetter_NetworkIdentity(NetworkIdentity value, ref NetworkIdentity field, ulong dirtyBit, Action OnChanged, ref uint netIdField) + { + if (!SyncVarNetworkIdentityEqual(value, netIdField)) + { + NetworkIdentity oldValue = field; + SetSyncVarNetworkIdentity(value, ref field, dirtyBit, ref netIdField); + + // call hook (if any) + if (OnChanged != null) + { + // in host mode, setting a SyncVar calls the hook directly. + // in client-only mode, OnDeserialize would call it. + // we use hook guard to protect against deadlock where hook + // changes syncvar, calling hook again. + if (NetworkServer.activeHost && !GetSyncVarHookGuard(dirtyBit)) + { + SetSyncVarHookGuard(dirtyBit, true); + OnChanged(oldValue, value); + SetSyncVarHookGuard(dirtyBit, false); + } + } + } + } + + // NetworkBehaviour needs custom handling for persistence via netId. + // has one extra parameter. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GeneratedSyncVarSetter_NetworkBehaviour(T value, ref T field, ulong dirtyBit, Action OnChanged, ref NetworkBehaviourSyncVar netIdField) + where T : NetworkBehaviour + { + if (!SyncVarNetworkBehaviourEqual(value, netIdField)) + { + T oldValue = field; + SetSyncVarNetworkBehaviour(value, ref field, dirtyBit, ref netIdField); + + // call hook (if any) + if (OnChanged != null) + { + // in host mode, setting a SyncVar calls the hook directly. + // in client-only mode, OnDeserialize would call it. + // we use hook guard to protect against deadlock where hook + // changes syncvar, calling hook again. + if (NetworkServer.activeHost && !GetSyncVarHookGuard(dirtyBit)) + { + SetSyncVarHookGuard(dirtyBit, true); + OnChanged(oldValue, value); + SetSyncVarHookGuard(dirtyBit, false); + } + } + } + } + + // helper function for [SyncVar] GameObjects. + // needs to be public so that tests & NetworkBehaviours from other + // assemblies both find it + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool SyncVarGameObjectEqual(GameObject newGameObject, uint netIdField) + { + uint newNetId = 0; + if (newGameObject != null) + { + if (newGameObject.TryGetComponent(out NetworkIdentity identity)) + { + newNetId = identity.netId; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarGameObject GameObject {newGameObject} has a zero netId. Maybe it is not spawned yet?"); + } + } + } + + return newNetId == netIdField; + } + + // helper function for [SyncVar] GameObjects. + // dirtyBit is a mask like 00010 + protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, ulong dirtyBit, ref uint netIdField) + { + if (GetSyncVarHookGuard(dirtyBit)) + return; + + uint newNetId = 0; + if (newGameObject != null) + { + if (newGameObject.TryGetComponent(out NetworkIdentity identity)) + { + newNetId = identity.netId; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarGameObject GameObject {newGameObject} has a zero netId. Maybe it is not spawned yet?"); + } + } + } + + //Debug.Log($"SetSyncVar GameObject {GetType().Name} bit:{dirtyBit} netfieldId:{netIdField} -> {newNetId}"); + SetSyncVarDirtyBit(dirtyBit); + // assign new one on the server, and in case we ever need it on client too + gameObjectField = newGameObject; + netIdField = newNetId; + } + + // helper function for [SyncVar] GameObjects. + // -> ref GameObject as second argument makes OnDeserialize processing easier + protected GameObject GetSyncVarGameObject(uint netId, ref GameObject gameObjectField) + { + // server always uses the field + // if neither, fallback to original field + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3447 + if (isServer || !isClient) + { + return gameObjectField; + } + + // client always looks up based on netId because objects might get in and out of range + // over and over again, which shouldn't null them forever + if (NetworkClient.spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null) + return gameObjectField = identity.gameObject; + return null; + } + + // helper function for [SyncVar] NetworkIdentities. + // needs to be public so that tests & NetworkBehaviours from other + // assemblies both find it + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool SyncVarNetworkIdentityEqual(NetworkIdentity newIdentity, uint netIdField) + { + uint newNetId = 0; + if (newIdentity != null) + { + newNetId = newIdentity.netId; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newIdentity} has a zero netId. Maybe it is not spawned yet?"); + } + } + + // netId changed? + return newNetId == netIdField; + } + + // move the [SyncVar] generated OnDeserialize C# to avoid much IL. + // + // before: + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // int num = health; + // Networkhealth = reader.ReadInt(); + // if (!NetworkBehaviour.SyncVarEqual(num, ref health)) + // { + // OnChanged(num, health); + // } + // return; + // } + // long num2 = (long)reader.ReadULong(); + // if ((num2 & 1L) != 0L) + // { + // int num3 = health; + // Networkhealth = reader.ReadInt(); + // if (!NetworkBehaviour.SyncVarEqual(num3, ref health)) + // { + // OnChanged(num3, health); + // } + // } + // } + // + // after: + // + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // GeneratedSyncVarDeserialize(reader, ref health, null, reader.ReadInt()); + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // GeneratedSyncVarDeserialize(reader, ref health, null, reader.ReadInt()); + // } + // } + public void GeneratedSyncVarDeserialize(ref T field, Action OnChanged, T value) + { + T previous = field; + field = value; + + // any hook? then call if changed. + if (OnChanged != null && !SyncVarEqual(previous, ref field)) + { + OnChanged(previous, field); + } + } + + // move the [SyncVar] generated OnDeserialize C# to avoid much IL. + // + // before: + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // uint __targetNetId = ___targetNetId; + // GameObject networktarget = Networktarget; + // ___targetNetId = reader.ReadUInt(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId, ref ___targetNetId)) + // { + // OnChangedNB(networktarget, Networktarget); + // } + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // uint __targetNetId2 = ___targetNetId; + // GameObject networktarget2 = Networktarget; + // ___targetNetId = reader.ReadUInt(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId2, ref ___targetNetId)) + // { + // OnChangedNB(networktarget2, Networktarget); + // } + // } + // } + // + // after: + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // GeneratedSyncVarDeserialize_GameObject(reader, ref target, OnChangedNB, ref ___targetNetId); + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // GeneratedSyncVarDeserialize_GameObject(reader, ref target, OnChangedNB, ref ___targetNetId); + // } + // } + public void GeneratedSyncVarDeserialize_GameObject(ref GameObject field, Action OnChanged, NetworkReader reader, ref uint netIdField) + { + uint previousNetId = netIdField; + GameObject previousGameObject = field; + netIdField = reader.ReadUInt(); + + // get the new GameObject now that netId field is set + field = GetSyncVarGameObject(netIdField, ref field); + + // any hook? then call if changed. + if (OnChanged != null && !SyncVarEqual(previousNetId, ref netIdField)) + { + OnChanged(previousGameObject, field); + } + } + + // move the [SyncVar] generated OnDeserialize C# to avoid much IL. + // + // before: + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // uint __targetNetId = ___targetNetId; + // NetworkIdentity networktarget = Networktarget; + // ___targetNetId = reader.ReadUInt(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId, ref ___targetNetId)) + // { + // OnChangedNI(networktarget, Networktarget); + // } + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // uint __targetNetId2 = ___targetNetId; + // NetworkIdentity networktarget2 = Networktarget; + // ___targetNetId = reader.ReadUInt(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId2, ref ___targetNetId)) + // { + // OnChangedNI(networktarget2, Networktarget); + // } + // } + // } + // + // after: + // + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // GeneratedSyncVarDeserialize_NetworkIdentity(reader, ref target, OnChangedNI, ref ___targetNetId); + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // GeneratedSyncVarDeserialize_NetworkIdentity(reader, ref target, OnChangedNI, ref ___targetNetId); + // } + // } + public void GeneratedSyncVarDeserialize_NetworkIdentity(ref NetworkIdentity field, Action OnChanged, NetworkReader reader, ref uint netIdField) + { + uint previousNetId = netIdField; + NetworkIdentity previousIdentity = field; + netIdField = reader.ReadUInt(); + + // get the new NetworkIdentity now that netId field is set + field = GetSyncVarNetworkIdentity(netIdField, ref field); + + // any hook? then call if changed. + if (OnChanged != null && !SyncVarEqual(previousNetId, ref netIdField)) + { + OnChanged(previousIdentity, field); + } + } + + // move the [SyncVar] generated OnDeserialize C# to avoid much IL. + // + // before: + // + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // NetworkBehaviourSyncVar __targetNetId = ___targetNetId; + // Tank networktarget = Networktarget; + // ___targetNetId = reader.ReadNetworkBehaviourSyncVar(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId, ref ___targetNetId)) + // { + // OnChangedNB(networktarget, Networktarget); + // } + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // NetworkBehaviourSyncVar __targetNetId2 = ___targetNetId; + // Tank networktarget2 = Networktarget; + // ___targetNetId = reader.ReadNetworkBehaviourSyncVar(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId2, ref ___targetNetId)) + // { + // OnChangedNB(networktarget2, Networktarget); + // } + // } + // } + // + // after: + // + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // GeneratedSyncVarDeserialize_NetworkBehaviour(reader, ref target, OnChangedNB, ref ___targetNetId); + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // GeneratedSyncVarDeserialize_NetworkBehaviour(reader, ref target, OnChangedNB, ref ___targetNetId); + // } + // } + public void GeneratedSyncVarDeserialize_NetworkBehaviour(ref T field, Action OnChanged, NetworkReader reader, ref NetworkBehaviourSyncVar netIdField) + where T : NetworkBehaviour + { + NetworkBehaviourSyncVar previousNetId = netIdField; + T previousBehaviour = field; + netIdField = reader.ReadNetworkBehaviourSyncVar(); + + // get the new NetworkBehaviour now that netId field is set + field = GetSyncVarNetworkBehaviour(netIdField, ref field); + + // any hook? then call if changed. + if (OnChanged != null && !SyncVarEqual(previousNetId, ref netIdField)) + { + OnChanged(previousBehaviour, field); + } + } + + // helper function for [SyncVar] NetworkIdentities. + // dirtyBit is a mask like 00010 + protected void SetSyncVarNetworkIdentity(NetworkIdentity newIdentity, ref NetworkIdentity identityField, ulong dirtyBit, ref uint netIdField) + { + if (GetSyncVarHookGuard(dirtyBit)) + return; + + uint newNetId = 0; + if (newIdentity != null) + { + newNetId = newIdentity.netId; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newIdentity} has a zero netId. Maybe it is not spawned yet?"); + } + } + + //Debug.Log($"SetSyncVarNetworkIdentity NetworkIdentity {GetType().Name} bit:{dirtyBit} netIdField:{netIdField} -> {newNetId}"); + SetSyncVarDirtyBit(dirtyBit); + netIdField = newNetId; + // assign new one on the server, and in case we ever need it on client too + identityField = newIdentity; + } + + // helper function for [SyncVar] NetworkIdentities. + // -> ref GameObject as second argument makes OnDeserialize processing easier + protected NetworkIdentity GetSyncVarNetworkIdentity(uint netId, ref NetworkIdentity identityField) + { + // server always uses the field + // if neither, fallback to original field + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3447 + if (isServer || !isClient) + { + return identityField; + } + + // client always looks up based on netId because objects might get in and out of range + // over and over again, which shouldn't null them forever + NetworkClient.spawned.TryGetValue(netId, out identityField); + return identityField; + } + + protected static bool SyncVarNetworkBehaviourEqual(T newBehaviour, NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour + { + uint newNetId = 0; + byte newComponentIndex = 0; + if (newBehaviour != null) + { + newNetId = newBehaviour.netId; + newComponentIndex = newBehaviour.ComponentIndex; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newBehaviour} has a zero netId. Maybe it is not spawned yet?"); + } + } + + // netId changed? + return syncField.Equals(newNetId, newComponentIndex); + } + + // helper function for [SyncVar] NetworkIdentities. + // dirtyBit is a mask like 00010 + protected void SetSyncVarNetworkBehaviour(T newBehaviour, ref T behaviourField, ulong dirtyBit, ref NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour + { + if (GetSyncVarHookGuard(dirtyBit)) + return; + + uint newNetId = 0; + byte componentIndex = 0; + if (newBehaviour != null) + { + newNetId = newBehaviour.netId; + componentIndex = newBehaviour.ComponentIndex; + if (newNetId == 0) + { + Debug.LogWarning($"{nameof(SetSyncVarNetworkBehaviour)} NetworkIdentity {newBehaviour} has a zero netId. Maybe it is not spawned yet?"); + } + } + + syncField = new NetworkBehaviourSyncVar(newNetId, componentIndex); + + SetSyncVarDirtyBit(dirtyBit); + + // assign new one on the server, and in case we ever need it on client too + behaviourField = newBehaviour; + + // Debug.Log($"SetSyncVarNetworkBehaviour NetworkIdentity {GetType().Name} bit [{dirtyBit}] netIdField:{oldField}->{syncField}"); + } + + // helper function for [SyncVar] NetworkBehaviours. + // -> ref GameObject as second argument makes OnDeserialize processing easier + protected T GetSyncVarNetworkBehaviour(NetworkBehaviourSyncVar syncNetBehaviour, ref T behaviourField) where T : NetworkBehaviour + { + // server always uses the field + // if neither, fallback to original field + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3447 + if (isServer || !isClient) + { + return behaviourField; + } + + // client always looks up based on netId because objects might get in and out of range + // over and over again, which shouldn't null them forever + if (!NetworkClient.spawned.TryGetValue(syncNetBehaviour.netId, out NetworkIdentity identity)) + { + return null; + } + + // ensure componentIndex is in range. + // show explicit errors if something went wrong, instead of IndexOutOfRangeException. + // removing components at runtime isn't allowed, yet this happened in a project so we need to check for it. + if (syncNetBehaviour.componentIndex >= identity.NetworkBehaviours.Length) + { + Debug.LogError($"[SyncVar] {typeof(T)} on {name}'s {GetType()}: can't access {identity.name} NetworkBehaviour[{syncNetBehaviour.componentIndex}] because it only has {identity.NetworkBehaviours.Length} components.\nWas a NetworkBeahviour accidentally destroyed at runtime?"); + return null; + } + + behaviourField = identity.NetworkBehaviours[syncNetBehaviour.componentIndex] as T; + return behaviourField; + } + + protected static bool SyncVarEqual(T value, ref T fieldValue) + { + // newly initialized or changed value? + // value.Equals(fieldValue) allocates without 'where T : IEquatable' + // seems like we use EqualityComparer to avoid allocations, + // because not all SyncVars are IEquatable + return EqualityComparer.Default.Equals(value, fieldValue); + } + + // dirtyBit is a mask like 00010 + protected void SetSyncVar(T value, ref T fieldValue, ulong dirtyBit) + { + //Debug.Log($"SetSyncVar {GetType().Name} bit:{dirtyBit} fieldValue:{value}"); + SetSyncVarDirtyBit(dirtyBit); + fieldValue = value; + } + + /// Override to do custom serialization (instead of SyncVars/SyncLists). Use OnDeserialize too. + // if a class has syncvars, then OnSerialize/OnDeserialize are added + // automatically. + // + // initialState is true for full spawns, false for delta syncs. + // note: SyncVar hooks are only called when inital=false + public virtual void OnSerialize(NetworkWriter writer, bool initialState) + { + SerializeSyncObjects(writer, initialState); + SerializeSyncVars(writer, initialState); + } + + /// Override to do custom deserialization (instead of SyncVars/SyncLists). Use OnSerialize too. + public virtual void OnDeserialize(NetworkReader reader, bool initialState) + { + DeserializeSyncObjects(reader, initialState); + DeserializeSyncVars(reader, initialState); + } + + void SerializeSyncObjects(NetworkWriter writer, bool initialState) + { + // if initialState: write all SyncVars. + // otherwise write dirtyBits+dirty SyncVars + if (initialState) + SerializeObjectsAll(writer); + else + SerializeObjectsDelta(writer); + } + + void DeserializeSyncObjects(NetworkReader reader, bool initialState) + { + if (initialState) + { + DeserializeObjectsAll(reader); + } + else + { + DeserializeObjectsDelta(reader); + } + } + + // USED BY WEAVER + protected virtual void SerializeSyncVars(NetworkWriter writer, bool initialState) + { + // SyncVar are written here in subclass + + // if initialState + // write all SyncVars + // else + // write syncVarDirtyBits + // write dirty SyncVars + } + + // USED BY WEAVER + protected virtual void DeserializeSyncVars(NetworkReader reader, bool initialState) + { + // SyncVars are read here in subclass + + // if initialState + // read all SyncVars + // else + // read syncVarDirtyBits + // read dirty SyncVars + } + + public void SerializeObjectsAll(NetworkWriter writer) + { + for (int i = 0; i < syncObjects.Count; i++) + { + SyncObject syncObject = syncObjects[i]; + syncObject.OnSerializeAll(writer); + } + } + + public void SerializeObjectsDelta(NetworkWriter writer) + { + // write the mask + writer.WriteULong(syncObjectDirtyBits); + + // serializable objects, such as synclists + for (int i = 0; i < syncObjects.Count; i++) + { + // check dirty mask at nth bit + SyncObject syncObject = syncObjects[i]; + if ((syncObjectDirtyBits & (1UL << i)) != 0) + { + syncObject.OnSerializeDelta(writer); + } + } + } + + internal void DeserializeObjectsAll(NetworkReader reader) + { + for (int i = 0; i < syncObjects.Count; i++) + { + SyncObject syncObject = syncObjects[i]; + syncObject.OnDeserializeAll(reader); + } + } + + internal void DeserializeObjectsDelta(NetworkReader reader) + { + ulong dirty = reader.ReadULong(); + for (int i = 0; i < syncObjects.Count; i++) + { + // check dirty mask at nth bit + SyncObject syncObject = syncObjects[i]; + if ((dirty & (1UL << i)) != 0) + { + syncObject.OnDeserializeDelta(reader); + } + } + } + + // safely serialize each component in a way that one reading too much or + // too few bytes will show obvious, easy to resolve error messages. + // + // prevents the original UNET bug which started Mirror: + // https://github.com/vis2k/Mirror/issues/2617 + // where one component would read too much, and then all following reads + // on other entities would be mismatched, causing the weirdest errors. + // + // reads <> for 100% safety. + internal void Serialize(NetworkWriter writer, bool initialState) + { + // reserve length header to ensure the correct amount will be read. + // originally we used a 4 byte header (too bandwidth heavy). + // instead, let's "& 0xFF" the size. + // + // this is cleaner than barriers at the end of payload, because: + // - ensures the correct safety is read _before_ payload. + // - it's quite hard to break the check. + // a component would need to read/write the intented amount + // multiplied by 255 in order to miss the check. + // with barriers, reading 1 byte too much may still succeed if the + // next component's first byte matches the expected barrier. + // - we can still attempt to correct the invalid position via the + // safety length byte (we know that one is correct). + // + // it's just overall cleaner, and still low on bandwidth. + + // write placeholder length byte + // (jumping back later is WAY faster than allocating a temporary + // writer for the payload, then writing payload.size, payload) + int headerPosition = writer.Position; + writer.WriteByte(0); + int contentPosition = writer.Position; + + // write payload + try + { + // note this may not write anything if no syncIntervals elapsed + OnSerialize(writer, initialState); + } + catch (Exception e) + { + // show a detailed error and let the user know what went wrong + Debug.LogError($"OnSerialize failed for: object={name} component={GetType()} sceneId={netIdentity.sceneId:X}\n\n{e}"); + } + int endPosition = writer.Position; + + // fill in length hash as the last byte of the 4 byte length + writer.Position = headerPosition; + int size = endPosition - contentPosition; + byte safety = (byte)(size & 0xFF); + writer.WriteByte(safety); + writer.Position = endPosition; + + //Debug.Log($"OnSerializeSafely written for object {name} component:{GetType()} sceneId:{sceneId:X} header:{headerPosition} content:{contentPosition} end:{endPosition} contentSize:{endPosition - contentPosition}"); + } + + // correct the read size with the 1 byte length hash (by mischa). + // -> the component most likely read a few too many/few bytes. + // -> we know the correct last byte of the expected size (=the safety). + // -> attempt to reconstruct the size via safety byte. + // it will be correct unless someone wrote way way too much, + // as in > 255 bytes worth too much. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int ErrorCorrection(int size, byte safety) + { + // clear the last byte which most likely contains the error + uint cleared = (uint)size & 0xFFFFFF00; + + // insert the safety which we know to be correct + return (int)(cleared | safety); + } + + // returns false in case of errors. + // server needs to know in order to disconnect on error. + internal bool Deserialize(NetworkReader reader, bool initialState) + { + // detect errors, but attempt to correct before returning + bool result = true; + + // read 1 byte length hash safety & capture beginning for size check + byte safety = reader.ReadByte(); + int chunkStart = reader.Position; + + // call OnDeserialize and wrap it in a try-catch block so there's no + // way to mess up another component's deserialization + try + { + //Debug.Log($"OnDeserializeSafely: {name} component:{GetType()} sceneId:{sceneId:X} length:{contentSize}"); + OnDeserialize(reader, initialState); + } + catch (Exception e) + { + // show a detailed error and let the user know what went wrong + Debug.LogError($"OnDeserialize failed Exception={e.GetType()} (see below) object={name} component={GetType()} netId={netId}. Possible Reasons:\n" + + $" * Do {GetType()}'s OnSerialize and OnDeserialize calls write the same amount of data? \n" + + $" * Was there an exception in {GetType()}'s OnSerialize/OnDeserialize code?\n" + + $" * Are the server and client the exact same project?\n" + + $" * Maybe this OnDeserialize call was meant for another GameObject? The sceneIds can easily get out of sync if the Hierarchy was modified only in the client OR the server. Try rebuilding both.\n\n" + + $"Exception {e}"); + result = false; + } + + // compare bytes read with length hash + int size = reader.Position - chunkStart; + byte sizeHash = (byte)(size & 0xFF); + if (sizeHash != safety) + { + // warn the user. + Debug.LogWarning($"{name} (netId={netId}): {GetType()} OnDeserialize size mismatch. It read {size} bytes, which caused a size hash mismatch of {sizeHash:X2} vs. {safety:X2}. Make sure that OnSerialize and OnDeserialize write/read the same amount of data in all cases."); + + // attempt to fix the position, so the following components + // don't all fail. this is very likely to work, unless the user + // read more than 255 bytes too many / too few. + // + // see test: SerializationSizeMismatch. + int correctedSize = ErrorCorrection(size, safety); + reader.Position = chunkStart + correctedSize; + result = false; + } + + return result; + } + + internal void ResetSyncObjects() + { + foreach (SyncObject syncObject in syncObjects) + { + syncObject.Reset(); + } + } + + /// Like Start(), but only called on server and host. + public virtual void OnStartServer() {} + + /// Stop event, only called on server and host. + public virtual void OnStopServer() {} + + /// Like Start(), but only called on client and host. + public virtual void OnStartClient() {} + + /// Stop event, only called on client and host. + public virtual void OnStopClient() {} + + /// Like Start(), but only called on client and host for the local player object. + public virtual void OnStartLocalPlayer() {} + + /// Stop event, but only called on client and host for the local player object. + public virtual void OnStopLocalPlayer() {} + + /// Like Start(), but only called for objects the client has authority over. + public virtual void OnStartAuthority() {} + + /// Stop event, only called for objects the client has authority over. + public virtual void OnStopAuthority() {} + + // Weaver injects this into inheriting classes to return true. + // allows runtime & tests to check if a type was weaved. + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual bool Weaved() => false; + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkBehaviour.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkBehaviour.cs.meta new file mode 100644 index 0000000000..203c650546 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkBehaviour.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 655ee8cba98594f70880da5cc4dc442d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkBehaviour.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkBehaviourSyncVar.cs b/Assets/ImportedAssets/Mirror/Core/NetworkBehaviourSyncVar.cs new file mode 100644 index 0000000000..e9ed726388 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkBehaviourSyncVar.cs @@ -0,0 +1,33 @@ +using System; + +namespace Mirror +{ + // backing field for sync NetworkBehaviour + public struct NetworkBehaviourSyncVar : IEquatable + { + public uint netId; + // limited to 255 behaviours per identity + public byte componentIndex; + + public NetworkBehaviourSyncVar(uint netId, int componentIndex) : this() + { + this.netId = netId; + this.componentIndex = (byte)componentIndex; + } + + public bool Equals(NetworkBehaviourSyncVar other) + { + return other.netId == netId && other.componentIndex == componentIndex; + } + + public bool Equals(uint netId, int componentIndex) + { + return this.netId == netId && this.componentIndex == componentIndex; + } + + public override string ToString() + { + return $"[netId:{netId} compIndex:{componentIndex}]"; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkBehaviourSyncVar.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkBehaviourSyncVar.cs.meta new file mode 100644 index 0000000000..c6fe032a43 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkBehaviourSyncVar.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: b04fe7518657486089dfaf811db0b3ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkBehaviourSyncVar.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkClient.cs b/Assets/ImportedAssets/Mirror/Core/NetworkClient.cs new file mode 100644 index 0000000000..c8f01205cf --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkClient.cs @@ -0,0 +1,1855 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Mirror.RemoteCalls; +using UnityEngine; + +namespace Mirror +{ + public enum ConnectState + { + None, + // connecting between Connect() and OnTransportConnected() + Connecting, + Connected, + // disconnecting between Disconnect() and OnTransportDisconnected() + Disconnecting, + Disconnected + } + + /// NetworkClient with connection to server. + public static partial class NetworkClient + { + // time & value snapshot interpolation are separate. + // -> time is interpolated globally on NetworkClient / NetworkConnection + // -> value is interpolated per-component, i.e. NetworkTransform. + // however, both need to be on the same send interval. + // + // additionally, server & client need to use the same send interval. + // otherwise it's too easy to accidentally cause interpolation issues if + // a component sends with client.interval but interpolates with + // server.interval, etc. + public static int sendRate => NetworkServer.sendRate; + public static float sendInterval => sendRate < int.MaxValue ? 1f / sendRate : 0; // for 30 Hz, that's 33ms + static double lastSendTime; + + // For security, it is recommended to disconnect a player if a networked + // action triggers an exception\nThis could prevent components being + // accessed in an undefined state, which may be an attack vector for + // exploits. + // + // However, some games may want to allow exceptions in order to not + // interrupt the player's experience. + public static bool exceptionsDisconnect = true; // security by default + + // message handlers by messageId + internal static readonly Dictionary handlers = + new Dictionary(); + + /// All spawned NetworkIdentities by netId. + // client sees OBSERVED spawned ones. + public static readonly Dictionary spawned = + new Dictionary(); + + /// Client's NetworkConnection to server. + public static NetworkConnection connection { get; internal set; } + + /// True if client is ready (= joined world). + // TODO redundant state. point it to .connection.isReady instead (& test) + // TODO OR remove NetworkConnection.isReady? unless it's used on server + // + // TODO maybe ClientState.Connected/Ready/AddedPlayer/etc.? + // way better for security if we can check states in callbacks + public static bool ready; + + /// NetworkIdentity of the localPlayer + public static NetworkIdentity localPlayer { get; internal set; } + + // NetworkClient state + internal static ConnectState connectState = ConnectState.None; + + /// active is true while a client is connecting/connected either as standalone or as host client. + // (= while the network is active) + public static bool active => connectState == ConnectState.Connecting || + connectState == ConnectState.Connected; + + /// active is true while the client is connected in host mode. + // naming consistent with NetworkServer.activeHost. + public static bool activeHost => connection is LocalConnectionToServer; + + /// Check if client is connecting (before connected). + public static bool isConnecting => connectState == ConnectState.Connecting; + + /// Check if client is connected (after connecting). + public static bool isConnected => connectState == ConnectState.Connected; + + // OnConnected / OnDisconnected used to be NetworkMessages that were + // invoked. this introduced a bug where external clients could send + // Connected/Disconnected messages over the network causing undefined + // behaviour. + // => public so that custom NetworkManagers can hook into it + public static Action OnConnectedEvent; + public static Action OnDisconnectedEvent; + public static Action OnErrorEvent; + public static Action OnTransportExceptionEvent; + + /// Registered spawnable prefabs by assetId. + public static readonly Dictionary prefabs = + new Dictionary(); + + // custom spawn / unspawn handlers by assetId. + // useful to support prefab pooling etc.: + // https://mirror-networking.gitbook.io/docs/guides/gameobjects/custom-spawnfunctions + internal static readonly Dictionary spawnHandlers = + new Dictionary(); + internal static readonly Dictionary unspawnHandlers = + new Dictionary(); + + // spawning + // internal for tests + internal static bool isSpawnFinished; + + // Disabled scene objects that can be spawned again, by sceneId. + internal static readonly Dictionary spawnableObjects = + new Dictionary(); + + internal static Unbatcher unbatcher = new Unbatcher(); + + // interest management component (optional) + // only needed for SetHostVisibility + public static InterestManagementBase aoi; + + // scene loading + public static bool isLoadingScene; + + // connection quality + // this is set by a virtual function in NetworkManager, + // which allows users to overwrite it with their own estimations. + public static ConnectionQuality connectionQuality = ConnectionQuality.ESTIMATING; + public static ConnectionQuality lastConnectionQuality = ConnectionQuality.ESTIMATING; + public static ConnectionQualityMethod connectionQualityMethod = ConnectionQualityMethod.Simple; + public static float connectionQualityInterval = 3; + static double lastConnectionQualityUpdate; + + /// + /// Invoked when connection quality changes. + /// First argument is the old quality, second argument is the new quality. + /// + public static event Action onConnectionQualityChanged; + + // initialization ////////////////////////////////////////////////////// + static void AddTransportHandlers() + { + // community Transports may forget to call OnDisconnected. + // which could cause handlers to be added twice with +=. + // ensure we always clear the old ones first. + // fixes: https://github.com/vis2k/Mirror/issues/3152 + RemoveTransportHandlers(); + + // += so that other systems can also hook into it (i.e. statistics) + Transport.active.OnClientConnected += OnTransportConnected; + Transport.active.OnClientDataReceived += OnTransportData; + Transport.active.OnClientDisconnected += OnTransportDisconnected; + Transport.active.OnClientError += OnTransportError; + Transport.active.OnClientTransportException += OnTransportException; + } + + static void RemoveTransportHandlers() + { + // -= so that other systems can also hook into it (i.e. statistics) + Transport.active.OnClientConnected -= OnTransportConnected; + Transport.active.OnClientDataReceived -= OnTransportData; + Transport.active.OnClientDisconnected -= OnTransportDisconnected; + Transport.active.OnClientError -= OnTransportError; + Transport.active.OnClientTransportException -= OnTransportException; + } + + // connect ///////////////////////////////////////////////////////////// + // initialize is called before every connect + static void Initialize(bool hostMode) + { + // safety: ensure Weaving succeded. + // if it silently failed, we would get lots of 'writer not found' + // and other random errors at runtime instead. this is cleaner. + if (!WeaverFuse.Weaved()) + { + // if it failed, throw an exception to early exit all Connect calls. + throw new Exception("NetworkClient won't start because Weaving failed or didn't run."); + } + + // Debug.Log($"Client Connect: {address}"); + Debug.Assert(Transport.active != null, "There was no active transport when calling NetworkClient.Connect, If you are calling Connect manually then make sure to set 'Transport.active' first"); + + // reset unbatcher in case any batches from last session remain. + // need to do this in Initialize() so it runs for the host as well. + // fixes host mode scene transition receiving data from previous scene. + // credits: BigBoxVR + unbatcher = new Unbatcher(); + + // reset time interpolation on every new connect. + // ensures last sessions' state is cleared before starting again. + InitTimeInterpolation(); + + RegisterMessageHandlers(hostMode); + Transport.active.enabled = true; + } + + /// Connect client to a NetworkServer by address. + public static void Connect(string address) + { + Initialize(false); + + AddTransportHandlers(); + connectState = ConnectState.Connecting; + Transport.active.ClientConnect(address); + connection = new NetworkConnectionToServer(); + } + + /// Connect client to a NetworkServer by Uri. + public static void Connect(Uri uri) + { + Initialize(false); + + AddTransportHandlers(); + connectState = ConnectState.Connecting; + Transport.active.ClientConnect(uri); + connection = new NetworkConnectionToServer(); + } + + // TODO why are there two connect host methods? + // called from NetworkManager.FinishStartHost() + public static void ConnectHost() + { + Initialize(true); + connectState = ConnectState.Connected; + HostMode.SetupConnections(); + } + + // disconnect ////////////////////////////////////////////////////////// + /// Disconnect from server. + public static void Disconnect() + { + // only if connected or connecting. + // don't disconnect() again if already in the process of + // disconnecting or fully disconnected. + if (connectState != ConnectState.Connecting && + connectState != ConnectState.Connected) + return; + + // we are disconnecting until OnTransportDisconnected is called. + // setting state to Disconnected would stop OnTransportDisconnected + // from calling cleanup code because it would think we are already + // disconnected fully. + // TODO move to 'cleanup' code below if safe + connectState = ConnectState.Disconnecting; + ready = false; + + // call Disconnect on the NetworkConnection + connection?.Disconnect(); + + // IMPORTANT: do NOT clear connection here yet. + // we still need it in OnTransportDisconnected for callbacks. + // connection = null; + } + + // transport events //////////////////////////////////////////////////// + // called by Transport + static void OnTransportConnected() + { + if (connection != null) + { + // reset network time stats + NetworkTime.ResetStatics(); + + // the handler may want to send messages to the client + // thus we should set the connected state before calling the handler + connectState = ConnectState.Connected; + // ping right away after connecting so client gets new time asap + NetworkTime.SendPing(); + OnConnectedEvent?.Invoke(); + } + else Debug.LogError("Skipped Connect message handling because connection is null."); + } + + // helper function + static bool UnpackAndInvoke(NetworkReader reader, int channelId) + { + if (NetworkMessages.UnpackId(reader, out ushort msgType)) + { + // try to invoke the handler for that message + if (handlers.TryGetValue(msgType, out NetworkMessageDelegate handler)) + { + handler.Invoke(connection, reader, channelId); + + // message handler may disconnect client, making connection = null + // therefore must check for null to avoid NRE. + if (connection != null) + connection.lastMessageTime = Time.time; + + return true; + } + else + { + // message in a batch are NOT length prefixed to save bandwidth. + // every message needs to be handled and read until the end. + // otherwise it would overlap into the next message. + // => need to warn and disconnect to avoid undefined behaviour. + // => WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning($"Unknown message id: {msgType}. This can happen if no handler was registered for this message."); + // simply return false. caller is responsible for disconnecting. + //connection.Disconnect(); + return false; + } + } + else + { + // => WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning("Invalid message header."); + // simply return false. caller is responsible for disconnecting. + //connection.Disconnect(); + return false; + } + } + + // called by Transport + internal static void OnTransportData(ArraySegment data, int channelId) + { + if (connection != null) + { + // server might batch multiple messages into one packet. + // feed it to the Unbatcher. + // NOTE: we don't need to associate a channelId because we + // always process all messages in the batch. + if (!unbatcher.AddBatch(data)) + { + if (exceptionsDisconnect) + { + Debug.LogError($"NetworkClient: failed to add batch, disconnecting."); + connection.Disconnect(); + } + else + Debug.LogWarning($"NetworkClient: failed to add batch."); + + return; + } + + // process all messages in the batch. + // only while NOT loading a scene. + // if we get a scene change message, then we need to stop + // processing. otherwise we might apply them to the old scene. + // => fixes https://github.com/vis2k/Mirror/issues/2651 + // + // NOTE: is scene starts loading, then the rest of the batch + // would only be processed when OnTransportData is called + // the next time. + // => consider moving processing to NetworkEarlyUpdate. + while (!isLoadingScene && + unbatcher.GetNextMessage(out ArraySegment message, out double remoteTimestamp)) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message)) + { + // enough to read at least header size? + if (reader.Remaining >= NetworkMessages.IdSize) + { + // make remoteTimeStamp available to the user + connection.remoteTimeStamp = remoteTimestamp; + + // handle message + if (!UnpackAndInvoke(reader, channelId)) + { + // warn, disconnect and return if failed + // -> warning because attackers might send random data + // -> messages in a batch aren't length prefixed. + // failing to read one would cause undefined + // behaviour for every message afterwards. + // so we need to disconnect. + // -> return to avoid the below unbatches.count error. + // we already disconnected and handled it. + if (exceptionsDisconnect) + { + Debug.LogError($"NetworkClient: failed to unpack and invoke message. Disconnecting."); + connection.Disconnect(); + } + else + Debug.LogWarning($"NetworkClient: failed to unpack and invoke message."); + + return; + } + } + // otherwise disconnect + else + { + if (exceptionsDisconnect) + { + Debug.LogError($"NetworkClient: received Message was too short (messages should start with message id). Disconnecting."); + connection.Disconnect(); + } + else + Debug.LogWarning("NetworkClient: received Message was too short (messages should start with message id)"); + return; + } + } + } + + // if we weren't interrupted by a scene change, + // then all batched messages should have been processed now. + // if not, we need to log an error to avoid debugging hell. + // otherwise batches would silently grow. + // we need to log an error to avoid debugging hell. + // + // EXAMPLE: https://github.com/vis2k/Mirror/issues/2882 + // -> UnpackAndInvoke silently returned because no handler for id + // -> Reader would never be read past the end + // -> Batch would never be retired because end is never reached + // + // NOTE: prefixing every message in a batch with a length would + // avoid ever not reading to the end. for extra bandwidth. + // + // IMPORTANT: always keep this check to detect memory leaks. + // this took half a day to debug last time. + if (!isLoadingScene && unbatcher.BatchesCount > 0) + { + Debug.LogError($"Still had {unbatcher.BatchesCount} batches remaining after processing, even though processing was not interrupted by a scene change. This should never happen, as it would cause ever growing batches.\nPossible reasons:\n* A message didn't deserialize as much as it serialized\n*There was no message handler for a message id, so the reader wasn't read until the end."); + } + } + else Debug.LogError("Skipped Data message handling because connection is null."); + } + + // called by Transport + // IMPORTANT: often times when disconnecting, we call this from Mirror + // too because we want to remove the connection and handle + // the disconnect immediately. + // => which is fine as long as we guarantee it only runs once + // => which we do by setting the state to Disconnected! + internal static void OnTransportDisconnected() + { + // StopClient called from user code triggers Disconnected event + // from transport which calls StopClient again, so check here + // and short circuit running the Shutdown process twice. + if (connectState == ConnectState.Disconnected) return; + + // Raise the event before changing ConnectState + // because 'active' depends on this during shutdown + // + // previously OnDisconnected was only invoked if connection != null. + // however, if DNS resolve fails in Transport.Connect(), + // OnDisconnected would never be called because 'connection' is only + // created after the Transport.Connect() call. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3365 + OnDisconnectedEvent?.Invoke(); + + connectState = ConnectState.Disconnected; + ready = false; + snapshots.Clear(); + localTimeline = 0; + + // now that everything was handled, clear the connection. + // previously this was done in Disconnect() already, but we still + // need it for the above OnDisconnectedEvent. + connection?.Cleanup(); + connection = null; + + // transport handlers are only added when connecting. + // so only remove when actually disconnecting. + RemoveTransportHandlers(); + } + + // transport errors are forwarded to high level + static void OnTransportError(TransportError error, string reason) + { + // transport errors will happen. logging a warning is enough. + // make sure the user does not panic. + Debug.LogWarning($"Client Transport Error: {error}: {reason}. This is fine."); + OnErrorEvent?.Invoke(error, reason); + } + + static void OnTransportException(Exception exception) + { + // transport errors will happen. logging a warning is enough. + // make sure the user does not panic. + Debug.LogWarning($"Client Transport Exception: {exception}. This is fine."); + OnTransportExceptionEvent?.Invoke(exception); + } + + // send //////////////////////////////////////////////////////////////// + /// Send a NetworkMessage to the server over the given channel. + public static void Send(T message, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + if (connection != null) + { + if (connectState == ConnectState.Connected) + { + connection.Send(message, channelId); + } + else Debug.LogError("NetworkClient Send when not connected to a server"); + } + else Debug.LogError("NetworkClient Send with no connection"); + } + + // message handlers //////////////////////////////////////////////////// + internal static void RegisterMessageHandlers(bool hostMode) + { + // host mode client / remote client react to some messages differently. + // but we still need to add handlers for all of them to avoid + // 'message id not found' errors. + if (hostMode) + { + RegisterHandler(OnHostClientObjectDestroy); + RegisterHandler(OnHostClientObjectHide); + RegisterHandler(_ => { }, false); + RegisterHandler(OnHostClientSpawn); + // host mode doesn't need spawning + RegisterHandler(_ => { }); + // host mode doesn't need spawning + RegisterHandler(_ => { }); + // host mode doesn't need state updates + RegisterHandler(_ => { }); + } + else + { + RegisterHandler(OnObjectDestroy); + RegisterHandler(OnObjectHide); + RegisterHandler(NetworkTime.OnClientPong, false); + RegisterHandler(NetworkTime.OnClientPing, false); + RegisterHandler(OnSpawn); + RegisterHandler(OnObjectSpawnStarted); + RegisterHandler(OnObjectSpawnFinished); + RegisterHandler(OnEntityStateMessage); + } + + // These handlers are the same for host and remote clients + RegisterHandler(OnTimeSnapshotMessage); + RegisterHandler(OnChangeOwner); + RegisterHandler(OnRPCMessage); + } + + /// Register a handler for a message type T. Most should require authentication. + public static void RegisterHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + if (handlers.ContainsKey(msgType)) + { + Debug.LogWarning($"NetworkClient.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning."); + } + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + // we use the same WrapHandler function for server and client. + // so let's wrap it to ignore the NetworkConnection parameter. + // it's not needed on client. it's always NetworkClient.connection. + void HandlerWrapped(NetworkConnection _, T value) => handler(value); + handlers[msgType] = NetworkMessages.WrapHandler((Action)HandlerWrapped, requireAuthentication, exceptionsDisconnect); + } + + /// Register a handler for a message type T. Most should require authentication. + // This version passes channelId to the handler. + public static void RegisterHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + if (handlers.ContainsKey(msgType)) + { + Debug.LogWarning($"NetworkClient.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning."); + } + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + // we use the same WrapHandler function for server and client. + // so let's wrap it to ignore the NetworkConnection parameter. + // it's not needed on client. it's always NetworkClient.connection. + void HandlerWrapped(NetworkConnection _, T value, int channelId) => handler(value, channelId); + handlers[msgType] = NetworkMessages.WrapHandler((Action)HandlerWrapped, requireAuthentication, exceptionsDisconnect); + } + + // Deprecated 2024-01-21 + [Obsolete("Use ReplaceHandler without the NetworkConnection parameter instead. This version is obsolete and will be removed soon.")] + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + // we use the same WrapHandler function for server and client. + // so let's wrap it to ignore the NetworkConnection parameter. + // it's not needed on client. it's always NetworkClient.connection. + ushort msgType = NetworkMessageId.Id; + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + void HandlerWrapped(NetworkConnection _, T value) => handler(_, value); + handlers[msgType] = NetworkMessages.WrapHandler((Action)HandlerWrapped, requireAuthentication, exceptionsDisconnect); + } + + /// Replace a handler for a particular message type. Should require authentication by default. + // RegisterHandler throws a warning (as it should) if a handler is assigned twice + // Use of ReplaceHandler makes it clear the user intended to replace the handler + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + // we use the same WrapHandler function for server and client. + // so let's wrap it to ignore the NetworkConnection parameter. + // it's not needed on client. it's always NetworkClient.connection. + ushort msgType = NetworkMessageId.Id; + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + void HandlerWrapped(NetworkConnection _, T value) => handler(value); + handlers[msgType] = NetworkMessages.WrapHandler((Action)HandlerWrapped, requireAuthentication, exceptionsDisconnect); + } + + /// Replace a handler for a particular message type. Should require authentication by default. This version passes channelId to the handler. + // RegisterHandler throws a warning (as it should) if a handler is assigned twice + // Use of ReplaceHandler makes it clear the user intended to replace the handler + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + // we use the same WrapHandler function for server and client. + // so let's wrap it to ignore the NetworkConnection parameter. + // it's not needed on client. it's always NetworkClient.connection. + ushort msgType = NetworkMessageId.Id; + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + void HandlerWrapped(NetworkConnection _, T value, int channelId) => handler(value, channelId); + handlers[msgType] = NetworkMessages.WrapHandler((Action)HandlerWrapped, requireAuthentication, exceptionsDisconnect); + } + + /// Unregister a message handler of type T. + public static bool UnregisterHandler() + where T : struct, NetworkMessage + { + // use int to minimize collisions + ushort msgType = NetworkMessageId.Id; + return handlers.Remove(msgType); + } + + // spawnable prefabs /////////////////////////////////////////////////// + /// Find the registered prefab for this asset id. + // Useful for debuggers + public static bool GetPrefab(uint assetId, out GameObject prefab) + { + prefab = null; + return assetId != 0 && + prefabs.TryGetValue(assetId, out prefab) && + prefab != null; + } + + /// Validates Prefab then adds it to prefabs dictionary. + static void RegisterPrefabIdentity(NetworkIdentity prefab) + { + if (prefab.assetId == 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead"); + return; + } + + if (prefab.sceneId != 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene."); + return; + } + + // disallow child NetworkIdentities. + // TODO likely not necessary anymore due to the new check in + // NetworkIdentity.OnValidate. + NetworkIdentity[] identities = prefab.GetComponentsInChildren(); + if (identities.Length > 1) + { + Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object."); + } + + if (prefabs.ContainsKey(prefab.assetId)) + { + GameObject existingPrefab = prefabs[prefab.assetId]; + Debug.LogWarning($"Replacing existing prefab with assetId '{prefab.assetId}'. Old prefab '{existingPrefab.name}', New prefab '{prefab.name}'"); + } + + if (spawnHandlers.ContainsKey(prefab.assetId) || unspawnHandlers.ContainsKey(prefab.assetId)) + { + Debug.LogWarning($"Adding prefab '{prefab.name}' with assetId '{prefab.assetId}' when spawnHandlers with same assetId already exists. If you want to use custom spawn handling, then remove the prefab from NetworkManager's registered prefabs first."); + } + + // Debug.Log($"Registering prefab '{prefab.name}' as asset:{prefab.assetId}"); + + prefabs[prefab.assetId] = prefab.gameObject; + } + + /// Register spawnable prefab with custom assetId. + // Note: newAssetId can not be set on GameObjects that already have an assetId + // Note: registering with assetId is useful for assetbundles etc. a lot + // of people use this. + public static void RegisterPrefab(GameObject prefab, uint newAssetId) + { + if (prefab == null) + { + Debug.LogError("Could not register prefab because it was null"); + return; + } + + if (newAssetId == 0) + { + Debug.LogError($"Could not register '{prefab.name}' with new assetId because the new assetId was empty"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + if (identity.assetId != 0 && identity.assetId != newAssetId) + { + Debug.LogError($"Could not register '{prefab.name}' to {newAssetId} because it already had an AssetId, Existing assetId {identity.assetId}"); + return; + } + + identity.assetId = newAssetId; + + RegisterPrefabIdentity(identity); + } + + /// Register spawnable prefab. + public static void RegisterPrefab(GameObject prefab) + { + if (prefab == null) + { + Debug.LogError("Could not register prefab because it was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + RegisterPrefabIdentity(identity); + } + + /// Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers. + // Note: newAssetId can not be set on GameObjects that already have an assetId + // Note: registering with assetId is useful for assetbundles etc. a lot + // of people use this. + // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate? + public static void RegisterPrefab(GameObject prefab, uint newAssetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + // We need this check here because we don't want a null handler in the lambda expression below + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {newAssetId}"); + return; + } + + RegisterPrefab(prefab, newAssetId, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler); + } + + /// Register a spawnable prefab with custom spawn/unspawn handlers. + // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate? + public static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (prefab == null) + { + Debug.LogError("Could not register handler for prefab because the prefab was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + if (identity.sceneId != 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene."); + return; + } + + if (identity.assetId == 0) + { + Debug.LogError($"Can not Register handler for '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead"); + return; + } + + // We need this check here because we don't want a null handler in the lambda expression below + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {identity.assetId}"); + return; + } + + RegisterPrefab(prefab, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler); + } + + /// Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers. + // Note: newAssetId can not be set on GameObjects that already have an assetId + // Note: registering with assetId is useful for assetbundles etc. a lot + // of people use this. + // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate? + public static void RegisterPrefab(GameObject prefab, uint newAssetId, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (newAssetId == 0) + { + Debug.LogError($"Could not register handler for '{prefab.name}' with new assetId because the new assetId was empty"); + return; + } + + if (prefab == null) + { + Debug.LogError("Could not register handler for prefab because the prefab was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + if (identity.assetId != 0 && identity.assetId != newAssetId) + { + Debug.LogError($"Could not register Handler for '{prefab.name}' to {newAssetId} because it already had an AssetId, Existing assetId {identity.assetId}"); + return; + } + + if (identity.sceneId != 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene."); + return; + } + + identity.assetId = newAssetId; + uint assetId = identity.assetId; + + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {assetId}"); + return; + } + + if (unspawnHandler == null) + { + Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}"); + return; + } + + if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId)) + { + Debug.LogWarning($"Replacing existing spawnHandlers for prefab '{prefab.name}' with assetId '{assetId}'"); + } + + if (prefabs.ContainsKey(assetId)) + { + // this is error because SpawnPrefab checks prefabs before handler + Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}', unregister the prefab first before trying to add handler"); + } + + NetworkIdentity[] identities = prefab.GetComponentsInChildren(); + if (identities.Length > 1) + { + Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object."); + } + + //Debug.Log($"Registering custom prefab {prefab.name} as asset:{assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}"); + + spawnHandlers[assetId] = spawnHandler; + unspawnHandlers[assetId] = unspawnHandler; + } + + /// Register a spawnable prefab with custom spawn/unspawn handlers. + // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate? + public static void RegisterPrefab(GameObject prefab, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (prefab == null) + { + Debug.LogError("Could not register handler for prefab because the prefab was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + if (identity.sceneId != 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene."); + return; + } + + uint assetId = identity.assetId; + + if (assetId == 0) + { + Debug.LogError($"Can not Register handler for '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead"); + return; + } + + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {assetId}"); + return; + } + + if (unspawnHandler == null) + { + Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}"); + return; + } + + if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId)) + { + Debug.LogWarning($"Replacing existing spawnHandlers for prefab '{prefab.name}' with assetId '{assetId}'"); + } + + if (prefabs.ContainsKey(assetId)) + { + // this is error because SpawnPrefab checks prefabs before handler + Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}', unregister the prefab first before trying to add handler"); + } + + NetworkIdentity[] identities = prefab.GetComponentsInChildren(); + if (identities.Length > 1) + { + Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object."); + } + + //Debug.Log($"Registering custom prefab {prefab.name} as asset:{assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}"); + + spawnHandlers[assetId] = spawnHandler; + unspawnHandlers[assetId] = unspawnHandler; + } + + /// Removes a registered spawn prefab that was setup with NetworkClient.RegisterPrefab. + public static void UnregisterPrefab(GameObject prefab) + { + if (prefab == null) + { + Debug.LogError("Could not unregister prefab because it was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not unregister '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + uint assetId = identity.assetId; + + prefabs.Remove(assetId); + spawnHandlers.Remove(assetId); + unspawnHandlers.Remove(assetId); + } + + // spawn handlers ////////////////////////////////////////////////////// + /// This is an advanced spawning function that registers a custom assetId with the spawning system. + // This can be used to register custom spawning methods for an assetId - + // instead of the usual method of registering spawning methods for a + // prefab. This should be used when no prefab exists for the spawned + // objects - such as when they are constructed dynamically at runtime + // from configuration data. + public static void RegisterSpawnHandler(uint assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + // We need this check here because we don't want a null handler in the lambda expression below + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {assetId}"); + return; + } + + RegisterSpawnHandler(assetId, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler); + } + + /// This is an advanced spawning function that registers a custom assetId with the spawning system. + // This can be used to register custom spawning methods for an assetId - + // instead of the usual method of registering spawning methods for a + // prefab. This should be used when no prefab exists for the spawned + // objects - such as when they are constructed dynamically at runtime + // from configuration data. + public static void RegisterSpawnHandler(uint assetId, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {assetId}"); + return; + } + + if (unspawnHandler == null) + { + Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}"); + return; + } + + if (assetId == 0) + { + Debug.LogError("Can not Register SpawnHandler for empty assetId"); + return; + } + + if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId)) + { + Debug.LogWarning($"Replacing existing spawnHandlers for {assetId}"); + } + + if (prefabs.ContainsKey(assetId)) + { + // this is error because SpawnPrefab checks prefabs before handler + Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}'"); + } + + // Debug.Log("RegisterSpawnHandler asset {assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}"); + + spawnHandlers[assetId] = spawnHandler; + unspawnHandlers[assetId] = unspawnHandler; + } + + /// Removes a registered spawn handler function that was registered with NetworkClient.RegisterHandler(). + public static void UnregisterSpawnHandler(uint assetId) + { + spawnHandlers.Remove(assetId); + unspawnHandlers.Remove(assetId); + } + + /// This clears the registered spawn prefabs and spawn handler functions for this client. + public static void ClearSpawners() + { + prefabs.Clear(); + spawnHandlers.Clear(); + unspawnHandlers.Clear(); + } + + internal static bool InvokeUnSpawnHandler(uint assetId, GameObject obj) + { + if (unspawnHandlers.TryGetValue(assetId, out UnSpawnDelegate handler) && handler != null) + { + handler(obj); + return true; + } + return false; + } + + // ready /////////////////////////////////////////////////////////////// + /// Sends Ready message to server, indicating that we loaded the scene, ready to enter the game. + // This could be for example when a client enters an ongoing game and + // has finished loading the current scene. The server should respond to + // the SYSTEM_READY event with an appropriate handler which instantiates + // the players object for example. + public static bool Ready() + { + // Debug.Log($"NetworkClient.Ready() called with connection {conn}"); + if (ready) + { + Debug.LogError("NetworkClient is already ready. It shouldn't be called twice."); + return false; + } + + // need a valid connection to become ready + if (connection == null) + { + Debug.LogError("Ready() called with invalid connection object: conn=null"); + return false; + } + + // Set these before sending the ReadyMessage, otherwise host client + // will fail in InternalAddPlayer with null readyConnection. + // TODO this is redundant. have one source of truth for .ready + ready = true; + connection.isReady = true; + + // Tell server we're ready to have a player object spawned + connection.Send(new ReadyMessage()); + return true; + } + + // add player ////////////////////////////////////////////////////////// + // called from message handler for Owner message + internal static void InternalAddPlayer(NetworkIdentity identity) + { + //Debug.Log("NetworkClient.InternalAddPlayer"); + + // NOTE: It can be "normal" when changing scenes for the player to be destroyed and recreated. + // But, the player structures are not cleaned up, we'll just replace the old player + localPlayer = identity; + + // NOTE: we DONT need to set isClient=true here, because OnStartClient + // is called before OnStartLocalPlayer, hence it's already set. + // localPlayer.isClient = true; + + // TODO this check might not be necessary + //if (readyConnection != null) + if (ready && connection != null) + { + connection.identity = identity; + } + else Debug.LogWarning("NetworkClient can't AddPlayer before being ready. Please call NetworkClient.Ready() first. Clients are considered ready after joining the game world."); + } + + /// Sends AddPlayer message to the server, indicating that we want to join the world. + public static bool AddPlayer() + { + // ensure valid ready connection + if (connection == null) + { + Debug.LogError("AddPlayer requires a valid NetworkClient.connection."); + return false; + } + + // UNET checked 'if readyConnection != null'. + // in other words, we need a connection and we need to be ready. + if (!ready) + { + Debug.LogError("AddPlayer requires a ready NetworkClient."); + return false; + } + + if (connection.identity != null) + { + Debug.LogError("NetworkClient.AddPlayer: a PlayerController was already added. Did you call AddPlayer twice?"); + return false; + } + + // Debug.Log($"NetworkClient.AddPlayer() called with connection {readyConnection}"); + connection.Send(new AddPlayerMessage()); + return true; + } + + // spawning //////////////////////////////////////////////////////////// + internal static void ApplySpawnPayload(NetworkIdentity identity, SpawnMessage message) + { + if (message.assetId != 0) + identity.assetId = message.assetId; + + if (!identity.gameObject.activeSelf) + { + identity.gameObject.SetActive(true); + } + + // apply local values for VR support + identity.transform.localPosition = message.position; + identity.transform.localRotation = message.rotation; + identity.transform.localScale = message.scale; + + // configure flags + // the below DeserializeClient call invokes SyncVarHooks. + // flags always need to be initialized before that. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3259 + identity.isOwned = message.isOwner; + identity.netId = message.netId; + + if (message.isLocalPlayer) + InternalAddPlayer(identity); + + // configure isClient/isLocalPlayer flags. + // => after InternalAddPlayer. can't initialize .isLocalPlayer + // before InternalAddPlayer sets .localPlayer + // => before DeserializeClient, otherwise SyncVar hooks wouldn't + // have isClient/isLocalPlayer set yet. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3259 + InitializeIdentityFlags(identity); + + // deserialize components if any payload + // (Count is 0 if there were no components) + if (message.payload.Count > 0) + { + using (NetworkReaderPooled payloadReader = NetworkReaderPool.Get(message.payload)) + { + identity.DeserializeClient(payloadReader, true); + } + } + + spawned[message.netId] = identity; + if (identity.isOwned) connection?.owned.Add(identity); + + // the initial spawn with OnObjectSpawnStarted/Finished calls all + // object's OnStartClient/OnStartLocalPlayer after they were all + // spawned. + // this only happens once though. + // for all future spawns, we need to call OnStartClient/LocalPlayer + // here immediately since there won't be another OnObjectSpawnFinished. + if (isSpawnFinished) + { + InvokeIdentityCallbacks(identity); + } + } + + // Finds Existing Object with NetId or spawns a new one using AssetId or sceneId + internal static bool FindOrSpawnObject(SpawnMessage message, out NetworkIdentity identity) + { + // was the object already spawned? + identity = GetExistingObject(message.netId); + + // if found, return early + if (identity != null) + { + return true; + } + + if (message.assetId == 0 && message.sceneId == 0) + { + Debug.LogError($"OnSpawn message with netId '{message.netId}' has no AssetId or sceneId"); + return false; + } + + identity = message.sceneId == 0 ? SpawnPrefab(message) : SpawnSceneObject(message.sceneId); + + if (identity == null) + { + Debug.LogError($"Could not spawn assetId={message.assetId} scene={message.sceneId:X} netId={message.netId}"); + return false; + } + + return true; + } + + static NetworkIdentity GetExistingObject(uint netid) + { + spawned.TryGetValue(netid, out NetworkIdentity identity); + return identity; + } + + static NetworkIdentity SpawnPrefab(SpawnMessage message) + { + // custom spawn handler for this prefab? (for prefab pools etc.) + // + // IMPORTANT: look for spawn handlers BEFORE looking for registered + // prefabs. Unspawning also looks for unspawn handlers + // before falling back to regular Destroy. this needs to + // be consistent. + // https://github.com/vis2k/Mirror/issues/2705 + if (spawnHandlers.TryGetValue(message.assetId, out SpawnHandlerDelegate handler)) + { + GameObject obj = handler(message); + if (obj == null) + { + Debug.LogError($"Spawn Handler returned null, Handler assetId '{message.assetId}'"); + return null; + } + + if (!obj.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Object Spawned by handler did not have a NetworkIdentity, Handler assetId '{message.assetId}'"); + return null; + } + + return identity; + } + + // otherwise look in NetworkManager registered prefabs + if (GetPrefab(message.assetId, out GameObject prefab)) + { + GameObject obj = GameObject.Instantiate(prefab, message.position, message.rotation); + //Debug.Log($"Client spawn handler instantiating [netId{message.netId} asset ID:{message.assetId} pos:{message.position} rotation:{message.rotation}]"); + return obj.GetComponent(); + } + + Debug.LogError($"Failed to spawn server object, did you forget to add it to the NetworkManager? assetId={message.assetId} netId={message.netId}"); + return null; + } + + static NetworkIdentity SpawnSceneObject(ulong sceneId) + { + NetworkIdentity identity = GetAndRemoveSceneObject(sceneId); + if (identity == null) + { + Debug.LogError($"Spawn scene object not found for {sceneId:X}. Make sure that client and server use exactly the same project. This only happens if the hierarchy gets out of sync."); + + // dump the whole spawnable objects dict for easier debugging + //foreach (KeyValuePair kvp in spawnableObjects) + // Debug.Log($"Spawnable: SceneId={kvp.Key:X} name={kvp.Value.name}"); + } + //else Debug.Log($"Client spawn for [netId:{msg.netId}] [sceneId:{msg.sceneId:X}] obj:{identity}"); + return identity; + } + + static NetworkIdentity GetAndRemoveSceneObject(ulong sceneId) + { + if (spawnableObjects.TryGetValue(sceneId, out NetworkIdentity identity)) + { + spawnableObjects.Remove(sceneId); + return identity; + } + return null; + } + + /// Call this after loading/unloading a scene in the client after connection to register the spawnable objects + public static void PrepareToSpawnSceneObjects() + { + // remove existing items, they will be re-added below + spawnableObjects.Clear(); + + // finds all NetworkIdentity currently loaded by unity (includes disabled objects) + NetworkIdentity[] allIdentities = Resources.FindObjectsOfTypeAll(); + foreach (NetworkIdentity identity in allIdentities) + { + // add all unspawned NetworkIdentities to spawnable objects + // need to check netId to make sure object is not spawned + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3541 + // PrepareToSpawnSceneObjects may be called multiple times in case + // the ObjectSpawnStarted message is received multiple times. + if (Utils.IsSceneObject(identity) && + identity.netId == 0) + { + if (spawnableObjects.TryGetValue(identity.sceneId, out NetworkIdentity existingIdentity)) + { + string msg = $"NetworkClient: Duplicate sceneId {identity.sceneId} detected on {identity.gameObject.name} and {existingIdentity.gameObject.name}\n" + + $"This can happen if a networked object is persisted in DontDestroyOnLoad through loading / changing to the scene where it originated,\n" + + $"otherwise you may need to open and re-save the {identity.gameObject.scene} to reset scene id's."; + Debug.LogWarning(msg, identity.gameObject); + } + else + { + spawnableObjects.Add(identity.sceneId, identity); + } + } + } + } + + internal static void OnObjectSpawnStarted(ObjectSpawnStartedMessage _) + { + // Debug.Log("SpawnStarted"); + PrepareToSpawnSceneObjects(); + isSpawnFinished = false; + } + + internal static void OnObjectSpawnFinished(ObjectSpawnFinishedMessage _) + { + // paul: Initialize the objects in the same order as they were + // initialized in the server. This is important if spawned objects + // use data from scene objects + foreach (NetworkIdentity identity in spawned.Values.OrderBy(uv => uv.netId)) + { + // NetworkIdentities should always be removed from .spawned when + // they are destroyed. for safety, let's double check here. + if (identity != null) + { + BootstrapIdentity(identity); + } + else Debug.LogWarning("Found null entry in NetworkClient.spawned. This is unexpected. Was the NetworkIdentity not destroyed properly?"); + } + isSpawnFinished = true; + } + + // host mode callbacks ///////////////////////////////////////////////// + static void OnHostClientObjectDestroy(ObjectDestroyMessage message) + { + //Debug.Log($"NetworkClient.OnLocalObjectObjDestroy netId:{message.netId}"); + + // remove from owned (if any) + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity)) + connection.owned.Remove(identity); + + spawned.Remove(message.netId); + } + + static void OnHostClientObjectHide(ObjectHideMessage message) + { + //Debug.Log($"ClientScene::OnLocalObjectObjHide netId:{message.netId}"); + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity) && + identity != null) + { + if (aoi != null) + aoi.SetHostVisibility(identity, false); + } + } + + internal static void OnHostClientSpawn(SpawnMessage message) + { + // on host mode, the object already exist in NetworkServer.spawned. + // simply add it to NetworkClient.spawned too. + if (NetworkServer.spawned.TryGetValue(message.netId, out NetworkIdentity identity) && identity != null) + { + spawned[message.netId] = identity; + if (message.isOwner) connection.owned.Add(identity); + + // now do the actual 'spawning' on host mode + if (message.isLocalPlayer) + InternalAddPlayer(identity); + + // set visibility before invoking OnStartClient etc. callbacks + if (aoi != null) + aoi.SetHostVisibility(identity, true); + + identity.isOwned = message.isOwner; + BootstrapIdentity(identity); + } + } + + // client-only mode callbacks ////////////////////////////////////////// + static void OnEntityStateMessage(EntityStateMessage message) + { + // Debug.Log($"NetworkClient.OnUpdateVarsMessage {msg.netId}"); + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity) && identity != null) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message.payload)) + identity.DeserializeClient(reader, false); + } + else Debug.LogWarning($"Did not find target for sync message for {message.netId}. Were all prefabs added to the NetworkManager's spawnable list?\nNote: this can be completely normal because UDP messages may arrive out of order, so this message might have arrived after a Destroy message."); + } + + static void OnRPCMessage(RpcMessage message) + { + // Debug.Log($"NetworkClient.OnRPCMessage hash:{message.functionHash} netId:{message.netId}"); + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity)) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message.payload)) + identity.HandleRemoteCall(message.componentIndex, message.functionHash, RemoteCallType.ClientRpc, reader); + } + // Rpcs often can't be applied if interest management unspawned them + } + + static void OnObjectHide(ObjectHideMessage message) => DestroyObject(message.netId); + + internal static void OnObjectDestroy(ObjectDestroyMessage message) => DestroyObject(message.netId); + + internal static void OnSpawn(SpawnMessage message) + { + // Debug.Log($"Client spawn handler instantiating netId={msg.netId} assetID={msg.assetId} sceneId={msg.sceneId:X} pos={msg.position}"); + if (FindOrSpawnObject(message, out NetworkIdentity identity)) + { + ApplySpawnPayload(identity, message); + } + } + + internal static void OnChangeOwner(ChangeOwnerMessage message) + { + NetworkIdentity identity = GetExistingObject(message.netId); + + if (identity != null) + ChangeOwner(identity, message); + else + Debug.LogError($"OnChangeOwner: Could not find object with netId {message.netId}"); + } + + // ChangeOwnerMessage contains new 'owned' and new 'localPlayer' + // that we need to apply to the identity. + internal static void ChangeOwner(NetworkIdentity identity, ChangeOwnerMessage message) + { + // local player before, but not anymore? + // call OnStopLocalPlayer before setting new values. + if (identity.isLocalPlayer && !message.isLocalPlayer) + { + identity.OnStopLocalPlayer(); + } + + // set ownership flag (aka authority) + identity.isOwned = message.isOwner; + + // Add / Remove to client's connectionToServer.owned hashset. + if (identity.isOwned) + connection?.owned.Add(identity); + else + connection?.owned.Remove(identity); + + // Call OnStartAuthority / OnStopAuthority + identity.NotifyAuthority(); + + // set localPlayer flag + identity.isLocalPlayer = message.isLocalPlayer; + + // identity is now local player. set our static helper field to it. + if (identity.isLocalPlayer) + { + localPlayer = identity; + identity.connectionToServer = connection; + identity.OnStartLocalPlayer(); + } + // identity's isLocalPlayer was set to false. + // clear our static localPlayer IF (and only IF) it was that one before. + else if (localPlayer == identity) + { + localPlayer = null; + // TODO set .connectionToServer to null for old local player? + // since we set it in the above 'if' case too. + } + } + + // set up NetworkIdentity flags on the client. + // needs to be separate from invoking callbacks. + // cleaner, and some places need to set flags first. + static void InitializeIdentityFlags(NetworkIdentity identity) + { + // initialize flags before invoking callbacks. + // this way isClient/isLocalPlayer is correct during callbacks. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3362 + identity.isClient = true; + identity.isLocalPlayer = localPlayer == identity; + + // .connectionToServer is only available for local players. + // set it here, before invoking any callbacks. + // this way it's available in _all_ callbacks. + if (identity.isLocalPlayer) + identity.connectionToServer = connection; + } + + // invoke NetworkIdentity callbacks on the client. + // needs to be separate from configuring flags. + // cleaner, and some places need to set flags first. + static void InvokeIdentityCallbacks(NetworkIdentity identity) + { + // invoke OnStartAuthority + identity.NotifyAuthority(); + + // invoke OnStartClient + identity.OnStartClient(); + + // invoke OnStartLocalPlayer + if (identity.isLocalPlayer) + identity.OnStartLocalPlayer(); + } + + // configure flags & invoke callbacks + static void BootstrapIdentity(NetworkIdentity identity) + { + InitializeIdentityFlags(identity); + InvokeIdentityCallbacks(identity); + } + + // broadcast /////////////////////////////////////////////////////////// + static void BroadcastTimeSnapshot() + { + Send(new TimeSnapshotMessage(), Channels.Unreliable); + } + + // make sure Broadcast() is only called every sendInterval. + // calling it every update() would require too much bandwidth. + static void Broadcast() + { + // joined the world yet? + if (!connection.isReady) return; + + // nothing to do in host mode. server already knows the state. + if (NetworkServer.active) return; + + // send time snapshot every sendInterval. + BroadcastTimeSnapshot(); + + // for each entity that the client owns + foreach (NetworkIdentity identity in connection.owned) + { + // make sure it's not null or destroyed. + // (which can happen if someone uses + // GameObject.Destroy instead of + // NetworkServer.Destroy) + if (identity != null) + { + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // get serialization for this entity viewed by this connection + // (if anything was serialized this time) + identity.SerializeClient(writer); + if (writer.Position > 0) + { + // send state update message + EntityStateMessage message = new EntityStateMessage + { + netId = identity.netId, + payload = writer.ToArraySegment() + }; + Send(message); + } + } + } + // spawned list should have no null entries because we + // always call Remove in OnObjectDestroy everywhere. + // if it does have null then we missed something. + else Debug.LogWarning($"Found 'null' entry in owned list for client. This is unexpected behaviour."); + } + } + + // update ////////////////////////////////////////////////////////////// + // NetworkEarlyUpdate called before any Update/FixedUpdate + // (we add this to the UnityEngine in NetworkLoop) + internal static void NetworkEarlyUpdate() + { + // process all incoming messages first before updating the world + if (Transport.active != null) + Transport.active.ClientEarlyUpdate(); + + // time snapshot interpolation + UpdateTimeInterpolation(); + } + + // NetworkLateUpdate called after any Update/FixedUpdate/LateUpdate + // (we add this to the UnityEngine in NetworkLoop) + internal static void NetworkLateUpdate() + { + // broadcast ClientToServer components while active + if (active) + { + // broadcast every sendInterval. + // AccurateInterval to avoid update frequency inaccuracy issues: + // https://github.com/vis2k/Mirror/pull/3153 + // + // for example, host mode server doesn't set .targetFrameRate. + // Broadcast() would be called every tick. + // snapshots might be sent way too often, etc. + // + // during tests, we always call Broadcast() though. + // + // also important for syncInterval=0 components like + // NetworkTransform, so they can sync on same interval as time + // snapshots _but_ not every single tick. + // + // Unity 2019 doesn't have Time.timeAsDouble yet + if (!Application.isPlaying || + AccurateInterval.Elapsed(NetworkTime.localTime, sendInterval, ref lastSendTime)) + { + Broadcast(); + } + + UpdateConnectionQuality(); + } + + // Connection Quality ////////////////////////////////////////////////// + // uses 'pragmatic' version based on snapshot interpolation by default. + void UpdateConnectionQuality() + { + // only recalculate every few seconds + // we don't want to fire Good->Bad->Good->Bad dozens of times per second. + if (connectionQualityInterval > 0 && NetworkTime.time > lastConnectionQualityUpdate + connectionQualityInterval) + { + lastConnectionQualityUpdate = NetworkTime.time; + + switch (connectionQualityMethod) + { + case ConnectionQualityMethod.Simple: + connectionQuality = ConnectionQualityHeuristics.Simple(NetworkTime.rtt, NetworkTime.rttVariance); + break; + case ConnectionQualityMethod.Pragmatic: + connectionQuality = ConnectionQualityHeuristics.Pragmatic(initialBufferTime, bufferTime); + break; + } + + if (lastConnectionQuality != connectionQuality) + { + // Invoke the event before assigning the new value so + // the event handler can compare old and new values. + onConnectionQualityChanged?.Invoke(lastConnectionQuality, connectionQuality); + lastConnectionQuality = connectionQuality; + } + } + } + + // update connections to flush out messages _after_ broadcast + // local connection? + if (connection is LocalConnectionToServer localConnection) + { + localConnection.Update(); + } + // remote connection? + else if (connection is NetworkConnectionToServer remoteConnection) + { + // only update things while connected + if (active && connectState == ConnectState.Connected) + { + // update NetworkTime + NetworkTime.UpdateClient(); + + // update connection to flush out batched messages + remoteConnection.Update(); + } + } + + // process all outgoing messages after updating the world + if (Transport.active != null) + Transport.active.ClientLateUpdate(); + } + + // destroy ///////////////////////////////////////////////////////////// + /// Destroys all networked objects on the client. + // Note: NetworkServer.CleanupNetworkIdentities does the same on server. + public static void DestroyAllClientObjects() + { + // user can modify spawned lists which causes InvalidOperationException + // list can modified either in UnSpawnHandler or in OnDisable/OnDestroy + // we need the Try/Catch so that the rest of the shutdown does not get stopped + try + { + foreach (NetworkIdentity identity in spawned.Values) + { + if (identity != null && identity.gameObject != null) + { + if (identity.isLocalPlayer) + identity.OnStopLocalPlayer(); + + identity.OnStopClient(); + + // NetworkClient.Shutdown calls DestroyAllClientObjects. + // which destroys all objects in NetworkClient.spawned. + // => NC.spawned contains owned & observed objects + // => in host mode, we CAN NOT destroy observed objects. + // => that would destroy them other connection's objects + // on the host server, making them disconnect. + // https://github.com/vis2k/Mirror/issues/2954 + bool hostOwned = identity.connectionToServer is LocalConnectionToServer; + bool shouldDestroy = !identity.isServer || hostOwned; + if (shouldDestroy) + { + bool wasUnspawned = InvokeUnSpawnHandler(identity.assetId, identity.gameObject); + + // unspawned objects should be reset for reuse later. + if (wasUnspawned) + { + identity.ResetState(); + } + // without unspawn handler, we need to disable/destroy. + else + { + // scene objects are reset and disabled. + // they always stay in the scene, we don't destroy them. + if (identity.sceneId != 0) + { + identity.ResetState(); + identity.gameObject.SetActive(false); + } + // spawned objects are destroyed + else + { + GameObject.Destroy(identity.gameObject); + } + } + } + } + } + spawned.Clear(); + connection?.owned.Clear(); + } + catch (InvalidOperationException e) + { + Debug.LogException(e); + Debug.LogError("Could not DestroyAllClientObjects because spawned list was modified during loop, make sure you are not modifying NetworkIdentity.spawned by calling NetworkServer.Destroy or NetworkServer.Spawn in OnDestroy or OnDisable."); + } + } + + static void DestroyObject(uint netId) + { + // Debug.Log($"NetworkClient.OnObjDestroy netId: {netId}"); + if (spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null) + { + if (identity.isLocalPlayer) + identity.OnStopLocalPlayer(); + + identity.OnStopClient(); + + // custom unspawn handler for this prefab? (for prefab pools etc.) + if (InvokeUnSpawnHandler(identity.assetId, identity.gameObject)) + { + // reset object after user's handler + identity.ResetState(); + } + // otherwise fall back to default Destroy + else if (identity.sceneId == 0) + { + // don't call reset before destroy so that values are still set in OnDestroy + GameObject.Destroy(identity.gameObject); + } + // scene object.. disable it in scene instead of destroying + else + { + identity.gameObject.SetActive(false); + spawnableObjects[identity.sceneId] = identity; + // reset for scene objects + identity.ResetState(); + } + + // remove from dictionary no matter how it is unspawned + connection.owned.Remove(identity); // if any + spawned.Remove(netId); + } + //else Debug.LogWarning($"Did not find target for destroy message for {netId}"); + } + + // shutdown //////////////////////////////////////////////////////////// + /// Shutdown the client. + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + public static void Shutdown() + { + //Debug.Log("Shutting down client."); + + // objects need to be destroyed before spawners are cleared + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3334 + DestroyAllClientObjects(); + + // calls prefabs.Clear(); + // calls spawnHandlers.Clear(); + // calls unspawnHandlers.Clear(); + ClearSpawners(); + + spawned.Clear(); + connection?.owned.Clear(); + handlers.Clear(); + spawnableObjects.Clear(); + + // IMPORTANT: do NOT call NetworkIdentity.ResetStatics() here! + // calling StopClient() in host mode would reset nextNetId to 1, + // causing next connection to have a duplicate netId accidentally. + // => see also: https://github.com/vis2k/Mirror/issues/2954 + //NetworkIdentity.ResetStatics(); + // => instead, reset only the client sided statics. + NetworkIdentity.ResetClientStatics(); + + // disconnect the client connection. + // we do NOT call Transport.Shutdown, because someone only called + // NetworkClient.Shutdown. we can't assume that the server is + // supposed to be shut down too! + if (Transport.active != null) + Transport.active.ClientDisconnect(); + + // reset statics + connectState = ConnectState.None; + connection = null; + localPlayer = null; + ready = false; + isSpawnFinished = false; + isLoadingScene = false; + lastSendTime = 0; + + unbatcher = new Unbatcher(); + + // clear events. someone might have hooked into them before, but + // we don't want to use those hooks after Shutdown anymore. + OnConnectedEvent = null; + OnDisconnectedEvent = null; + OnErrorEvent = null; + OnTransportExceptionEvent = null; + } + + // GUI ///////////////////////////////////////////////////////////////// + // called from NetworkManager to display timeline interpolation status. + // useful to indicate catchup / slowdown / dynamic adjustment etc. + public static void OnGUI() + { + // only if in world + if (!ready) return; + + GUILayout.BeginArea(new Rect(10, 5, 1020, 50)); + + GUILayout.BeginHorizontal("Box"); + GUILayout.Label("Snapshot Interp.:"); + // color while catching up / slowing down + if (localTimescale > 1) GUI.color = Color.green; // green traffic light = go fast + else if (localTimescale < 1) GUI.color = Color.red; // red traffic light = go slow + else GUI.color = Color.white; + GUILayout.Box($"timeline: {localTimeline:F2}"); + GUILayout.Box($"buffer: {snapshots.Count}"); + GUILayout.Box($"DriftEMA: {NetworkClient.driftEma.Value:F2}"); + GUILayout.Box($"DelTimeEMA: {NetworkClient.deliveryTimeEma.Value:F2}"); + GUILayout.Box($"timescale: {localTimescale:F2}"); + GUILayout.Box($"BTM: {NetworkClient.bufferTimeMultiplier:F2}"); // current dynamically adjusted multiplier + GUILayout.Box($"RTT: {NetworkTime.rtt * 1000:F0}ms"); + GUILayout.Box($"PredErrUNADJ: {NetworkTime.predictionErrorUnadjusted * 1000:F0}ms"); + GUILayout.Box($"PredErrADJ: {NetworkTime.predictionErrorAdjusted * 1000:F0}ms"); + GUILayout.EndHorizontal(); + + GUILayout.EndArea(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkClient.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkClient.cs.meta new file mode 100644 index 0000000000..b3830226e6 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkClient.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: abe6be14204d94224a3e7cd99dd2ea73 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkClient.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkClient_TimeInterpolation.cs b/Assets/ImportedAssets/Mirror/Core/NetworkClient_TimeInterpolation.cs new file mode 100644 index 0000000000..8d28859837 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkClient_TimeInterpolation.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + public static partial class NetworkClient + { + // snapshot interpolation settings ///////////////////////////////////// + // TODO expose the settings to the user later. + // via NetMan or NetworkClientConfig or NetworkClient as component etc. + public static SnapshotInterpolationSettings snapshotSettings = new SnapshotInterpolationSettings(); + + // snapshot interpolation runtime data ///////////////////////////////// + // buffer time is dynamically adjusted. + // store the current multiplier here, without touching the original in settings. + // this way we can easily reset to or compare with original where needed. + public static double bufferTimeMultiplier; + + // original buffer time based on the settings + // dynamically adjusted buffer time based on dynamically adjusted multiplier + public static double initialBufferTime => NetworkServer.sendInterval * snapshotSettings.bufferTimeMultiplier; + public static double bufferTime => NetworkServer.sendInterval * bufferTimeMultiplier; + + // + public static SortedList snapshots = new SortedList(); + + // for smooth interpolation, we need to interpolate along server time. + // any other time (arrival on client, client local time, etc.) is not + // going to give smooth results. + // in other words, this is the remote server's time, but adjusted. + // + // internal for use from NetworkTime. + // double for long running servers, see NetworkTime comments. + internal static double localTimeline; + + // catchup / slowdown adjustments are applied to timescale, + // to be adjusted in every update instead of when receiving messages. + internal static double localTimescale = 1; + + // catchup ///////////////////////////////////////////////////////////// + + + // we use EMA to average the last second worth of snapshot time diffs. + // manually averaging the last second worth of values with a for loop + // would be the same, but a moving average is faster because we only + // ever add one value. + static ExponentialMovingAverage driftEma; + + // dynamic buffer time adjustment ////////////////////////////////////// + // dynamically adjusts bufferTimeMultiplier for smooth results. + // to understand how this works, try this manually: + // + // - disable dynamic adjustment + // - set jitter = 0.2 (20% is a lot!) + // - notice some stuttering + // - disable interpolation to see just how much jitter this really is(!) + // - enable interpolation again + // - manually increase bufferTimeMultiplier to 3-4 + // ... the cube slows down (blue) until it's smooth + // - with dynamic adjustment enabled, it will set 4 automatically + // ... the cube slows down (blue) until it's smooth as well + // + // note that 20% jitter is extreme. + // for this to be perfectly smooth, set the safety tolerance to '2'. + // but realistically this is not necessary, and '1' is enough. + [Header("Snapshot Interpolation: Dynamic Adjustment")] + [Tooltip("Automatically adjust bufferTimeMultiplier for smooth results.\nSets a low multiplier on stable connections, and a high multiplier on jittery connections.")] + public static bool dynamicAdjustment = true; + + [Tooltip("Safety buffer that is always added to the dynamic bufferTimeMultiplier adjustment.")] + public static float dynamicAdjustmentTolerance = 1; // 1 is realistically just fine, 2 is very very safe even for 20% jitter. can be half a frame too. (see above comments) + + [Tooltip("Dynamic adjustment is computed over n-second exponential moving average standard deviation.")] + public static int deliveryTimeEmaDuration = 2; // 1-2s recommended to capture average delivery time + static ExponentialMovingAverage deliveryTimeEma; // average delivery time (standard deviation gives average jitter) + + // OnValidate: see NetworkClient.cs + // add snapshot & initialize client interpolation time if needed + + // initialization called from Awake + static void InitTimeInterpolation() + { + // reset timeline, localTimescale & snapshots from last session (if any) + bufferTimeMultiplier = snapshotSettings.bufferTimeMultiplier; + localTimeline = 0; + localTimescale = 1; + snapshots.Clear(); + + // initialize EMA with 'emaDuration' seconds worth of history. + // 1 second holds 'sendRate' worth of values. + // multiplied by emaDuration gives n-seconds. + driftEma = new ExponentialMovingAverage(NetworkServer.sendRate * snapshotSettings.driftEmaDuration); + deliveryTimeEma = new ExponentialMovingAverage(NetworkServer.sendRate * snapshotSettings.deliveryTimeEmaDuration); + } + + // server sends TimeSnapshotMessage every sendInterval. + // batching already includes the remoteTimestamp. + // we simply insert it on-message here. + // => only for reliable channel. unreliable would always arrive earlier. + static void OnTimeSnapshotMessage(TimeSnapshotMessage _) + { + // insert another snapshot for snapshot interpolation. + // before calling OnDeserialize so components can use + // NetworkTime.time and NetworkTime.timeStamp. + + // Unity 2019 doesn't have Time.timeAsDouble yet + OnTimeSnapshot(new TimeSnapshot(connection.remoteTimeStamp, NetworkTime.localTime)); + } + + // see comments at the top of this file + public static void OnTimeSnapshot(TimeSnapshot snap) + { + // Debug.Log($"NetworkClient: OnTimeSnapshot @ {snap.remoteTime:F3}"); + + // (optional) dynamic adjustment + if (snapshotSettings.dynamicAdjustment) + { + // set bufferTime on the fly. + // shows in inspector for easier debugging :) + bufferTimeMultiplier = SnapshotInterpolation.DynamicAdjustment( + NetworkServer.sendInterval, + deliveryTimeEma.StandardDeviation, + snapshotSettings.dynamicAdjustmentTolerance + ); + } + + // insert into the buffer & initialize / adjust / catchup + SnapshotInterpolation.InsertAndAdjust( + snapshots, + snapshotSettings.bufferLimit, + snap, + ref localTimeline, + ref localTimescale, + NetworkServer.sendInterval, + bufferTime, + snapshotSettings.catchupSpeed, + snapshotSettings.slowdownSpeed, + ref driftEma, + snapshotSettings.catchupNegativeThreshold, + snapshotSettings.catchupPositiveThreshold, + ref deliveryTimeEma); + + // Debug.Log($"inserted TimeSnapshot remote={snap.remoteTime:F2} local={snap.localTime:F2} total={snapshots.Count}"); + } + + // call this from early update, so the timeline is safe to use in update + static void UpdateTimeInterpolation() + { + // only while we have snapshots. + // timeline starts when the first snapshot arrives. + if (snapshots.Count > 0) + { + // progress local timeline. + // NetworkTime uses unscaled time and ignores Time.timeScale. + // fixes Time.timeScale getting server & client time out of sync: + // https://github.com/MirrorNetworking/Mirror/issues/3409 + SnapshotInterpolation.StepTime(Time.unscaledDeltaTime, ref localTimeline, localTimescale); + + // progress local interpolation. + // TimeSnapshot doesn't interpolate anything. + // this is merely to keep removing older snapshots. + SnapshotInterpolation.StepInterpolation(snapshots, localTimeline, out _, out _, out double t); + // Debug.Log($"NetworkClient SnapshotInterpolation @ {localTimeline:F2} t={t:F2}"); + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkClient_TimeInterpolation.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkClient_TimeInterpolation.cs.meta new file mode 100644 index 0000000000..1e37411c93 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkClient_TimeInterpolation.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ad039071a9cc487b9f7831d28bbe8e83 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkClient_TimeInterpolation.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkConnection.cs b/Assets/ImportedAssets/Mirror/Core/NetworkConnection.cs new file mode 100644 index 0000000000..851beaea09 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkConnection.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + /// Base NetworkConnection class for server-to-client and client-to-server connection. + public abstract class NetworkConnection + { + public const int LocalConnectionId = 0; + + /// Unique identifier for this connection that is assigned by the transport layer. + // assigned by transport, this id is unique for every connection on server. + // clients don't know their own id and they don't know other client's ids. + public readonly int connectionId; + + /// Flag that indicates the client has been authenticated. + public bool isAuthenticated; + + /// General purpose object to hold authentication data, character selection, tokens, etc. + public object authenticationData; + + /// A server connection is ready after joining the game world. + // TODO move this to ConnectionToClient so the flag only lives on server + // connections? clients could use NetworkClient.ready to avoid redundant + // state. + public bool isReady; + + /// Last time a message was received for this connection. Includes system and user messages. + public float lastMessageTime; + + /// This connection's main object (usually the player object). + public NetworkIdentity identity { get; internal set; } + + /// All NetworkIdentities owned by this connection. Can be main player, pets, etc. + // .owned is now valid both on server and on client. + // IMPORTANT: this needs to be , not . + // fixes a bug where DestroyOwnedObjects wouldn't find the + // netId anymore: https://github.com/vis2k/Mirror/issues/1380 + // Works fine with NetworkIdentity pointers though. + public readonly HashSet owned = new HashSet(); + + // batching from server to client & client to server. + // fewer transport calls give us significantly better performance/scale. + // + // for a 64KB max message transport and 64 bytes/message on average, we + // reduce transport calls by a factor of 1000. + // + // depending on the transport, this can give 10x performance. + // + // Dictionary because we have multiple channels. + protected Dictionary batches = new Dictionary(); + + /// last batch's remote timestamp. not interpolated. useful for NetworkTransform etc. + // for any given NetworkMessage/Rpc/Cmd/OnSerialize, this was the time + // on the REMOTE END when it was sent. + // + // NOTE: this is NOT in NetworkTime, it needs to be per-connection + // because the server receives different batch timestamps from + // different connections. + public double remoteTimeStamp { get; internal set; } + + internal NetworkConnection() + { + // set lastTime to current time when creating connection to make + // sure it isn't instantly kicked for inactivity + lastMessageTime = Time.time; + } + + internal NetworkConnection(int networkConnectionId) : this() + { + connectionId = networkConnectionId; + } + + // TODO if we only have Reliable/Unreliable, then we could initialize + // two batches and avoid this code + protected Batcher GetBatchForChannelId(int channelId) + { + // get existing or create new writer for the channelId + Batcher batch; + if (!batches.TryGetValue(channelId, out batch)) + { + // get max batch size for this channel + int threshold = Transport.active.GetBatchThreshold(channelId); + + // create batcher + batch = new Batcher(threshold); + batches[channelId] = batch; + } + return batch; + } + + // Send stage one: NetworkMessage + /// Send a NetworkMessage to this connection over the given channel. + public void Send(T message, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // pack message + NetworkMessages.Pack(message, writer); + + // validate packet size immediately. + // we know how much can fit into one batch at max. + // if it's larger, log an error immediately with the type . + // previously we only logged in Update() when processing batches, + // but there we don't have type information anymore. + int max = NetworkMessages.MaxMessageSize(channelId); + if (writer.Position > max) + { + Debug.LogError($"NetworkConnection.Send: message of type {typeof(T)} with a size of {writer.Position} bytes is larger than the max allowed message size in one batch: {max}.\nThe message was dropped, please make it smaller."); + return; + } + + // send allocation free + NetworkDiagnostics.OnSend(message, channelId, writer.Position, 1); + Send(writer.ToArraySegment(), channelId); + } + } + + // Send stage two: serialized NetworkMessage as ArraySegment + // internal because no one except Mirror should send bytes directly to + // the client. they would be detected as a message. send messages instead. + // => make sure to validate message size before calling Send! + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal virtual void Send(ArraySegment segment, int channelId = Channels.Reliable) + { + //Debug.Log($"ConnectionSend {this} bytes:{BitConverter.ToString(segment.Array, segment.Offset, segment.Count)}"); + + // add to batch no matter what. + // batching will try to fit as many as possible into MTU. + // but we still allow > MTU, e.g. kcp max packet size 144kb. + // those are simply sent as single batches. + // + // IMPORTANT: do NOT send > batch sized messages directly: + // - data race: large messages would be sent directly. small + // messages would be sent in the batch at the end of frame + // - timestamps: if batching assumes a timestamp, then large + // messages need that too. + // + // NOTE: we ALWAYS batch. it's not optional, because the + // receiver needs timestamps for NT etc. + // + // NOTE: we do NOT ValidatePacketSize here yet. the final packet + // will be the full batch, including timestamp. + GetBatchForChannelId(channelId).AddMessage(segment, NetworkTime.localTime); + } + + // Send stage three: hand off to transport + protected abstract void SendToTransport(ArraySegment segment, int channelId = Channels.Reliable); + + // flush batched messages at the end of every Update. + internal virtual void Update() + { + // go through batches for all channels + // foreach ((int key, Batcher batcher) in batches) // Unity 2020 doesn't support deconstruct yet + foreach (KeyValuePair kvp in batches) + { + // make and send as many batches as necessary from the stored + // messages. + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // make a batch with our local time (double precision) + while (kvp.Value.GetBatch(writer)) + { + // message size is validated in Send, with test coverage. + // we can send directly without checking again. + ArraySegment segment = writer.ToArraySegment(); + + // send to transport + SendToTransport(segment, kvp.Key); + //UnityEngine.Debug.Log($"sending batch of {writer.Position} bytes for channel={kvp.Key} connId={connectionId}"); + + // reset writer for each new batch + writer.Position = 0; + } + } + } + } + + /// Check if we received a message within the last 'timeout' seconds. + internal virtual bool IsAlive(float timeout) => Time.time - lastMessageTime < timeout; + + /// Disconnects this connection. + // for future reference, here is how Disconnects work in Mirror. + // + // first, there are two types of disconnects: + // * voluntary: the other end simply disconnected + // * involuntary: server disconnects a client by itself + // + // UNET had special (complex) code to handle both cases differently. + // + // Mirror handles both cases the same way: + // * Disconnect is called from TOP to BOTTOM + // NetworkServer/Client -> NetworkConnection -> Transport.Disconnect() + // * Disconnect is handled from BOTTOM to TOP + // Transport.OnDisconnected -> ... + // + // in other words, calling Disconnect() does no cleanup whatsoever. + // it simply asks the transport to disconnect. + // then later the transport events will do the clean up. + public abstract void Disconnect(); + + // cleanup is called before the connection is removed. + // return any batches' pooled writers before the connection disappears. + // otherwise if a connection disappears before flushing, writers would + // never be returned to the pool. + public virtual void Cleanup() + { + foreach (Batcher batcher in batches.Values) + { + batcher.Clear(); + } + } + + public override string ToString() => $"connection({connectionId})"; + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkConnection.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkConnection.cs.meta new file mode 100644 index 0000000000..797f19fc21 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkConnection.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 11ea41db366624109af1f0834bcdde2f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkConnection.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToClient.cs b/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToClient.cs new file mode 100644 index 0000000000..361b00c34e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToClient.cs @@ -0,0 +1,220 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + public class NetworkConnectionToClient : NetworkConnection + { + // rpcs are collected in a buffer, and then flushed out together. + // this way we don't need one NetworkMessage per rpc. + // => prepares for LocalWorldState as well. + // ensure max size when adding! + readonly NetworkWriter reliableRpcs = new NetworkWriter(); + readonly NetworkWriter unreliableRpcs = new NetworkWriter(); + + public virtual string address => Transport.active.ServerGetClientAddress(connectionId); + + /// NetworkIdentities that this connection can see + // TODO move to server's NetworkConnectionToClient? + public readonly HashSet observing = new HashSet(); + + // unbatcher + public Unbatcher unbatcher = new Unbatcher(); + + // server runs a time snapshot interpolation for each client's local time. + // this is necessary for client auth movement to still be smooth on the + // server for host mode. + // TODO move them along server's timeline in the future. + // perhaps with an offset. + // for now, keep compatibility by manually constructing a timeline. + ExponentialMovingAverage driftEma; + ExponentialMovingAverage deliveryTimeEma; // average delivery time (standard deviation gives average jitter) + public double remoteTimeline; + public double remoteTimescale; + double bufferTimeMultiplier = 2; + double bufferTime => NetworkServer.sendInterval * bufferTimeMultiplier; + + // + readonly SortedList snapshots = new SortedList(); + + // Snapshot Buffer size limit to avoid ever growing list memory consumption attacks from clients. + public int snapshotBufferSizeLimit = 64; + + // ping for rtt (round trip time) + // useful for statistics, lag compensation, etc. + double lastPingTime = 0; + internal ExponentialMovingAverage _rtt = new ExponentialMovingAverage(NetworkTime.PingWindowSize); + + /// Round trip time (in seconds) that it takes a message to go server->client->server. + public double rtt => _rtt.Value; + + public NetworkConnectionToClient(int networkConnectionId) + : base(networkConnectionId) + { + // initialize EMA with 'emaDuration' seconds worth of history. + // 1 second holds 'sendRate' worth of values. + // multiplied by emaDuration gives n-seconds. + driftEma = new ExponentialMovingAverage(NetworkServer.sendRate * NetworkClient.snapshotSettings.driftEmaDuration); + deliveryTimeEma = new ExponentialMovingAverage(NetworkServer.sendRate * NetworkClient.snapshotSettings.deliveryTimeEmaDuration); + + // buffer limit should be at least multiplier to have enough in there + snapshotBufferSizeLimit = Mathf.Max((int)NetworkClient.snapshotSettings.bufferTimeMultiplier, snapshotBufferSizeLimit); + } + + public void OnTimeSnapshot(TimeSnapshot snapshot) + { + // protect against ever growing buffer size attacks + if (snapshots.Count >= snapshotBufferSizeLimit) return; + + // (optional) dynamic adjustment + if (NetworkClient.snapshotSettings.dynamicAdjustment) + { + // set bufferTime on the fly. + // shows in inspector for easier debugging :) + bufferTimeMultiplier = SnapshotInterpolation.DynamicAdjustment( + NetworkServer.sendInterval, + deliveryTimeEma.StandardDeviation, + NetworkClient.snapshotSettings.dynamicAdjustmentTolerance + ); + // Debug.Log($"[Server]: {name} delivery std={serverDeliveryTimeEma.StandardDeviation} bufferTimeMult := {bufferTimeMultiplier} "); + } + + // insert into the server buffer & initialize / adjust / catchup + SnapshotInterpolation.InsertAndAdjust( + snapshots, + NetworkClient.snapshotSettings.bufferLimit, + snapshot, + ref remoteTimeline, + ref remoteTimescale, + NetworkServer.sendInterval, + bufferTime, + NetworkClient.snapshotSettings.catchupSpeed, + NetworkClient.snapshotSettings.slowdownSpeed, + ref driftEma, + NetworkClient.snapshotSettings.catchupNegativeThreshold, + NetworkClient.snapshotSettings.catchupPositiveThreshold, + ref deliveryTimeEma + ); + } + + public void UpdateTimeInterpolation() + { + // timeline starts when the first snapshot arrives. + if (snapshots.Count > 0) + { + // progress local timeline. + SnapshotInterpolation.StepTime(Time.unscaledDeltaTime, ref remoteTimeline, remoteTimescale); + + // progress local interpolation. + // TimeSnapshot doesn't interpolate anything. + // this is merely to keep removing older snapshots. + SnapshotInterpolation.StepInterpolation(snapshots, remoteTimeline, out _, out _, out _); + // Debug.Log($"NetworkClient SnapshotInterpolation @ {localTimeline:F2} t={t:F2}"); + } + } + + // Send stage three: hand off to transport + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected override void SendToTransport(ArraySegment segment, int channelId = Channels.Reliable) => + Transport.active.ServerSend(connectionId, segment, channelId); + + protected virtual void UpdatePing() + { + // localTime (double) instead of Time.time for accuracy over days + if (NetworkTime.localTime >= lastPingTime + NetworkTime.PingInterval) + { + // TODO it would be safer for the server to store the last N + // messages' timestamp and only send a message number. + // This way client's can't just modify the timestamp. + // predictedTime parameter is 0 because the server doesn't predict. + NetworkPingMessage pingMessage = new NetworkPingMessage(NetworkTime.localTime, 0); + Send(pingMessage, Channels.Unreliable); + lastPingTime = NetworkTime.localTime; + } + } + + internal override void Update() + { + UpdatePing(); + base.Update(); + } + + /// Disconnects this connection. + public override void Disconnect() + { + // set not ready and handle clientscene disconnect in any case + // (might be client or host mode here) + isReady = false; + reliableRpcs.Position = 0; + unreliableRpcs.Position = 0; + Transport.active.ServerDisconnect(connectionId); + + // IMPORTANT: NetworkConnection.Disconnect() is NOT called for + // voluntary disconnects from the other end. + // -> so all 'on disconnect' cleanup code needs to be in + // OnTransportDisconnect, where it's called for both voluntary + // and involuntary disconnects! + } + + internal void AddToObserving(NetworkIdentity netIdentity) + { + observing.Add(netIdentity); + + // spawn identity for this conn + NetworkServer.ShowForConnection(netIdentity, this); + } + + internal void RemoveFromObserving(NetworkIdentity netIdentity, bool isDestroyed) + { + observing.Remove(netIdentity); + + if (!isDestroyed) + { + // hide identity for this conn + NetworkServer.HideForConnection(netIdentity, this); + } + } + + internal void RemoveFromObservingsObservers() + { + foreach (NetworkIdentity netIdentity in observing) + { + netIdentity.RemoveObserver(this); + } + observing.Clear(); + } + + internal void AddOwnedObject(NetworkIdentity obj) + { + owned.Add(obj); + } + + internal void RemoveOwnedObject(NetworkIdentity obj) + { + owned.Remove(obj); + } + + internal void DestroyOwnedObjects() + { + // create a copy because the list might be modified when destroying + HashSet tmp = new HashSet(owned); + foreach (NetworkIdentity netIdentity in tmp) + { + if (netIdentity != null) + { + // unspawn scene objects, destroy instantiated objects. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3538 + if (netIdentity.sceneId != 0) + NetworkServer.UnSpawn(netIdentity.gameObject); + else + NetworkServer.Destroy(netIdentity.gameObject); + } + } + + // clear the hashset because we destroyed them all + owned.Clear(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToClient.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToClient.cs.meta new file mode 100644 index 0000000000..4683fc7f36 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToClient.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: bb2195f8b29d24f0680a57fde2e9fd09 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkConnectionToClient.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToServer.cs b/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToServer.cs new file mode 100644 index 0000000000..496813d6df --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToServer.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public class NetworkConnectionToServer : NetworkConnection + { + // Send stage three: hand off to transport + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected override void SendToTransport(ArraySegment segment, int channelId = Channels.Reliable) => + Transport.active.ClientSend(segment, channelId); + + /// Disconnects this connection. + public override void Disconnect() + { + // set not ready and handle clientscene disconnect in any case + // (might be client or host mode here) + // TODO remove redundant state. have one source of truth for .ready! + isReady = false; + NetworkClient.ready = false; + Transport.active.ClientDisconnect(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToServer.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToServer.cs.meta new file mode 100644 index 0000000000..58ace7bd7b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkConnectionToServer.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 761977cbf38a34ded9dd89de45445675 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkConnectionToServer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkDiagnostics.cs b/Assets/ImportedAssets/Mirror/Core/NetworkDiagnostics.cs new file mode 100644 index 0000000000..1cdc96fd76 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkDiagnostics.cs @@ -0,0 +1,63 @@ +using System; + +namespace Mirror +{ + /// Profiling statistics for tool to subscribe to (profiler etc.) + public static class NetworkDiagnostics + { + /// Describes an outgoing message + public readonly struct MessageInfo + { + /// The message being sent + public readonly NetworkMessage message; + /// channel through which the message was sent + public readonly int channel; + /// how big was the message (does not include transport headers) + public readonly int bytes; + /// How many connections was the message sent to. + public readonly int count; + + internal MessageInfo(NetworkMessage message, int channel, int bytes, int count) + { + this.message = message; + this.channel = channel; + this.bytes = bytes; + this.count = count; + } + } + + /// Event for when Mirror sends a message. Can be subscribed to. + public static event Action OutMessageEvent; + + /// Event for when Mirror receives a message. Can be subscribed to. + public static event Action InMessageEvent; + + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [UnityEngine.RuntimeInitializeOnLoadMethod] + static void ResetStatics() + { + InMessageEvent = null; + OutMessageEvent = null; + } + + internal static void OnSend(T message, int channel, int bytes, int count) + where T : struct, NetworkMessage + { + if (count > 0 && OutMessageEvent != null) + { + MessageInfo outMessage = new MessageInfo(message, channel, bytes, count); + OutMessageEvent?.Invoke(outMessage); + } + } + + internal static void OnReceive(T message, int channel, int bytes) + where T : struct, NetworkMessage + { + if (InMessageEvent != null) + { + MessageInfo inMessage = new MessageInfo(message, channel, bytes, 1); + InMessageEvent?.Invoke(inMessage); + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkDiagnostics.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkDiagnostics.cs.meta new file mode 100644 index 0000000000..1c9ebb3144 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkDiagnostics.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: c3754b39e5f8740fd93f3337b2c4274e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkDiagnostics.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkIdentity.cs b/Assets/ImportedAssets/Mirror/Core/NetworkIdentity.cs new file mode 100644 index 0000000000..aed8251f6f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkIdentity.cs @@ -0,0 +1,1390 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Mirror.RemoteCalls; +using UnityEngine; +using UnityEngine.Serialization; + +#if UNITY_EDITOR +using UnityEditor; + +#if UNITY_2021_2_OR_NEWER +using UnityEditor.SceneManagement; +#else +using UnityEditor.Experimental.SceneManagement; +#endif +#endif + +namespace Mirror +{ + // Default = use interest management + // ForceHidden = useful to hide monsters while they respawn etc. + // ForceShown = useful to have score NetworkIdentities that always broadcast + // to everyone etc. + public enum Visibility { Default, ForceHidden, ForceShown } + + public struct NetworkIdentitySerialization + { + // IMPORTANT: int tick avoids floating point inaccuracy over days/weeks + public int tick; + public NetworkWriter ownerWriter; + public NetworkWriter observersWriter; + } + + /// NetworkIdentity identifies objects across the network. + [DisallowMultipleComponent] + // NetworkIdentity.Awake initializes all NetworkComponents. + // let's make sure it's always called before their Awake's. + [DefaultExecutionOrder(-1)] + [AddComponentMenu("Network/Network Identity")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-identity")] + public sealed class NetworkIdentity : MonoBehaviour + { + /// Returns true if running as a client and this object was spawned by a server. + // + // IMPORTANT: + // OnStartClient sets it to true. we NEVER set it to false after. + // otherwise components like Skillbars couldn't use OnDestroy() + // for saving, etc. since isClient may have been reset before + // OnDestroy was called. + // + // we also DO NOT make it dependent on NetworkClient.active or similar. + // we set it, then never change it. that's the user's expectation too. + // + // => fixes https://github.com/vis2k/Mirror/issues/1475 + public bool isClient { get; internal set; } + + /// Returns true if NetworkServer.active and server is not stopped. + // + // IMPORTANT: + // OnStartServer sets it to true. we NEVER set it to false after. + // otherwise components like Skillbars couldn't use OnDestroy() + // for saving, etc. since isServer may have been reset before + // OnDestroy was called. + // + // we also DO NOT make it dependent on NetworkServer.active or similar. + // we set it, then never change it. that's the user's expectation too. + // + // => fixes https://github.com/vis2k/Mirror/issues/1484 + // => fixes https://github.com/vis2k/Mirror/issues/2533 + public bool isServer { get; internal set; } + + /// Return true if this object represents the player on the local machine. + // + // IMPORTANT: + // OnStartLocalPlayer sets it to true. we NEVER set it to false after. + // otherwise components like Skillbars couldn't use OnDestroy() + // for saving, etc. since isLocalPlayer may have been reset before + // OnDestroy was called. + // + // we also DO NOT make it dependent on NetworkClient.localPlayer or similar. + // we set it, then never change it. that's the user's expectation too. + // + // => fixes https://github.com/vis2k/Mirror/issues/2615 + public bool isLocalPlayer { get; internal set; } + + /// True if this object only exists on the server + public bool isServerOnly => isServer && !isClient; + + /// True if this object exists on a client that is not also acting as a server. + public bool isClientOnly => isClient && !isServer; + + /// isOwned is true on the client if this NetworkIdentity is one of the .owned entities of our connection on the server. + // for example: main player & pets are owned. monsters & npcs aren't. + public bool isOwned { get; internal set; } + + // internal so NetworkManager can reset it from StopClient. + internal bool clientStarted; + + /// The set of network connections (players) that can see this object. + public readonly Dictionary observers = + new Dictionary(); + + /// The unique network Id of this object (unique at runtime). + public uint netId { get; internal set; } + + /// Unique identifier for NetworkIdentity objects within a scene, used for spawning scene objects. + // persistent scene id (see AssignSceneID comments) + [FormerlySerializedAs("m_SceneId"), HideInInspector] + public ulong sceneId; + + // assetId used to spawn prefabs across the network. + // originally a Guid, but a 4 byte uint is sufficient + // (as suggested by james) + // + // it's also easier to work with for serialization etc. + // serialized and visible in inspector for easier debugging + [SerializeField, HideInInspector] uint _assetId; + + // The AssetId trick: + // Ideally we would have a serialized 'Guid m_AssetId' but Unity can't + // serialize it because Guid's internal bytes are private + // + // Using just the Guid string would work, but it's 32 chars long and + // would then be sent over the network as 64 instead of 16 bytes + // + // => The solution is to serialize the string internally here and then + // use the real 'Guid' type for everything else via .assetId + public uint assetId + { + get + { +#if UNITY_EDITOR + // old UNET comment: + // This is important because sometimes OnValidate does not run + // (like when adding NetworkIdentity to prefab with no child links) + if (_assetId == 0) + SetupIDs(); +#endif + return _assetId; + } + // assetId is set internally when creating or duplicating a prefab + internal set + { + // should never be empty + if (value == 0) + { + Debug.LogError($"Can not set AssetId to empty guid on NetworkIdentity '{name}', old assetId '{_assetId}'"); + return; + } + + // always set it otherwise. + // for new prefabs, it will set from 0 to N. + // for duplicated prefabs, it will set from N to M. + // either way, it's always set to a valid GUID. + _assetId = value; + // Debug.Log($"Setting AssetId on NetworkIdentity '{name}', new assetId '{value:X4}'"); + } + } + + /// Make this object only exist when the game is running as a server (or host). + [FormerlySerializedAs("m_ServerOnly")] + [Tooltip("Prevents this object from being spawned / enabled on clients")] + public bool serverOnly; + + // Set before Destroy is called so that OnDestroy doesn't try to destroy + // the object again + internal bool destroyCalled; + + /// Client's network connection to the server. This is only valid for player objects on the client. + // TODO change to NetworkConnectionToServer, but might cause some breaking + public NetworkConnection connectionToServer { get; internal set; } + + /// Server's network connection to the client. This is only valid for client-owned objects (including the Player object) on the server. + public NetworkConnectionToClient connectionToClient + { + get => _connectionToClient; + internal set + { + _connectionToClient?.RemoveOwnedObject(this); + _connectionToClient = value; + _connectionToClient?.AddOwnedObject(this); + } + } + NetworkConnectionToClient _connectionToClient; + + // get all NetworkBehaviour components + public NetworkBehaviour[] NetworkBehaviours { get; private set; } + + // to save bandwidth, we send one 64 bit dirty mask + // instead of 1 byte index per dirty component. + // which means we can't allow > 64 components (it's enough). + const int MaxNetworkBehaviours = 64; + + // current visibility + // + // Default = use interest management + // ForceHidden = useful to hide monsters while they respawn etc. + // ForceShown = useful to have score NetworkIdentities that always broadcast + // to everyone etc. + [Tooltip("Visibility can overwrite interest management. ForceHidden can be useful to hide monsters while they respawn. ForceShown can be useful for score NetworkIdentities that should always broadcast to everyone in the world.")] + [FormerlySerializedAs("visible")] + public Visibility visibility = Visibility.Default; + + // Deprecated 2024-01-21 + [HideInInspector] + [Obsolete("Deprecated - Use .visibility instead. This will be removed soon.")] + public Visibility visible + { + get => visibility; + set => visibility = value; + } + + // broadcasting serializes all entities around a player for each player. + // we don't want to serialize one entity twice in the same tick. + // so we cache the last serialization and remember the timestamp so we + // know which Update it was serialized. + // (timestamp is the same while inside Update) + // => this way we don't need to pool thousands of writers either. + // => way easier to store them per object + NetworkIdentitySerialization lastSerialization = new NetworkIdentitySerialization + { + ownerWriter = new NetworkWriter(), + observersWriter = new NetworkWriter() + }; + + // Keep track of all sceneIds to detect scene duplicates + static readonly Dictionary sceneIds = + new Dictionary(); + + // Helper function to handle Command/Rpc + internal void HandleRemoteCall(byte componentIndex, ushort functionHash, RemoteCallType remoteCallType, NetworkReader reader, NetworkConnectionToClient senderConnection = null) + { + // check if unity object has been destroyed + if (this == null) + { + Debug.LogWarning($"{remoteCallType} [{functionHash}] received for deleted object [netId={netId}]"); + return; + } + + // find the right component to invoke the function on + if (componentIndex >= NetworkBehaviours.Length) + { + Debug.LogWarning($"Component [{componentIndex}] not found for [netId={netId}]"); + return; + } + + NetworkBehaviour invokeComponent = NetworkBehaviours[componentIndex]; + if (!RemoteProcedureCalls.Invoke(functionHash, remoteCallType, reader, invokeComponent, senderConnection)) + { + Debug.LogError($"Found no receiver for incoming {remoteCallType} [{functionHash}] on {gameObject.name}, the server and client should have the same NetworkBehaviour instances [netId={netId}]."); + } + } + + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + // internal so it can be called from NetworkServer & NetworkClient + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + internal static void ResetStatics() + { + // reset ALL statics + ResetClientStatics(); + ResetServerStatics(); + } + + // reset only client sided statics. + // don't touch server statics when calling StopClient in host mode. + // https://github.com/vis2k/Mirror/issues/2954 + internal static void ResetClientStatics() + { + previousLocalPlayer = null; + clientAuthorityCallback = null; + } + + internal static void ResetServerStatics() + { + nextNetworkId = 1; + } + + /// Gets the NetworkIdentity from the sceneIds dictionary with the corresponding id + public static NetworkIdentity GetSceneIdentity(ulong id) => sceneIds[id]; + + static uint nextNetworkId = 1; + internal static uint GetNextNetworkId() => nextNetworkId++; + + /// Resets nextNetworkId = 1 + public static void ResetNextNetworkId() => nextNetworkId = 1; + + /// The delegate type for the clientAuthorityCallback. + public delegate void ClientAuthorityCallback(NetworkConnectionToClient conn, NetworkIdentity identity, bool authorityState); + + /// A callback that can be populated to be notified when the client-authority state of objects changes. + public static event ClientAuthorityCallback clientAuthorityCallback; + + // hasSpawned should always be false before runtime + [SerializeField, HideInInspector] bool hasSpawned; + public bool SpawnedFromInstantiate { get; private set; } + + // NetworkBehaviour components are initialized in Awake once. + // Changing them at runtime would get client & server out of sync. + // BUT internal so tests can add them after creating the NetworkIdentity + internal void InitializeNetworkBehaviours() + { + // Get all NetworkBehaviour components, including children. + // Some users need NetworkTransform on child bones, etc. + // => Deterministic: https://forum.unity.com/threads/getcomponentsinchildren.4582/#post-33983 + // => Never null. GetComponents returns [] if none found. + // => Include inactive. We need all child components. + NetworkBehaviours = GetComponentsInChildren(true); + ValidateComponents(); + + // initialize each one + for (int i = 0; i < NetworkBehaviours.Length; ++i) + { + NetworkBehaviour component = NetworkBehaviours[i]; + component.netIdentity = this; + component.ComponentIndex = (byte)i; + } + } + + void ValidateComponents() + { + if (NetworkBehaviours == null) + { + Debug.LogError($"NetworkBehaviours array is null on {gameObject.name}!\n" + + $"Typically this can happen when a networked object is a child of a " + + $"non-networked parent that's disabled, preventing Awake on the networked object " + + $"from being invoked, where the NetworkBehaviours array is initialized.", gameObject); + } + else if (NetworkBehaviours.Length > MaxNetworkBehaviours) + { + Debug.LogError($"NetworkIdentity {name} has too many NetworkBehaviour components: only {MaxNetworkBehaviours} NetworkBehaviour components are allowed in order to save bandwidth.", this); + } + } + + // Awake is only called in Play mode. + // internal so we can call it during unit tests too. + internal void Awake() + { + // initialize NetworkBehaviour components. + // Awake() is called immediately after initialization. + // no one can overwrite it because NetworkIdentity is sealed. + // => doing it here is the fastest and easiest solution. + InitializeNetworkBehaviours(); + + if (hasSpawned) + { + Debug.LogError($"{name} has already spawned. Don't call Instantiate for NetworkIdentities that were in the scene since the beginning (aka scene objects). Otherwise the client won't know which object to use for a SpawnSceneObject message."); + SpawnedFromInstantiate = true; + Destroy(gameObject); + } + hasSpawned = true; + } + + void OnValidate() + { + // OnValidate is not called when using Instantiate, so we can use + // it to make sure that hasSpawned is false + hasSpawned = false; + +#if UNITY_EDITOR + DisallowChildNetworkIdentities(); + SetupIDs(); +#endif + } + + // expose our AssetId Guid to uint mapping code in case projects need to map Guids to uint as well. + // this way their projects won't break if we change our mapping algorithm. + // needs to be available at runtime / builds, don't wrap in #if UNITY_EDITOR + public static uint AssetGuidToUint(Guid guid) => (uint)guid.GetHashCode(); // deterministic + +#if UNITY_EDITOR + // child NetworkIdentities are not supported. + // Disallow them and show an error for the user to fix. + // This needs to work for Prefabs & Scene objects, so the previous check + // in NetworkClient.RegisterPrefab is not enough. + void DisallowChildNetworkIdentities() + { +#if UNITY_2020_3_OR_NEWER + NetworkIdentity[] identities = GetComponentsInChildren(true); +#else + NetworkIdentity[] identities = GetComponentsInChildren(); +#endif + if (identities.Length > 1) + { + // always log the next child component so it's easy to fix. + // if there are multiple, then after removing it'll log the next. + Debug.LogError($"'{name}' has another NetworkIdentity component on '{identities[1].name}'. There should only be one NetworkIdentity, and it must be on the root object. Please remove the other one.", this); + } + } + + void AssignAssetID(string path) + { + // only set if not empty. fixes https://github.com/vis2k/Mirror/issues/2765 + if (!string.IsNullOrWhiteSpace(path)) + { + // if we generate the assetId then we MUST be sure to set dirty + // in order to save the prefab object properly. otherwise it + // would be regenerated every time we reopen the prefab. + // -> Undo.RecordObject is the new EditorUtility.SetDirty! + // -> we need to call it before changing. + // + // to verify this, duplicate a prefab and double click to open it. + // add a log message if "_assetId != before_". + // without RecordObject, it'll log every time because it's not saved. + Undo.RecordObject(this, "Assigned AssetId"); + + // uint before = _assetId; + Guid guid = new Guid(AssetDatabase.AssetPathToGUID(path)); + assetId = AssetGuidToUint(guid); + // if (_assetId != before) Debug.Log($"Assigned assetId={assetId} to {name}"); + } + } + + void AssignAssetID(GameObject prefab) => AssignAssetID(AssetDatabase.GetAssetPath(prefab)); + + // persistent sceneId assignment + // (because scene objects have no persistent unique ID in Unity) + // + // original UNET used OnPostProcessScene to assign an index based on + // FindObjectOfType order. + // -> this didn't work because FindObjectOfType order isn't deterministic. + // -> one workaround is to sort them by sibling paths, but it can still + // get out of sync when we open scene2 in editor and we have + // DontDestroyOnLoad objects that messed with the sibling index. + // + // we absolutely need a persistent id. challenges: + // * it needs to be 0 for prefabs + // => we set it to 0 in SetupIDs() if prefab! + // * it needs to be only assigned in edit time, not at runtime because + // only the objects that were in the scene since beginning should have + // a scene id. + // => Application.isPlaying check solves that + // * it needs to detect duplicated sceneIds after duplicating scene + // objects + // => sceneIds dict takes care of that + // * duplicating the whole scene file shouldn't result in duplicate + // scene objects + // => buildIndex is shifted into sceneId for that. + // => if we have no scenes in build index then it doesn't matter + // because by definition a build can't switch to other scenes + // => if we do have scenes in build index then it will be != -1 + // note: the duplicated scene still needs to be opened once for it to + // be set properly + // * scene objects need the correct scene index byte even if the scene's + // build index was changed or a duplicated scene wasn't opened yet. + // => OnPostProcessScene is the only function that gets called for + // each scene before runtime, so this is where we set the scene + // byte. + // * disabled scenes in build settings should result in same scene index + // in editor and in build + // => .gameObject.scene.buildIndex filters out disabled scenes by + // default + // * generated sceneIds absolutely need to set scene dirty and force the + // user to resave. + // => Undo.RecordObject does that perfectly. + // * sceneIds should never be generated temporarily for unopened scenes + // when building, otherwise editor and build get out of sync + // => BuildPipeline.isBuildingPlayer check solves that + void AssignSceneID() + { + // we only ever assign sceneIds at edit time, never at runtime. + // by definition, only the original scene objects should get one. + // -> if we assign at runtime then server and client would generate + // different random numbers! + if (Application.isPlaying) + return; + + // no valid sceneId yet, or duplicate? + bool duplicate = sceneIds.TryGetValue(sceneId, out NetworkIdentity existing) && existing != null && existing != this; + if (sceneId == 0 || duplicate) + { + // clear in any case, because it might have been a duplicate + sceneId = 0; + + // if a scene was never opened and we are building it, then a + // sceneId would be assigned to build but not saved in editor, + // resulting in them getting out of sync. + // => don't ever assign temporary ids. they always need to be + // permanent + // => throw an exception to cancel the build and let the user + // know how to fix it! + if (BuildPipeline.isBuildingPlayer) + throw new InvalidOperationException($"Scene {gameObject.scene.path} needs to be opened and resaved before building, because the scene object {name} has no valid sceneId yet."); + + // if we generate the sceneId then we MUST be sure to set dirty + // in order to save the scene object properly. otherwise it + // would be regenerated every time we reopen the scene, and + // upgrading would be very difficult. + // -> Undo.RecordObject is the new EditorUtility.SetDirty! + // -> we need to call it before changing. + Undo.RecordObject(this, "Generated SceneId"); + + // generate random sceneId part (0x00000000FFFFFFFF) + uint randomId = Utils.GetTrueRandomUInt(); + + // only assign if not a duplicate of an existing scene id + // (small chance, but possible) + duplicate = sceneIds.TryGetValue(randomId, out existing) && existing != null && existing != this; + if (!duplicate) + { + sceneId = randomId; + //Debug.Log($"{name} in scene {gameObject.scene.name} sceneId assigned to:{sceneId:X}"); + } + } + + // add to sceneIds dict no matter what + // -> even if we didn't generate anything new, because we still need + // existing sceneIds in there to check duplicates + sceneIds[sceneId] = this; + } + + // copy scene path hash into sceneId for scene objects. + // this is the only way for scene file duplication to not contain + // duplicate sceneIds as it seems. + // -> sceneId before: 0x00000000AABBCCDD + // -> then we clear the left 4 bytes, so that our 'OR' uses 0x00000000 + // -> then we OR the hash into the 0x00000000 part + // -> buildIndex is not enough, because Editor and Build have different + // build indices if there are disabled scenes in build settings, and + // if no scene is in build settings then Editor and Build have + // different indices too (Editor=0, Build=-1) + // => ONLY USE THIS FROM POSTPROCESSSCENE! + public void SetSceneIdSceneHashPartInternal() + { + // Use `ToLower` to that because BuildPipeline.BuildPlayer is case insensitive but hash is case sensitive + // If the scene in the project is `forest.unity` but `Forest.unity` is given to BuildPipeline then the + // BuildPipeline will use `Forest.unity` for the build and create a different hash than the editor will. + // Using ToLower will mean the hash will be the same for these 2 paths + // Assets/Scenes/Forest.unity + // Assets/Scenes/forest.unity + string scenePath = gameObject.scene.path.ToLower(); + + // get deterministic scene hash + uint pathHash = (uint)scenePath.GetStableHashCode(); + + // shift hash from 0x000000FFFFFFFF to 0xFFFFFFFF00000000 + ulong shiftedHash = (ulong)pathHash << 32; + + // OR into scene id + sceneId = (sceneId & 0xFFFFFFFF) | shiftedHash; + + // log it. this is incredibly useful to debug sceneId issues. + //Debug.Log($"{name} in scene {gameObject.scene.name} scene index hash {pathHash:X} copied into sceneId {sceneId:X}"); + } + + void SetupIDs() + { + // is this a prefab? + if (Utils.IsPrefab(gameObject)) + { + // force 0 for prefabs + sceneId = 0; + AssignAssetID(gameObject); + } + // are we currently in prefab editing mode? aka prefab stage + // => check prefabstage BEFORE SceneObjectWithPrefabParent + // (fixes https://github.com/vis2k/Mirror/issues/976) + // => if we don't check GetCurrentPrefabStage and only check + // GetPrefabStage(gameObject), then the 'else' case where we + // assign a sceneId and clear the assetId would still be + // triggered for prefabs. in other words: if we are in prefab + // stage, do not bother with anything else ever! + else if (PrefabStageUtility.GetCurrentPrefabStage() != null) + { + // when modifying a prefab in prefab stage, Unity calls + // OnValidate for that prefab and for all scene objects based on + // that prefab. + // + // is this GameObject the prefab that we modify, and not just a + // scene object based on the prefab? + // * GetCurrentPrefabStage = 'are we editing ANY prefab?' + // * GetPrefabStage(go) = 'are we editing THIS prefab?' + if (PrefabStageUtility.GetPrefabStage(gameObject) != null) + { + // force 0 for prefabs + sceneId = 0; + //Debug.Log($"{name} scene:{gameObject.scene.name} sceneid reset to 0 because CurrentPrefabStage={PrefabStageUtility.GetCurrentPrefabStage()} PrefabStage={PrefabStageUtility.GetPrefabStage(gameObject)}"); + + // get path from PrefabStage for this prefab +#if UNITY_2020_1_OR_NEWER + string path = PrefabStageUtility.GetPrefabStage(gameObject).assetPath; +#else + string path = PrefabStageUtility.GetPrefabStage(gameObject).prefabAssetPath; +#endif + + AssignAssetID(path); + } + } + // is this a scene object with prefab parent? + else if (Utils.IsSceneObjectWithPrefabParent(gameObject, out GameObject prefab)) + { + AssignSceneID(); + AssignAssetID(prefab); + } + else + { + AssignSceneID(); + + // IMPORTANT: DO NOT clear assetId at runtime! + // => fixes a bug where clicking any of the NetworkIdentity + // properties (like ServerOnly/ForceHidden) at runtime would + // call OnValidate + // => OnValidate gets into this else case here because prefab + // connection isn't known at runtime + // => then we would clear the previously assigned assetId + // => and NetworkIdentity couldn't be spawned on other clients + // anymore because assetId was cleared + if (!EditorApplication.isPlaying) + { + _assetId = 0; + } + // don't log. would show a lot when pressing play in uMMORPG/uSurvival/etc. + //else Debug.Log($"Avoided clearing assetId at runtime for {name} after (probably) clicking any of the NetworkIdentity properties."); + } + } +#endif + + // OnDestroy is called for all SPAWNED NetworkIdentities + // => scene objects aren't destroyed. it's not called for them. + // + // Note: Unity will Destroy all networked objects on Scene Change, so we + // have to handle that here silently. That means we cannot have any + // warning or logging in this method. + void OnDestroy() + { + // Objects spawned from Instantiate are not allowed so are destroyed right away + // we don't want to call NetworkServer.Destroy if this is the case + if (SpawnedFromInstantiate) + return; + + // If false the object has already been unspawned + // if it is still true, then we need to unspawn it + // if destroy is already called don't call it again + if (isServer && !destroyCalled) + { + // Do not add logging to this (see above) + NetworkServer.Destroy(gameObject); + } + + if (isLocalPlayer) + { + // previously there was a bug where isLocalPlayer was + // false in OnDestroy because it was dynamically defined as: + // isLocalPlayer => NetworkClient.localPlayer == this + // we fixed it by setting isLocalPlayer manually and never + // resetting it. + // + // BUT now we need to be aware of a possible data race like in + // our rooms example: + // => GamePlayer is in world + // => player returns to room + // => GamePlayer is destroyed + // => NetworkClient.localPlayer is set to RoomPlayer + // => GamePlayer.OnDestroy is called 1 frame later + // => GamePlayer.OnDestroy 'isLocalPlayer' is true, so here we + // are trying to clear NetworkClient.localPlayer + // => which would overwrite the new RoomPlayer local player + // + // FIXED by simply only clearing if NetworkClient.localPlayer + // still points to US! + // => see also: https://github.com/vis2k/Mirror/issues/2635 + if (NetworkClient.localPlayer == this) + NetworkClient.localPlayer = null; + } + + if (isClient) + { + // ServerChangeScene doesn't send destroy messages. + // some identities may persist in DDOL. + // some are destroyed by scene change. + // if an identity is still in .owned remove it. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3308 + if (NetworkClient.connection != null) + NetworkClient.connection.owned.Remove(this); + + // if an identity is still in .spawned, remove it too. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3324 + NetworkClient.spawned.Remove(netId); + } + } + + internal void OnStartServer() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartServer should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStartServer(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal void OnStopServer() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartServer should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStopServer(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal void OnStartClient() + { + if (clientStarted) return; + + clientStarted = true; + + // Debug.Log($"OnStartClient {gameObject} netId:{netId}"); + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartClient should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + // user implemented startup + comp.OnStartClient(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal void OnStopClient() + { + // In case this object was destroyed already don't call + // OnStopClient if OnStartClient hasn't been called. + if (!clientStarted) return; + + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStopClient should be caught, so that + // one component's exception doesn't stop all other components + // from being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStopClient(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal static NetworkIdentity previousLocalPlayer = null; + internal void OnStartLocalPlayer() + { + // ensure OnStartLocalPlayer is only called once. + // Room demo would call it multiple times: + // - once from ApplySpawnPayload + // - once from OnObjectSpawnFinished + // + // to reproduce: + // - open room demo, add the 3 scenes to build settings + // - add OnStartLocalPlayer log to RoomPlayer prefab + // - build, run server-only + // - in editor, connect, press ready + // - in server, start game + // - notice multiple OnStartLocalPlayer logs in editor client + // + // explanation: + // we send the spawn message multiple times. Whenever an object changes + // authority, we send the spawn message again for the object. This is + // necessary because we need to reinitialize all variables when + // ownership change due to sync to owner feature. + // Without this static, the second time we get the spawn message we + // would call OnStartLocalPlayer again on the same object + if (previousLocalPlayer == this) + return; + previousLocalPlayer = this; + + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartLocalPlayer should be caught, so that + // one component's exception doesn't stop all other components + // from being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStartLocalPlayer(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal void OnStopLocalPlayer() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStopLocalPlayer should be caught, so that + // one component's exception doesn't stop all other components + // from being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStopLocalPlayer(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + // build dirty mask for server owner & observers (= all dirty components). + // faster to do it in one iteration instead of iterating separately. + (ulong, ulong) ServerDirtyMasks(bool initialState) + { + ulong ownerMask = 0; + ulong observerMask = 0; + + NetworkBehaviour[] components = NetworkBehaviours; + for (int i = 0; i < components.Length; ++i) + { + NetworkBehaviour component = components[i]; + + bool dirty = component.IsDirty(); + ulong nthBit = (1u << i); + + // owner needs to be considered for both SyncModes, because + // Observers mode always includes the Owner. + // + // for initial, it should always sync owner. + // for delta, only for ServerToClient and only if dirty. + // ClientToServer comes from the owner client. + if (initialState || (component.syncDirection == SyncDirection.ServerToClient && dirty)) + ownerMask |= nthBit; + + // observers need to be considered only in Observers mode + // + // for initial, it should always sync to observers. + // for delta, only if dirty. + // SyncDirection is irrelevant, as both are broadcast to + // observers which aren't the owner. + if (component.syncMode == SyncMode.Observers && (initialState || dirty)) + observerMask |= nthBit; + } + + return (ownerMask, observerMask); + } + + // build dirty mask for client. + // server always knows initialState, so we don't need it here. + ulong ClientDirtyMask() + { + ulong mask = 0; + + NetworkBehaviour[] components = NetworkBehaviours; + for (int i = 0; i < components.Length; ++i) + { + // on the client, we need to consider different sync scenarios: + // + // ServerToClient SyncDirection: + // do nothing. + // ClientToServer SyncDirection: + // serialize only if owned. + + // on client, only consider owned components with SyncDirection to server + NetworkBehaviour component = components[i]; + if (isOwned && component.syncDirection == SyncDirection.ClientToServer) + { + // set the n-th bit if dirty + // shifting from small to large numbers is varint-efficient. + if (component.IsDirty()) mask |= (1u << i); + } + } + + return mask; + } + + // check if n-th component is dirty. + // in other words, if it has the n-th bit set in the dirty mask. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool IsDirty(ulong mask, int index) + { + ulong nthBit = (ulong)(1 << index); + return (mask & nthBit) != 0; + } + + // serialize components into writer on the server. + // check ownerWritten/observersWritten to know if anything was written + // We pass dirtyComponentsMask into this function so that we can check + // if any Components are dirty before creating writers + internal void SerializeServer(bool initialState, NetworkWriter ownerWriter, NetworkWriter observersWriter) + { + // ensure NetworkBehaviours are valid before usage + ValidateComponents(); + NetworkBehaviour[] components = NetworkBehaviours; + + // check which components are dirty for owner / observers. + // this is quite complicated with SyncMode + SyncDirection. + // see the function for explanation. + // + // instead of writing a 1 byte index per component, + // we limit components to 64 bits and write one ulong instead. + // the ulong is also varint compressed for minimum bandwidth. + (ulong ownerMask, ulong observerMask) = ServerDirtyMasks(initialState); + + // if nothing dirty, then don't even write the mask. + // otherwise, every unchanged object would send a 1 byte dirty mask! + if (ownerMask != 0) Compression.CompressVarUInt(ownerWriter, ownerMask); + if (observerMask != 0) Compression.CompressVarUInt(observersWriter, observerMask); + + // serialize all components + // perf: only iterate if either dirty mask has dirty bits. + if ((ownerMask | observerMask) != 0) + { + for (int i = 0; i < components.Length; ++i) + { + NetworkBehaviour comp = components[i]; + + // is the component dirty for anyone (owner or observers)? + // may be serialized to owner, observer, both, or neither. + // + // OnSerialize should only be called once. + // this is faster, and it cleaner because it may set + // internal state, counters, logs, etc. + // + // previously we always serialized to owner and then copied + // the serialization to observers. however, since + // SyncDirection it's not guaranteed to be in owner anymore. + // so we need to serialize to temporary writer first. + // and then copy as needed. + bool ownerDirty = IsDirty(ownerMask, i); + bool observersDirty = IsDirty(observerMask, i); + if (ownerDirty || observersDirty) + { + // serialize into helper writer + using (NetworkWriterPooled temp = NetworkWriterPool.Get()) + { + comp.Serialize(temp, initialState); + ArraySegment segment = temp.ToArraySegment(); + + // copy to owner / observers as needed + if (ownerDirty) ownerWriter.WriteBytes(segment.Array, segment.Offset, segment.Count); + if (observersDirty) observersWriter.WriteBytes(segment.Array, segment.Offset, segment.Count); + } + + // clear dirty bits for the components that we serialized. + // do not clear for _all_ components, only the ones that + // were dirty and had their syncInterval elapsed. + // + // we don't want to clear bits before the syncInterval + // was elapsed, as then they wouldn't be synced. + // + // only clear for delta, not for full (spawn messages). + // otherwise if a player joins, we serialize monster, + // and shouldn't clear dirty bits not yet synced to + // other players. + if (!initialState) comp.ClearAllDirtyBits(); + } + } + } + } + + // serialize components into writer on the client. + internal void SerializeClient(NetworkWriter writer) + { + // ensure NetworkBehaviours are valid before usage + ValidateComponents(); + NetworkBehaviour[] components = NetworkBehaviours; + + // check which components are dirty. + // this is quite complicated with SyncMode + SyncDirection. + // see the function for explanation. + // + // instead of writing a 1 byte index per component, + // we limit components to 64 bits and write one ulong instead. + // the ulong is also varint compressed for minimum bandwidth. + ulong dirtyMask = ClientDirtyMask(); + + // varint compresses the mask to 1 byte in most cases. + // instead of writing an 8 byte ulong. + // 7 components fit into 1 byte. (previously 7 bytes) + // 11 components fit into 2 bytes. (previously 11 bytes) + // 16 components fit into 3 bytes. (previously 16 bytes) + // TODO imer: server knows amount of comps, write N bytes instead + + // if nothing dirty, then don't even write the mask. + // otherwise, every unchanged object would send a 1 byte dirty mask! + if (dirtyMask != 0) Compression.CompressVarUInt(writer, dirtyMask); + + // serialize all components + // perf: only iterate if dirty mask has dirty bits. + if (dirtyMask != 0) + { + // serialize all components + for (int i = 0; i < components.Length; ++i) + { + NetworkBehaviour comp = components[i]; + + // is this component dirty? + // reuse the mask instead of calling comp.IsDirty() again here. + if (IsDirty(dirtyMask, i)) + // if (isOwned && component.syncDirection == SyncDirection.ClientToServer) + { + // serialize into writer. + // server always knows initialState, we never need to send it + comp.Serialize(writer, false); + + // clear dirty bits for the components that we serialized. + // do not clear for _all_ components, only the ones that + // were dirty and had their syncInterval elapsed. + // + // we don't want to clear bits before the syncInterval + // was elapsed, as then they wouldn't be synced. + comp.ClearAllDirtyBits(); + } + } + } + } + + // deserialize components from the client on the server. + // there's no 'initialState'. server always knows the initial state. + internal bool DeserializeServer(NetworkReader reader) + { + // ensure NetworkBehaviours are valid before usage + ValidateComponents(); + NetworkBehaviour[] components = NetworkBehaviours; + + // first we deserialize the varinted dirty mask + ulong mask = Compression.DecompressVarUInt(reader); + + // now deserialize every dirty component + for (int i = 0; i < components.Length; ++i) + { + // was this one dirty? + if (IsDirty(mask, i)) + { + NetworkBehaviour comp = components[i]; + + // safety check to ensure clients can only modify their own + // ClientToServer components, nothing else. + if (comp.syncDirection == SyncDirection.ClientToServer) + { + // deserialize this component + // server always knows the initial state (initial=false) + // disconnect if failed, to prevent exploits etc. + if (!comp.Deserialize(reader, false)) return false; + + // server received state from the owner client. + // set dirty so it's broadcast to other clients too. + // + // note that we set the _whole_ component as dirty. + // everything will be broadcast to others. + // SetSyncVarDirtyBits() would be nicer, but not all + // components use [SyncVar]s. + comp.SetDirty(); + } + } + } + + // successfully deserialized everything + return true; + } + + // deserialize components from server on the client. + internal void DeserializeClient(NetworkReader reader, bool initialState) + { + // ensure NetworkBehaviours are valid before usage + ValidateComponents(); + NetworkBehaviour[] components = NetworkBehaviours; + + // first we deserialize the varinted dirty mask + ulong mask = Compression.DecompressVarUInt(reader); + + // now deserialize every dirty component + for (int i = 0; i < components.Length; ++i) + { + // was this one dirty? + if (IsDirty(mask, i)) + { + // deserialize this component + NetworkBehaviour comp = components[i]; + comp.Deserialize(reader, initialState); + } + } + } + + // get cached serialization for this tick (or serialize if none yet). + // IMPORTANT: int tick avoids floating point inaccuracy over days/weeks. + // calls SerializeServer, so this function is to be called on server. + internal NetworkIdentitySerialization GetServerSerializationAtTick(int tick) + { + // only rebuild serialization once per tick. reuse otherwise. + // except for tests, where Time.frameCount never increases. + // so during tests, we always rebuild. + // (otherwise [SyncVar] changes would never be serialized in tests) + // + // NOTE: != instead of < because int.max+1 overflows at some point. + if (lastSerialization.tick != tick +#if UNITY_EDITOR + || !Application.isPlaying +#endif + ) + { + // reset + lastSerialization.ownerWriter.Position = 0; + lastSerialization.observersWriter.Position = 0; + + // serialize + SerializeServer(false, + lastSerialization.ownerWriter, + lastSerialization.observersWriter); + + // set tick + lastSerialization.tick = tick; + //Debug.Log($"{name} (netId={netId}) serialized for tick={tickTimeStamp}"); + } + + // return it + return lastSerialization; + } + + internal void AddObserver(NetworkConnectionToClient conn) + { + if (observers.ContainsKey(conn.connectionId)) + { + // if we try to add a connectionId that was already added, then + // we may have generated one that was already in use. + return; + } + + // Debug.Log($"Added observer: {conn.address} added for {gameObject}"); + + // if we previously had no observers, then clear all dirty bits once. + // a monster's health may have changed while it had no observers. + // but that change (= the dirty bits) don't matter as soon as the + // first observer comes. + // -> first observer gets full spawn packet + // -> afterwards it gets delta packet + // => if we don't clear previous dirty bits, observer would get + // the health change because the bit was still set. + // => ultimately this happens because spawn doesn't reset dirty + // bits + // => which happens because spawn happens separately, instead of + // in Broadcast() (which will be changed in the future) + // + // NOTE that NetworkServer.Broadcast previously cleared dirty bits + // for ALL SPAWNED that don't have observers. that was super + // expensive. doing it when adding the first observer has the + // same result, without the O(N) iteration in Broadcast(). + // + // TODO remove this after moving spawning into Broadcast()! + if (observers.Count == 0) + { + ClearAllComponentsDirtyBits(); + } + + observers[conn.connectionId] = conn; + conn.AddToObserving(this); + } + + // clear all component's dirty bits no matter what + internal void ClearAllComponentsDirtyBits() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + comp.ClearAllDirtyBits(); + } + } + + // this is used when a connection is destroyed, since the "observers" property is read-only + internal void RemoveObserver(NetworkConnection conn) + { + observers.Remove(conn.connectionId); + } + + /// Assign control of an object to a client via the client's NetworkConnection. + // This causes hasAuthority to be set on the client that owns the object, + // and NetworkBehaviour.OnStartAuthority will be called on that client. + // This object then will be in the NetworkConnection.clientOwnedObjects + // list for the connection. + // + // Authority can be removed with RemoveClientAuthority. Only one client + // can own an object at any time. This does not need to be called for + // player objects, as their authority is setup automatically. + public bool AssignClientAuthority(NetworkConnectionToClient conn) + { + if (!isServer) + { + Debug.LogError("AssignClientAuthority can only be called on the server for spawned objects."); + return false; + } + + if (conn == null) + { + Debug.LogError($"AssignClientAuthority for {gameObject} owner cannot be null. Use RemoveClientAuthority() instead."); + return false; + } + + if (connectionToClient != null && conn != connectionToClient) + { + Debug.LogError($"AssignClientAuthority for {gameObject} already has an owner. Use RemoveClientAuthority() first."); + return false; + } + + SetClientOwner(conn); + + // The client will match to the existing object + NetworkServer.SendChangeOwnerMessage(this, conn); + + clientAuthorityCallback?.Invoke(conn, this, true); + + return true; + } + + // used when adding players + internal void SetClientOwner(NetworkConnectionToClient conn) + { + // do nothing if it already has an owner + if (connectionToClient != null && conn != connectionToClient) + { + Debug.LogError($"Object {this} netId={netId} already has an owner. Use RemoveClientAuthority() first", this); + return; + } + + // otherwise set the owner connection + connectionToClient = conn; + } + + /// Removes ownership for an object. + // Applies to objects that had authority set by AssignClientAuthority, + // or NetworkServer.Spawn with a NetworkConnection parameter included. + // Authority cannot be removed for player objects. + public void RemoveClientAuthority() + { + if (!isServer) + { + Debug.LogError("RemoveClientAuthority can only be called on the server for spawned objects."); + return; + } + + if (connectionToClient?.identity == this) + { + Debug.LogError("RemoveClientAuthority cannot remove authority for a player object"); + return; + } + + if (connectionToClient != null) + { + clientAuthorityCallback?.Invoke(connectionToClient, this, false); + NetworkConnectionToClient previousOwner = connectionToClient; + connectionToClient = null; + NetworkServer.SendChangeOwnerMessage(this, previousOwner); + } + } + + // Reset is called when the user hits the Reset button in the + // Inspector's context menu or when adding the component the first time. + // This function is only called in editor mode. + // + // Reset() seems to be called only for Scene objects. + // we can't destroy them (they are always in the scene). + // instead we disable them and call Reset(). + // + // Do not reset SyncObjects from Reset + // - Unspawned objects need to retain their list contents + // - They may be respawned, especially players, but others as well. + // + // OLD COMMENT: + // Marks the identity for future reset, this is because we cant reset + // the identity during destroy as people might want to be able to read + // the members inside OnDestroy(), and we have no way of invoking reset + // after OnDestroy is called. + internal void ResetState() + { + hasSpawned = false; + clientStarted = false; + isClient = false; + isServer = false; + //isLocalPlayer = false; <- cleared AFTER ClearLocalPlayer below! + + // remove authority flag. This object may be unspawned, not destroyed, on client. + isOwned = false; + NotifyAuthority(); + + netId = 0; + connectionToServer = null; + connectionToClient = null; + + ClearObservers(); + + // clear local player if it was the local player, + // THEN reset isLocalPlayer AFTERWARDS + if (isLocalPlayer) + { + // only clear NetworkClient.localPlayer IF IT POINTS TO US! + // see OnDestroy() comments. it does the same. + // (https://github.com/vis2k/Mirror/issues/2635) + if (NetworkClient.localPlayer == this) + NetworkClient.localPlayer = null; + } + + previousLocalPlayer = null; + isLocalPlayer = false; + } + + bool hadAuthority; + internal void NotifyAuthority() + { + if (!hadAuthority && isOwned) + OnStartAuthority(); + if (hadAuthority && !isOwned) + OnStopAuthority(); + hadAuthority = isOwned; + } + + internal void OnStartAuthority() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartAuthority should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStartAuthority(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal void OnStopAuthority() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStopAuthority should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStopAuthority(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + // Called when NetworkIdentity is destroyed + internal void ClearObservers() + { + foreach (NetworkConnectionToClient conn in observers.Values) + { + conn.RemoveFromObserving(this, true); + } + observers.Clear(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkIdentity.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkIdentity.cs.meta new file mode 100644 index 0000000000..b0f9bde714 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkIdentity.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 9b91ecbcc199f4492b9a91e820070131 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkIdentity.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkLoop.cs b/Assets/ImportedAssets/Mirror/Core/NetworkLoop.cs new file mode 100644 index 0000000000..a9cd49038e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkLoop.cs @@ -0,0 +1,211 @@ +// our ideal update looks like this: +// transport.process_incoming() +// update_world() +// transport.process_outgoing() +// +// this way we avoid unnecessary latency for low-ish server tick rates. +// for example, if we were to use this tick: +// transport.process_incoming/outgoing() +// update_world() +// +// then anything sent in update_world wouldn't be actually sent out by the +// transport until the next frame. if server runs at 60Hz, then this can add +// 16ms latency for every single packet. +// +// => instead we process incoming, update world, process_outgoing in the same +// frame. it's more clear (no race conditions) and lower latency. +// => we need to add custom Update functions to the Unity engine: +// NetworkEarlyUpdate before Update()/FixedUpdate() +// NetworkLateUpdate after LateUpdate() +// this way the user can update the world in Update/FixedUpdate/LateUpdate +// and networking still runs before/after those functions no matter what! +// => see also: https://docs.unity3d.com/Manual/ExecutionOrder.html +// => update order: +// * we add to the end of EarlyUpdate so it runs after any Unity initializations +// * we add to the end of PreLateUpdate so it runs after LateUpdate(). adding +// to the beginning of PostLateUpdate doesn't actually work. +using System; +using UnityEngine; +using UnityEngine.LowLevel; +using UnityEngine.PlayerLoop; + +namespace Mirror +{ + public static class NetworkLoop + { + // helper enum to add loop to begin/end of subSystemList + internal enum AddMode { Beginning, End } + + // callbacks for others to hook into if they need Early/LateUpdate. + public static Action OnEarlyUpdate; + public static Action OnLateUpdate; + + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + static void ResetStatics() + { + OnEarlyUpdate = null; + OnLateUpdate = null; + } + + // helper function to find an update function's index in a player loop + // type. this is used for testing to guarantee our functions are added + // at the beginning/end properly. + internal static int FindPlayerLoopEntryIndex(PlayerLoopSystem.UpdateFunction function, PlayerLoopSystem playerLoop, Type playerLoopSystemType) + { + // did we find the type? e.g. EarlyUpdate/PreLateUpdate/etc. + if (playerLoop.type == playerLoopSystemType) + return Array.FindIndex(playerLoop.subSystemList, (elem => elem.updateDelegate == function)); + + // recursively keep looking + if (playerLoop.subSystemList != null) + { + for (int i = 0; i < playerLoop.subSystemList.Length; ++i) + { + int index = FindPlayerLoopEntryIndex(function, playerLoop.subSystemList[i], playerLoopSystemType); + if (index != -1) return index; + } + } + return -1; + } + + // MODIFIED AddSystemToPlayerLoopList from Unity.Entities.ScriptBehaviourUpdateOrder (ECS) + // + // => adds an update function to the Unity internal update type. + // => Unity has different update loops: + // https://medium.com/@thebeardphantom/unity-2018-and-playerloop-5c46a12a677 + // EarlyUpdate + // FixedUpdate + // PreUpdate + // Update + // PreLateUpdate + // PostLateUpdate + // + // function: the custom update function to add + // IMPORTANT: according to a comment in Unity.Entities.ScriptBehaviourUpdateOrder, + // the UpdateFunction can not be virtual because + // Mono 4.6 has problems invoking virtual methods + // as delegates from native! + // ownerType: the .type to fill in so it's obvious who the new function + // belongs to. seems to be mostly for debugging. pass any. + // addMode: prepend or append to update list + internal static bool AddToPlayerLoop(PlayerLoopSystem.UpdateFunction function, Type ownerType, ref PlayerLoopSystem playerLoop, Type playerLoopSystemType, AddMode addMode) + { + // did we find the type? e.g. EarlyUpdate/PreLateUpdate/etc. + if (playerLoop.type == playerLoopSystemType) + { + // debugging + //Debug.Log($"Found playerLoop of type {playerLoop.type} with {playerLoop.subSystemList.Length} Functions:"); + //foreach (PlayerLoopSystem sys in playerLoop.subSystemList) + // Debug.Log($" ->{sys.type}"); + + // make sure the function wasn't added yet. + // with domain reload disabled, it would otherwise be added twice: + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3392 + if (Array.FindIndex(playerLoop.subSystemList, (s => s.updateDelegate == function)) != -1) + { + // loop contains the function, so return true. + return true; + } + + // resize & expand subSystemList to fit one more entry + int oldListLength = (playerLoop.subSystemList != null) ? playerLoop.subSystemList.Length : 0; + Array.Resize(ref playerLoop.subSystemList, oldListLength + 1); + + // IMPORTANT: always insert a FRESH PlayerLoopSystem! + // We CAN NOT resize and then OVERWRITE an entry's type/loop. + // => PlayerLoopSystem has native IntPtr loop members + // => forgetting to clear those would cause undefined behaviour! + // see also: https://github.com/vis2k/Mirror/pull/2652 + PlayerLoopSystem system = new PlayerLoopSystem { + type = ownerType, + updateDelegate = function + }; + + // prepend our custom loop to the beginning + if (addMode == AddMode.Beginning) + { + // shift to the right, write into first array element + Array.Copy(playerLoop.subSystemList, 0, playerLoop.subSystemList, 1, playerLoop.subSystemList.Length - 1); + playerLoop.subSystemList[0] = system; + } + // append our custom loop to the end + else if (addMode == AddMode.End) + { + // simply write into last array element + playerLoop.subSystemList[oldListLength] = system; + } + + // debugging + //Debug.Log($"New playerLoop of type {playerLoop.type} with {playerLoop.subSystemList.Length} Functions:"); + //foreach (PlayerLoopSystem sys in playerLoop.subSystemList) + // Debug.Log($" ->{sys.type}"); + + return true; + } + + // recursively keep looking + if (playerLoop.subSystemList != null) + { + for (int i = 0; i < playerLoop.subSystemList.Length; ++i) + { + if (AddToPlayerLoop(function, ownerType, ref playerLoop.subSystemList[i], playerLoopSystemType, addMode)) + return true; + } + } + return false; + } + + // hook into Unity runtime to actually add our custom functions + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + static void RuntimeInitializeOnLoad() + { + //Debug.Log("Mirror: adding Network[Early/Late]Update to Unity..."); + + // get loop + // 2019 has GetCURRENTPlayerLoop which is safe to use without + // breaking other custom system's custom loops. + // see also: https://github.com/vis2k/Mirror/pull/2627/files + PlayerLoopSystem playerLoop = PlayerLoop.GetCurrentPlayerLoop(); + + // add NetworkEarlyUpdate to the end of EarlyUpdate so it runs after + // any Unity initializations but before the first Update/FixedUpdate + AddToPlayerLoop(NetworkEarlyUpdate, typeof(NetworkLoop), ref playerLoop, typeof(EarlyUpdate), AddMode.End); + + // add NetworkLateUpdate to the end of PreLateUpdate so it runs after + // LateUpdate(). adding to the beginning of PostLateUpdate doesn't + // actually work. + AddToPlayerLoop(NetworkLateUpdate, typeof(NetworkLoop), ref playerLoop, typeof(PreLateUpdate), AddMode.End); + + // set the new loop + PlayerLoop.SetPlayerLoop(playerLoop); + } + + static void NetworkEarlyUpdate() + { + // loop functions run in edit mode and in play mode. + // however, we only want to call NetworkServer/Client in play mode. + if (!Application.isPlaying) return; + + NetworkTime.EarlyUpdate(); + //Debug.Log($"NetworkEarlyUpdate {Time.time}"); + NetworkServer.NetworkEarlyUpdate(); + NetworkClient.NetworkEarlyUpdate(); + // invoke event after mirror has done it's early updating. + OnEarlyUpdate?.Invoke(); + } + + static void NetworkLateUpdate() + { + // loop functions run in edit mode and in play mode. + // however, we only want to call NetworkServer/Client in play mode. + if (!Application.isPlaying) return; + + //Debug.Log($"NetworkLateUpdate {Time.time}"); + // invoke event before mirror does its final late updating. + OnLateUpdate?.Invoke(); + NetworkServer.NetworkLateUpdate(); + NetworkClient.NetworkLateUpdate(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkLoop.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkLoop.cs.meta new file mode 100644 index 0000000000..dc686cadc3 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkLoop.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 2c6cec4e279774b919386e05545317b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkLoop.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkManager.cs b/Assets/ImportedAssets/Mirror/Core/NetworkManager.cs new file mode 100644 index 0000000000..ef21e6c9fd --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkManager.cs @@ -0,0 +1,1515 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.Serialization; + +namespace Mirror +{ + public enum PlayerSpawnMethod { Random, RoundRobin } + public enum NetworkManagerMode { Offline, ServerOnly, ClientOnly, Host } + public enum HeadlessStartOptions { DoNothing, AutoStartServer, AutoStartClient } + + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Manager")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-manager")] + public class NetworkManager : MonoBehaviour + { + /// Enable to keep NetworkManager alive when changing scenes. + // This should be set if your game has a single NetworkManager that exists for the lifetime of the process. If there is a NetworkManager in each scene, then this should not be set. + [Header("Configuration")] + [FormerlySerializedAs("m_DontDestroyOnLoad")] + [Tooltip("Should the Network Manager object be persisted through scene changes?")] + public bool dontDestroyOnLoad = true; + + /// Multiplayer games should always run in the background so the network doesn't time out. + [FormerlySerializedAs("m_RunInBackground")] + [Tooltip("Multiplayer games should always run in the background so the network doesn't time out.")] + public bool runInBackground = true; + + /// Should the server auto-start when 'Server Build' is checked in build settings + [Header("Auto-Start Options")] + + [Tooltip("Choose whether Server or Client should auto-start in headless builds")] + public HeadlessStartOptions headlessStartMode = HeadlessStartOptions.DoNothing; + + [Tooltip("Headless Start Mode in Editor\nwhen enabled, headless start mode will be used in editor as well.")] + public bool editorAutoStart; + + /// Server Update frequency, per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE. + [Tooltip("Server / Client send rate per second.\nUse 60-100Hz for fast paced games like Counter-Strike to minimize latency.\nUse around 30Hz for games like WoW to minimize computations.\nUse around 1-10Hz for slow paced games like EVE.")] + [FormerlySerializedAs("serverTickRate")] + public int sendRate = 60; + + // Deprecated 2023-11-25 + // Using SerializeField and HideInInspector to self-correct for being + // replaced by headlessStartMode. This can be removed in the future. + // See OnValidate() for how we handle this. + [Obsolete("Deprecated - Use headlessStartMode instead.")] + [FormerlySerializedAs("autoStartServerBuild"), SerializeField, HideInInspector] + public bool autoStartServerBuild = true; + + // Deprecated 2023-11-25 + // Using SerializeField and HideInInspector to self-correct for being + // replaced by headlessStartMode. This can be removed in the future. + // See OnValidate() for how we handle this. + [Obsolete("Deprecated - Use headlessStartMode instead.")] + [FormerlySerializedAs("autoConnectClientBuild"), SerializeField, HideInInspector] + public bool autoConnectClientBuild; + + // client send rate follows server send rate to avoid errors for now + /// Client Update frequency, per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE. + // [Tooltip("Client broadcasts 'sendRate' times per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE.")] + // public int clientSendRate = 30; // 33 ms + + /// Automatically switch to this scene upon going offline (on start / on disconnect / on shutdown). + [Header("Scene Management")] + [Scene] + [FormerlySerializedAs("m_OfflineScene")] + [Tooltip("Scene that Mirror will switch to when the client or server is stopped")] + public string offlineScene = ""; + + /// Automatically switch to this scene upon going online (after connect/startserver). + [Scene] + [FormerlySerializedAs("m_OnlineScene")] + [Tooltip("Scene that Mirror will switch to when the server is started. Clients will recieve a Scene Message to load the server's current scene when they connect.")] + public string onlineScene = ""; + + // transport layer + [Header("Network Info")] + [Tooltip("Transport component attached to this object that server and client will use to connect")] + public Transport transport; + + /// Server's address for clients to connect to. + [FormerlySerializedAs("m_NetworkAddress")] + [Tooltip("Network Address where the client should connect to the server. Server does not use this for anything.")] + public string networkAddress = "localhost"; + + /// The maximum number of concurrent network connections to support. + [FormerlySerializedAs("m_MaxConnections")] + [Tooltip("Maximum number of concurrent connections.")] + public int maxConnections = 100; + + // Mirror global disconnect inactive option, independent of Transport. + // not all Transports do this properly, and it's easiest to configure this just once. + // this is very useful for some projects, keep it. + [Tooltip("When enabled, the server automatically disconnects inactive connections after the configured timeout.")] + public bool disconnectInactiveConnections; + + [Tooltip("Timeout in seconds for server to automatically disconnect inactive connections if 'disconnectInactiveConnections' is enabled.")] + public float disconnectInactiveTimeout = 60f; + + [Header("Authentication")] + [Tooltip("Authentication component attached to this object")] + public NetworkAuthenticator authenticator; + + /// The default prefab to be used to create player objects on the server. + // Player objects are created in the default handler for AddPlayer() on + // the server. Implementing OnServerAddPlayer overrides this behaviour. + [Header("Player Object")] + [FormerlySerializedAs("m_PlayerPrefab")] + [Tooltip("Prefab of the player object. Prefab must have a Network Identity component. May be an empty game object or a full avatar.")] + public GameObject playerPrefab; + + /// Enable to automatically create player objects on connect and on scene change. + [FormerlySerializedAs("m_AutoCreatePlayer")] + [Tooltip("Should Mirror automatically spawn the player after scene change?")] + public bool autoCreatePlayer = true; + + /// Where to spawn players. + [FormerlySerializedAs("m_PlayerSpawnMethod")] + [Tooltip("Round Robin or Random order of Start Position selection")] + public PlayerSpawnMethod playerSpawnMethod; + + /// Prefabs that can be spawned over the network need to be registered here. + [FormerlySerializedAs("m_SpawnPrefabs"), HideInInspector] + public List spawnPrefabs = new List(); + + /// List of transforms populated by NetworkStartPositions + public static List startPositions = new List(); + public static int startPositionIndex; + + [Header("Security")] + [Tooltip("For security, it is recommended to disconnect a player if a networked action triggers an exception\nThis could prevent components being accessed in an undefined state, which may be an attack vector for exploits.\nHowever, some games may want to allow exceptions in order to not interrupt the player's experience.")] + public bool exceptionsDisconnect = true; // security by default + + [Header("Snapshot Interpolation")] + public SnapshotInterpolationSettings snapshotSettings = new SnapshotInterpolationSettings(); + + [Header("Connection Quality")] + [Tooltip("Method to use for connection quality evaluation.\nSimple: based on rtt and jitter.\nPragmatic: based on snapshot interpolation adjustment.")] + public ConnectionQualityMethod evaluationMethod; + + [Tooltip("Interval in seconds to evaluate connection quality.\nSet to 0 to disable connection quality evaluation.")] + [Range(0, 60)] + [FormerlySerializedAs("connectionQualityInterval")] + public float evaluationInterval = 3; + + [Header("Interpolation UI - Requires Editor / Dev Build")] + public bool timeInterpolationGui = false; + + /// The one and only NetworkManager + public static NetworkManager singleton { get; internal set; } + + /// Number of active player objects across all connections on the server. + public int numPlayers => NetworkServer.connections.Count(kv => kv.Value.identity != null); + + /// True if the server is running or client is connected/connecting. + public bool isNetworkActive => NetworkServer.active || NetworkClient.active; + + // TODO remove this + // internal for tests + internal static NetworkConnection clientReadyConnection; + + /// True if the client loaded a new scene when connecting to the server. + // This is set before OnClientConnect is called, so it can be checked + // there to perform different logic if a scene load occurred. + protected bool clientLoadedScene; + + // helper enum to know if we started the networkmanager as server/client/host. + // -> this is necessary because when StartHost changes server scene to + // online scene, FinishLoadScene is called and the host client isn't + // connected yet (no need to connect it before server was fully set up). + // in other words, we need this to know which mode we are running in + // during FinishLoadScene. + public NetworkManagerMode mode { get; private set; } + + // virtual so that inheriting classes' OnValidate() can call base.OnValidate() too + public virtual void OnValidate() + { +#pragma warning disable 618 + // autoStartServerBuild and autoConnectClientBuild are now obsolete, but to avoid + // a breaking change we'll set headlessStartMode to what the user had set before. + // + // headlessStartMode defaults to DoNothing, so if the user had neither of these + // set, then it will remain as DoNothing, and if they set headlessStartMode to + // any selection in the inspector it won't get changed back. + if (autoStartServerBuild) + headlessStartMode = HeadlessStartOptions.AutoStartServer; + else if (autoConnectClientBuild) + headlessStartMode = HeadlessStartOptions.AutoStartClient; + + // Setting both to false here prevents this code from fighting with user + // selection in the inspector, and they're both SerialisedField's. + autoStartServerBuild = false; + autoConnectClientBuild = false; +#pragma warning restore 618 + + // always >= 0 + maxConnections = Mathf.Max(maxConnections, 0); + + if (playerPrefab != null && !playerPrefab.TryGetComponent(out NetworkIdentity _)) + { + Debug.LogError("NetworkManager - Player Prefab must have a NetworkIdentity."); + playerPrefab = null; + } + + // This avoids the mysterious "Replacing existing prefab with assetId ... Old prefab 'Player', New prefab 'Player'" warning. + if (playerPrefab != null && spawnPrefabs.Contains(playerPrefab)) + { + Debug.LogWarning("NetworkManager - Player Prefab doesn't need to be in Spawnable Prefabs list too. Removing it."); + spawnPrefabs.Remove(playerPrefab); + } + } + + // virtual so that inheriting classes' Reset() can call base.Reset() too + // Reset only gets called when the component is added or the user resets the component + // Thats why we validate these things that only need to be validated on adding the NetworkManager here + // If we would do it in OnValidate() then it would run this everytime a value changes + public virtual void Reset() + { + // make sure someone doesn't accidentally add another NetworkManager + // need transform.root because when adding to a child, the parent's + // Reset isn't called. + foreach (NetworkManager manager in transform.root.GetComponentsInChildren()) + { + if (manager != this) + { + Debug.LogError($"{name} detected another component of type {typeof(NetworkManager)} in its hierarchy on {manager.name}. There can only be one, please remove one of them."); + // return early so that transport component isn't auto-added + // to the duplicate NetworkManager. + return; + } + } + } + + // virtual so that inheriting classes' Awake() can call base.Awake() too + public virtual void Awake() + { + // Don't allow collision-destroyed second instance to continue. + if (!InitializeSingleton()) return; + + // Apply configuration in Awake once already + ApplyConfiguration(); + + // Set the networkSceneName to prevent a scene reload + // if client connection to server fails. + networkSceneName = offlineScene; + + // setup OnSceneLoaded callback + SceneManager.sceneLoaded += OnSceneLoaded; + } + + // virtual so that inheriting classes' Start() can call base.Start() too + public virtual void Start() + { + // Auto-start headless server or client. + // + // We can't do this in Awake because Awake is for initialization + // and some transports might not be ready until Start. + // + // Auto-starting in Editor is useful for debugging, so that can + // be enabled with editorAutoStart. + if (Utils.IsHeadless()) + { + if (!Application.isEditor || editorAutoStart) + switch (headlessStartMode) + { + case HeadlessStartOptions.AutoStartServer: + StartServer(); + break; + case HeadlessStartOptions.AutoStartClient: + StartClient(); + break; + } + } + } + + // make sure to call base.Update() when overwriting + public virtual void Update() + { + ApplyConfiguration(); + } + + // virtual so that inheriting classes' LateUpdate() can call base.LateUpdate() too + public virtual void LateUpdate() + { + UpdateScene(); + } + + //////////////////////////////////////////////////////////////////////// + + // keep the online scene change check in a separate function. + // only change scene if the requested online scene is not blank, and is not already loaded. + bool IsServerOnlineSceneChangeNeeded() => + !string.IsNullOrWhiteSpace(onlineScene) && + !Utils.IsSceneActive(onlineScene) && + onlineScene != offlineScene; + + // NetworkManager exposes some NetworkServer/Client configuration. + // we apply it every Update() in order to avoid two sources of truth. + // fixes issues where NetworkServer.sendRate was never set because + // NetworkManager.StartServer was never called, etc. + // => all exposed settings should be applied at all times if NM exists. + void ApplyConfiguration() + { + NetworkServer.tickRate = sendRate; + NetworkClient.snapshotSettings = snapshotSettings; + NetworkClient.connectionQualityInterval = evaluationInterval; + NetworkClient.connectionQualityMethod = evaluationMethod; + } + + // full server setup code, without spawning objects yet + void SetupServer() + { + // Debug.Log("NetworkManager SetupServer"); + InitializeSingleton(); + + // apply settings before initializing anything + NetworkServer.disconnectInactiveConnections = disconnectInactiveConnections; + NetworkServer.disconnectInactiveTimeout = disconnectInactiveTimeout; + NetworkServer.exceptionsDisconnect = exceptionsDisconnect; + + if (runInBackground) + Application.runInBackground = true; + + if (authenticator != null) + { + authenticator.OnStartServer(); + authenticator.OnServerAuthenticated.AddListener(OnServerAuthenticated); + } + + ConfigureHeadlessFrameRate(); + + // start listening to network connections + NetworkServer.Listen(maxConnections); + + // this must be after Listen(), since that registers the default message handlers + RegisterServerMessages(); + + // do not call OnStartServer here yet. + // this is up to the caller. different for server-only vs. host mode. + } + + /// Starts the server, listening for incoming connections. + public void StartServer() + { + if (NetworkServer.active) + { + Debug.LogWarning("Server already started."); + return; + } + + mode = NetworkManagerMode.ServerOnly; + + // StartServer is inherently ASYNCHRONOUS (=doesn't finish immediately) + // + // Here is what it does: + // Listen + // if onlineScene: + // LoadSceneAsync + // ... + // FinishLoadSceneServerOnly + // SpawnObjects + // else: + // SpawnObjects + // + // there is NO WAY to make it synchronous because both LoadSceneAsync + // and LoadScene do not finish loading immediately. as long as we + // have the onlineScene feature, it will be asynchronous! + + SetupServer(); + + // call OnStartServer AFTER Listen, so that NetworkServer.active is + // true and we can call NetworkServer.Spawn in OnStartServer + // overrides. + // (useful for loading & spawning stuff from database etc.) + // + // note: there is no risk of someone connecting after Listen() and + // before OnStartServer() because this all runs in one thread + // and we don't start processing connects until Update. + OnStartServer(); + + // scene change needed? then change scene and spawn afterwards. + if (IsServerOnlineSceneChangeNeeded()) + { + ServerChangeScene(onlineScene); + } + // otherwise spawn directly + else + { + NetworkServer.SpawnObjects(); + } + } + + void SetupClient() + { + InitializeSingleton(); + +#pragma warning disable 618 + // Remove when OnConnectionQualityChanged is removed. + NetworkClient.onConnectionQualityChanged += OnConnectionQualityChanged; +#pragma warning restore 618 + + // apply settings before initializing anything + NetworkClient.exceptionsDisconnect = exceptionsDisconnect; + // NetworkClient.sendRate = clientSendRate; + + if (runInBackground) + Application.runInBackground = true; + + if (authenticator != null) + { + authenticator.OnStartClient(); + authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated); + } + + } + + /// Starts the client, connects it to the server with networkAddress. + public void StartClient() + { + // Do checks and short circuits before setting anything up. + // If / when we retry, we won't have conflict issues. + if (NetworkClient.active) + { + Debug.LogWarning("Client already started."); + return; + } + + if (string.IsNullOrWhiteSpace(networkAddress)) + { + Debug.LogError("Must set the Network Address field in the manager"); + return; + } + + mode = NetworkManagerMode.ClientOnly; + + SetupClient(); + + // In case this is a headless client... + ConfigureHeadlessFrameRate(); + + RegisterClientMessages(); + + NetworkClient.Connect(networkAddress); + + OnStartClient(); + } + + /// Starts the client, connects it to the server via Uri + public void StartClient(Uri uri) + { + if (NetworkClient.active) + { + Debug.LogWarning("Client already started."); + return; + } + + mode = NetworkManagerMode.ClientOnly; + + SetupClient(); + + RegisterClientMessages(); + + // Debug.Log($"NetworkManager StartClient address:{uri}"); + networkAddress = uri.Host; + + NetworkClient.Connect(uri); + + OnStartClient(); + } + + /// Starts a network "host" - a server and client in the same application. + public void StartHost() + { + if (NetworkServer.active || NetworkClient.active) + { + Debug.LogWarning("Server or Client already started."); + return; + } + + mode = NetworkManagerMode.Host; + + // StartHost is inherently ASYNCHRONOUS (=doesn't finish immediately) + // + // Here is what it does: + // Listen + // ConnectHost + // if onlineScene: + // LoadSceneAsync + // ... + // FinishLoadSceneHost + // FinishStartHost + // SpawnObjects + // StartHostClient <= not guaranteed to happen after SpawnObjects if onlineScene is set! + // ClientAuth + // success: server sends changescene msg to client + // else: + // FinishStartHost + // + // there is NO WAY to make it synchronous because both LoadSceneAsync + // and LoadScene do not finish loading immediately. as long as we + // have the onlineScene feature, it will be asynchronous! + + // setup server first + SetupServer(); + + // scene change needed? then change scene and spawn afterwards. + // => BEFORE host client connects. if client auth succeeds then the + // server tells it to load 'onlineScene'. we can't do that if + // server is still in 'offlineScene'. so load on server first. + if (IsServerOnlineSceneChangeNeeded()) + { + // call FinishStartHost after changing scene. + finishStartHostPending = true; + ServerChangeScene(onlineScene); + } + // otherwise call FinishStartHost directly + else + { + FinishStartHost(); + } + } + + // This may be set true in StartHost and is evaluated in FinishStartHost + bool finishStartHostPending; + + // FinishStartHost is guaranteed to be called after the host server was + // fully started and all the asynchronous StartHost magic is finished + // (= scene loading), or immediately if there was no asynchronous magic. + // + // note: we don't really need FinishStartClient/FinishStartServer. the + // host version is enough. + void FinishStartHost() + { + // ConnectHost needs to be called BEFORE SpawnObjects: + // https://github.com/vis2k/Mirror/pull/1249/ + // -> this sets NetworkServer.localConnection. + // -> localConnection needs to be set before SpawnObjects because: + // -> SpawnObjects calls OnStartServer in all NetworkBehaviours + // -> OnStartServer might spawn an object and set [SyncVar(hook="OnColorChanged")] object.color = green; + // -> this calls SyncVar.set (generated by Weaver), which has + // a custom case for host mode (because host mode doesn't + // get OnDeserialize calls, where SyncVar hooks are usually + // called): + // + // if (!SyncVarEqual(value, ref color)) + // { + // if (NetworkServer.localClientActive && !getSyncVarHookGuard(1uL)) + // { + // setSyncVarHookGuard(1uL, value: true); + // OnColorChangedHook(value); + // setSyncVarHookGuard(1uL, value: false); + // } + // SetSyncVar(value, ref color, 1uL); + // } + // + // -> localClientActive needs to be true, otherwise the hook + // isn't called in host mode! + // + // TODO call this after spawnobjects and worry about the syncvar hook fix later? + NetworkClient.ConnectHost(); + + // invoke user callbacks AFTER ConnectHost has set .activeHost. + // this way initialization can properly handle host mode. + // + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3302 + // where [SyncVar] hooks wouldn't be called for objects spawned in + // NetworkManager.OnStartServer, because .activeHost was still false. + // + // TODO is there a risk of someone connecting between Listen() and FinishStartHost()? + OnStartServer(); + + // call OnStartHost AFTER SetupServer. this way we can use + // NetworkServer.Spawn etc. in there too. just like OnStartServer + // is called after the server is actually properly started. + OnStartHost(); + + // server scene was loaded. now spawn all the objects + NetworkServer.SpawnObjects(); + + // connect client and call OnStartClient AFTER server scene was + // loaded and all objects were spawned. + // DO NOT do this earlier. it would cause race conditions where a + // client will do things before the server is even fully started. + //Debug.Log("StartHostClient called"); + SetupClient(); + RegisterClientMessages(); + + // InvokeOnConnected needs to be called AFTER RegisterClientMessages + // (https://github.com/vis2k/Mirror/pull/1249/) + HostMode.InvokeOnConnected(); + + OnStartClient(); + } + + /// This stops both the client and the server that the manager is using. + public void StopHost() + { + OnStopHost(); + StopClient(); + StopServer(); + } + + /// Stops the server from listening and simulating the game. + public void StopServer() + { + // return if already stopped to avoid recursion deadlock + if (!NetworkServer.active) + return; + + if (authenticator != null) + { + authenticator.OnServerAuthenticated.RemoveListener(OnServerAuthenticated); + authenticator.OnStopServer(); + } + + // Get Network Manager out of DDOL before going to offline scene + // to avoid collision and let a fresh Network Manager be created. + // IMPORTANT: .gameObject can be null if StopClient is called from + // OnApplicationQuit or from tests! + if (gameObject != null + && gameObject.scene.name == "DontDestroyOnLoad" + && !string.IsNullOrWhiteSpace(offlineScene) + && SceneManager.GetActiveScene().path != offlineScene) + SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene()); + + OnStopServer(); + + //Debug.Log("NetworkManager StopServer"); + NetworkServer.Shutdown(); + + // set offline mode BEFORE changing scene so that FinishStartScene + // doesn't think we need initialize anything. + mode = NetworkManagerMode.Offline; + + if (!string.IsNullOrWhiteSpace(offlineScene)) + { + ServerChangeScene(offlineScene); + } + + startPositionIndex = 0; + + networkSceneName = ""; + } + + /// Stops and disconnects the client. + public void StopClient() + { + if (mode == NetworkManagerMode.Offline) + return; + + // For Host client, call OnServerDisconnect before NetworkClient.Disconnect + // because we need NetworkServer.localConnection to not be null + // NetworkClient.Disconnect will set it null. + if (mode == NetworkManagerMode.Host) + OnServerDisconnect(NetworkServer.localConnection); + + // ask client -> transport to disconnect. + // handle voluntary and involuntary disconnects in OnClientDisconnect. + // + // StopClient + // NetworkClient.Disconnect + // Transport.Disconnect + // ... + // Transport.OnClientDisconnect + // NetworkClient.OnTransportDisconnect + // NetworkManager.OnClientDisconnect + NetworkClient.Disconnect(); + +#pragma warning disable 618 + // Remove when OnConnectionQualityChanged is removed. + NetworkClient.onConnectionQualityChanged -= OnConnectionQualityChanged; +#pragma warning restore 618 + + // UNET invoked OnDisconnected cleanup immediately. + // let's keep it for now, in case any projects depend on it. + // TODO simply remove this in the future. + OnClientDisconnectInternal(); + } + + // called when quitting the application by closing the window / pressing + // stop in the editor. virtual so that inheriting classes' + // OnApplicationQuit() can call base.OnApplicationQuit() too + public virtual void OnApplicationQuit() + { + // stop client first + // (we want to send the quit packet to the server instead of waiting + // for a timeout) + if (NetworkClient.isConnected) + { + StopClient(); + //Debug.Log("OnApplicationQuit: stopped client"); + } + + // stop server after stopping client (for proper host mode stopping) + if (NetworkServer.active) + { + StopServer(); + //Debug.Log("OnApplicationQuit: stopped server"); + } + + // Call ResetStatics to reset statics and singleton + ResetStatics(); + } + + /// Set the frame rate for a headless builds. Override to disable or modify. + // useful for dedicated servers. + // useful for headless benchmark clients. + public virtual void ConfigureHeadlessFrameRate() + { + if (Utils.IsHeadless()) + { + Application.targetFrameRate = sendRate; + // Debug.Log($"Server Tick Rate set to {Application.targetFrameRate} Hz."); + } + } + + bool InitializeSingleton() + { + if (singleton != null && singleton == this) + return true; + + if (dontDestroyOnLoad) + { + if (singleton != null) + { + Debug.LogWarning("Multiple NetworkManagers detected in the scene. Only one NetworkManager can exist at a time. The duplicate NetworkManager will be destroyed."); + Destroy(gameObject); + + // Return false to not allow collision-destroyed second instance to continue. + return false; + } + //Debug.Log("NetworkManager created singleton (DontDestroyOnLoad)"); + singleton = this; + if (Application.isPlaying) + { + // Force the object to scene root, in case user made it a child of something + // in the scene since DDOL is only allowed for scene root objects + transform.SetParent(null); + DontDestroyOnLoad(gameObject); + } + } + else + { + //Debug.Log("NetworkManager created singleton (ForScene)"); + singleton = this; + } + + // set active transport AFTER setting singleton. + // so only if we didn't destroy ourselves. + + // This tries to avoid missing transport errors and more clearly tells user what to fix. + if (transport == null) + if (TryGetComponent(out Transport newTransport)) + { + Debug.LogWarning($"No Transport assigned to Network Manager - Using {newTransport} found on same object."); + transport = newTransport; + } + else + { + Debug.LogError("No Transport on Network Manager...add a transport and assign it."); + return false; + } + + Transport.active = transport; + return true; + } + + void RegisterServerMessages() + { + NetworkServer.OnConnectedEvent = OnServerConnectInternal; + NetworkServer.OnDisconnectedEvent = OnServerDisconnect; + NetworkServer.OnErrorEvent = OnServerError; + NetworkServer.OnTransportExceptionEvent = OnServerTransportException; + NetworkServer.RegisterHandler(OnServerAddPlayerInternal); + + // Network Server initially registers its own handler for this, so we replace it here. + NetworkServer.ReplaceHandler(OnServerReadyMessageInternal); + } + + void RegisterClientMessages() + { + NetworkClient.OnConnectedEvent = OnClientConnectInternal; + NetworkClient.OnDisconnectedEvent = OnClientDisconnectInternal; + NetworkClient.OnErrorEvent = OnClientError; + NetworkClient.OnTransportExceptionEvent = OnClientTransportException; + + // Don't require authentication because server may send NotReadyMessage from ServerChangeScene + NetworkClient.RegisterHandler(OnClientNotReadyMessageInternal, false); + NetworkClient.RegisterHandler(OnClientSceneInternal, false); + + if (playerPrefab != null) + NetworkClient.RegisterPrefab(playerPrefab); + + foreach (GameObject prefab in spawnPrefabs.Where(t => t != null)) + NetworkClient.RegisterPrefab(prefab); + } + + // This is the only way to clear the singleton, so another instance can be created. + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + public static void ResetStatics() + { + // call StopHost if we have a singleton + if (singleton) + singleton.StopHost(); + + // reset all statics + startPositions.Clear(); + startPositionIndex = 0; + clientReadyConnection = null; + loadingSceneAsync = null; + networkSceneName = string.Empty; + + // and finally (in case it isn't null already)... + singleton = null; + } + + // virtual so that inheriting classes' OnDestroy() can call base.OnDestroy() too + public virtual void OnDestroy() + { + //Debug.Log("NetworkManager destroyed"); + } + + /// The name of the current network scene. + // set by NetworkManager when changing the scene. + // new clients will automatically load this scene. + // Loading a scene manually won't set it. + public static string networkSceneName { get; protected set; } = ""; + + public static AsyncOperation loadingSceneAsync; + + /// Change the server scene and all client's scenes across the network. + // Called automatically if onlineScene or offlineScene are set, but it + // can be called from user code to switch scenes again while the game is + // in progress. This automatically sets clients to be not-ready during + // the change and ready again to participate in the new scene. + public virtual void ServerChangeScene(string newSceneName) + { + if (string.IsNullOrWhiteSpace(newSceneName)) + { + Debug.LogError("ServerChangeScene empty scene name"); + return; + } + + if (NetworkServer.isLoadingScene && newSceneName == networkSceneName) + { + Debug.LogError($"Scene change is already in progress for {newSceneName}"); + return; + } + + // Throw error if called from client + // Allow changing scene while stopping the server + if (!NetworkServer.active && newSceneName != offlineScene) + { + Debug.LogError("ServerChangeScene can only be called on an active server."); + return; + } + + // Debug.Log($"ServerChangeScene {newSceneName}"); + NetworkServer.SetAllClientsNotReady(); + networkSceneName = newSceneName; + + // Let server prepare for scene change + OnServerChangeScene(newSceneName); + + // set server flag to stop processing messages while changing scenes + // it will be re-enabled in FinishLoadScene. + NetworkServer.isLoadingScene = true; + + loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); + + // ServerChangeScene can be called when stopping the server + // when this happens the server is not active so does not need to tell clients about the change + if (NetworkServer.active) + { + // notify all clients about the new scene + NetworkServer.SendToAll(new SceneMessage + { + sceneName = newSceneName + }); + } + + startPositionIndex = 0; + startPositions.Clear(); + } + + // This is only set in ClientChangeScene below...never on server. + // We need to check this in OnClientSceneChanged called from FinishLoadSceneClientOnly + // to prevent AddPlayer message after loading/unloading additive scenes + SceneOperation clientSceneOperation = SceneOperation.Normal; + + internal void ClientChangeScene(string newSceneName, SceneOperation sceneOperation = SceneOperation.Normal, bool customHandling = false) + { + if (string.IsNullOrWhiteSpace(newSceneName)) + { + Debug.LogError("ClientChangeScene empty scene name"); + return; + } + + //Debug.Log($"ClientChangeScene newSceneName: {newSceneName} networkSceneName{networkSceneName}"); + + // Let client prepare for scene change + OnClientChangeScene(newSceneName, sceneOperation, customHandling); + + // After calling OnClientChangeScene, exit if server since server is already doing + // the actual scene change, and we don't need to do it for the host client + if (NetworkServer.active) + return; + + // set client flag to stop processing messages while loading scenes. + // otherwise we would process messages and then lose all the state + // as soon as the load is finishing, causing all kinds of bugs + // because of missing state. + // (client may be null after StopClient etc.) + // Debug.Log("ClientChangeScene: pausing handlers while scene is loading to avoid data loss after scene was loaded."); + NetworkClient.isLoadingScene = true; + + // Cache sceneOperation so we know what was requested by the + // Scene message in OnClientChangeScene and OnClientSceneChanged + clientSceneOperation = sceneOperation; + + // scene handling will happen in overrides of OnClientChangeScene and/or OnClientSceneChanged + // Do not call FinishLoadScene here. Custom handler will assign loadingSceneAsync and we need + // to wait for that to finish. UpdateScene already checks for that to be not null and isDone. + if (customHandling) + return; + + switch (sceneOperation) + { + case SceneOperation.Normal: + loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); + break; + case SceneOperation.LoadAdditive: + // Ensure additive scene is not already loaded on client by name or path + // since we don't know which was passed in the Scene message + if (!SceneManager.GetSceneByName(newSceneName).IsValid() && !SceneManager.GetSceneByPath(newSceneName).IsValid()) + loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName, LoadSceneMode.Additive); + else + { + Debug.LogWarning($"Scene {newSceneName} is already loaded"); + + // Reset the flag that we disabled before entering this switch + NetworkClient.isLoadingScene = false; + } + break; + case SceneOperation.UnloadAdditive: + // Ensure additive scene is actually loaded on client by name or path + // since we don't know which was passed in the Scene message + if (SceneManager.GetSceneByName(newSceneName).IsValid() || SceneManager.GetSceneByPath(newSceneName).IsValid()) + loadingSceneAsync = SceneManager.UnloadSceneAsync(newSceneName, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects); + else + { + Debug.LogWarning($"Cannot unload {newSceneName} with UnloadAdditive operation"); + + // Reset the flag that we disabled before entering this switch + NetworkClient.isLoadingScene = false; + } + break; + } + + // don't change the client's current networkSceneName when loading additive scene content + if (sceneOperation == SceneOperation.Normal) + networkSceneName = newSceneName; + } + + // support additive scene loads: + // NetworkScenePostProcess disables all scene objects on load, and + // * NetworkServer.SpawnObjects enables them again on the server when + // calling OnStartServer + // * NetworkClient.PrepareToSpawnSceneObjects enables them again on the + // client after the server sends ObjectSpawnStartedMessage to client + // in SpawnObserversForConnection. this is only called when the + // client joins, so we need to rebuild scene objects manually again + // TODO merge this with FinishLoadScene()? + void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + if (mode == LoadSceneMode.Additive) + { + if (NetworkServer.active) + { + // TODO only respawn the server objects from that scene later! + NetworkServer.SpawnObjects(); + // Debug.Log($"Respawned Server objects after additive scene load: {scene.name}"); + } + if (NetworkClient.active) + { + NetworkClient.PrepareToSpawnSceneObjects(); + // Debug.Log($"Rebuild Client spawnableObjects after additive scene load: {scene.name}"); + } + } + } + + void UpdateScene() + { + if (loadingSceneAsync != null && loadingSceneAsync.isDone) + { + //Debug.Log($"ClientChangeScene done readyConn {clientReadyConnection}"); + + // try-finally to guarantee loadingSceneAsync being cleared. + // fixes https://github.com/vis2k/Mirror/issues/2517 where if + // FinishLoadScene throws an exception, loadingSceneAsync would + // never be cleared and this code would run every Update. + try + { + FinishLoadScene(); + } + finally + { + loadingSceneAsync.allowSceneActivation = true; + loadingSceneAsync = null; + } + } + } + + protected void FinishLoadScene() + { + // NOTE: this cannot use NetworkClient.allClients[0] - that client may be for a completely different purpose. + + // process queued messages that we received while loading the scene + //Debug.Log("FinishLoadScene: resuming handlers after scene was loading."); + NetworkServer.isLoadingScene = false; + NetworkClient.isLoadingScene = false; + + // host mode? + if (mode == NetworkManagerMode.Host) + { + FinishLoadSceneHost(); + } + // server-only mode? + else if (mode == NetworkManagerMode.ServerOnly) + { + FinishLoadSceneServerOnly(); + } + // client-only mode? + else if (mode == NetworkManagerMode.ClientOnly) + { + FinishLoadSceneClientOnly(); + } + // otherwise we called it after stopping when loading offline scene. + // do nothing then. + } + + // finish load scene part for host mode. makes code easier and is + // necessary for FinishStartHost later. + // (the 3 things have to happen in that exact order) + void FinishLoadSceneHost() + { + // debug message is very important. if we ever break anything then + // it's very obvious to notice. + //Debug.Log("Finished loading scene in host mode."); + + if (clientReadyConnection != null) + { + clientLoadedScene = true; + clientReadyConnection = null; + } + + // do we need to finish a StartHost() call? + // then call FinishStartHost and let it take care of spawning etc. + if (finishStartHostPending) + { + finishStartHostPending = false; + FinishStartHost(); + + // call OnServerSceneChanged + OnServerSceneChanged(networkSceneName); + + // DO NOT call OnClientSceneChanged here. + // the scene change happened because StartHost loaded the + // server's online scene. it has nothing to do with the client. + // this was not meant as a client scene load, so don't call it. + // + // otherwise AddPlayer would be called twice: + // -> once for client OnConnected + // -> once in OnClientSceneChanged + } + // otherwise we just changed a scene in host mode + else + { + // spawn server objects + NetworkServer.SpawnObjects(); + + // call OnServerSceneChanged + OnServerSceneChanged(networkSceneName); + + if (NetworkClient.isConnected) + OnClientSceneChanged(); + } + } + + // finish load scene part for server-only. . makes code easier and is + // necessary for FinishStartServer later. + void FinishLoadSceneServerOnly() + { + // debug message is very important. if we ever break anything then + // it's very obvious to notice. + //Debug.Log("Finished loading scene in server-only mode."); + + NetworkServer.SpawnObjects(); + OnServerSceneChanged(networkSceneName); + } + + // finish load scene part for client-only. makes code easier and is + // necessary for FinishStartClient later. + void FinishLoadSceneClientOnly() + { + // debug message is very important. if we ever break anything then + // it's very obvious to notice. + //Debug.Log("Finished loading scene in client-only mode."); + + if (clientReadyConnection != null) + { + clientLoadedScene = true; + clientReadyConnection = null; + } + + if (NetworkClient.isConnected) + OnClientSceneChanged(); + } + + /// + /// Registers the transform of a game object as a player spawn location. + /// This is done automatically by NetworkStartPosition components, but can be done manually from user script code. + /// + /// Transform to register. + // Static because it's called from NetworkStartPosition::Awake + // and singleton may not exist yet + public static void RegisterStartPosition(Transform start) + { + // Debug.Log($"RegisterStartPosition: {start.gameObject.name} {start.position}"); + startPositions.Add(start); + + // reorder the list so that round-robin spawning uses the start positions + // in hierarchy order. This assumes all objects with NetworkStartPosition + // component are siblings, either in the scene root or together as children + // under a single parent in the scene. + startPositions = startPositions.OrderBy(transform => transform.GetSiblingIndex()).ToList(); + } + + /// Unregister a Transform from start positions. + // Static because it's called from NetworkStartPosition::OnDestroy + // and singleton may not exist yet + public static void UnRegisterStartPosition(Transform start) + { + //Debug.Log($"UnRegisterStartPosition: {start.name} {start.position}"); + startPositions.Remove(start); + } + + /// Get the next NetworkStartPosition based on the selected PlayerSpawnMethod. + public virtual Transform GetStartPosition() + { + // first remove any dead transforms + startPositions.RemoveAll(t => t == null); + + if (startPositions.Count == 0) + return null; + + if (playerSpawnMethod == PlayerSpawnMethod.Random) + { + return startPositions[UnityEngine.Random.Range(0, startPositions.Count)]; + } + else + { + Transform startPosition = startPositions[startPositionIndex]; + startPositionIndex = (startPositionIndex + 1) % startPositions.Count; + return startPosition; + } + } + + void OnServerConnectInternal(NetworkConnectionToClient conn) + { + //Debug.Log("NetworkManager.OnServerConnectInternal"); + + if (authenticator != null) + { + // we have an authenticator - let it handle authentication + authenticator.OnServerAuthenticate(conn); + } + else + { + // authenticate immediately + OnServerAuthenticated(conn); + } + } + + // called after successful authentication + // TODO do the NetworkServer.OnAuthenticated thing from x branch + void OnServerAuthenticated(NetworkConnectionToClient conn) + { + //Debug.Log("NetworkManager.OnServerAuthenticated"); + + // set connection to authenticated + conn.isAuthenticated = true; + + // proceed with the login handshake by calling OnServerConnect + if (networkSceneName != "" && networkSceneName != offlineScene) + { + SceneMessage msg = new SceneMessage() + { + sceneName = networkSceneName + }; + conn.Send(msg); + } + + OnServerConnect(conn); + } + + void OnServerReadyMessageInternal(NetworkConnectionToClient conn, ReadyMessage msg) + { + //Debug.Log("NetworkManager.OnServerReadyMessageInternal"); + OnServerReady(conn); + } + + void OnServerAddPlayerInternal(NetworkConnectionToClient conn, AddPlayerMessage msg) + { + //Debug.Log("NetworkManager.OnServerAddPlayer"); + + if (autoCreatePlayer && playerPrefab == null) + { + Debug.LogError("The PlayerPrefab is empty on the NetworkManager. Please setup a PlayerPrefab object."); + return; + } + + if (autoCreatePlayer && !playerPrefab.TryGetComponent(out NetworkIdentity _)) + { + Debug.LogError("The PlayerPrefab does not have a NetworkIdentity. Please add a NetworkIdentity to the player prefab."); + return; + } + + if (conn.identity != null) + { + Debug.LogError("There is already a player for this connection."); + return; + } + + OnServerAddPlayer(conn); + } + + void OnClientConnectInternal() + { + //Debug.Log("NetworkManager.OnClientConnectInternal"); + + if (authenticator != null) + { + // we have an authenticator - let it handle authentication + authenticator.OnClientAuthenticate(); + } + else + { + // authenticate immediately + OnClientAuthenticated(); + } + } + + // called after successful authentication + void OnClientAuthenticated() + { + //Debug.Log("NetworkManager.OnClientAuthenticated"); + + // set connection to authenticated + NetworkClient.connection.isAuthenticated = true; + + // Set flag to wait for scene change? + if (string.IsNullOrWhiteSpace(onlineScene) || onlineScene == offlineScene || Utils.IsSceneActive(onlineScene)) + { + clientLoadedScene = false; + } + else + { + // Scene message expected from server. + clientLoadedScene = true; + clientReadyConnection = NetworkClient.connection; + } + + // Call virtual method regardless of whether a scene change is expected or not. + OnClientConnect(); + } + + // Transport callback, invoked after client fully disconnected. + // the call order should always be: + // Disconnect() -> ask Transport -> Transport.OnDisconnected -> Cleanup + void OnClientDisconnectInternal() + { + //Debug.Log("NetworkManager.OnClientDisconnectInternal"); + + // Only let this run once. StopClient in Host mode changes to ServerOnly + if (mode == NetworkManagerMode.ServerOnly || mode == NetworkManagerMode.Offline) + return; + + // user callback + OnClientDisconnect(); + + if (authenticator != null) + { + authenticator.OnClientAuthenticated.RemoveListener(OnClientAuthenticated); + authenticator.OnStopClient(); + } + + // set mode BEFORE changing scene so FinishStartScene doesn't re-initialize anything. + // set mode BEFORE NetworkClient.Disconnect so StopClient only runs once. + // set mode BEFORE OnStopClient so StopClient only runs once. + // If we got here from StopClient in Host mode, change to ServerOnly. + // - If StopHost was called, StopServer will put us in Offline mode. + if (mode == NetworkManagerMode.Host) + mode = NetworkManagerMode.ServerOnly; + else + mode = NetworkManagerMode.Offline; + + //Debug.Log("NetworkManager StopClient"); + OnStopClient(); + + // shutdown client + NetworkClient.Shutdown(); + + // Exit here if we're now in ServerOnly mode (StopClient called in Host mode). + if (mode == NetworkManagerMode.ServerOnly) return; + + // Get Network Manager out of DDOL before going to offline scene + // to avoid collision and let a fresh Network Manager be created. + // IMPORTANT: .gameObject can be null if StopClient is called from + // OnApplicationQuit or from tests! + if (gameObject != null + && gameObject.scene.name == "DontDestroyOnLoad" + && !string.IsNullOrWhiteSpace(offlineScene) + && SceneManager.GetActiveScene().path != offlineScene) + SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene()); + + // If StopHost called in Host mode, StopServer will change scenes after this. + // Check loadingSceneAsync to ensure we don't double-invoke the scene change. + // Check if NetworkServer.active because we can get here via Disconnect before server has started to change scenes. + if (!string.IsNullOrWhiteSpace(offlineScene) && !Utils.IsSceneActive(offlineScene) && loadingSceneAsync == null && !NetworkServer.active) + { + ClientChangeScene(offlineScene, SceneOperation.Normal); + } + + networkSceneName = ""; + } + + void OnClientNotReadyMessageInternal(NotReadyMessage msg) + { + //Debug.Log("NetworkManager.OnClientNotReadyMessageInternal"); + NetworkClient.ready = false; + OnClientNotReady(); + + // NOTE: clientReadyConnection is not set here! don't want OnClientConnect to be invoked again after scene changes. + } + + void OnClientSceneInternal(SceneMessage msg) + { + //Debug.Log("NetworkManager.OnClientSceneInternal"); + + // This needs to run for host client too. NetworkServer.active is checked there + if (NetworkClient.isConnected) + { + ClientChangeScene(msg.sceneName, msg.sceneOperation, msg.customHandling); + } + } + + /// Called on the server when a new client connects. + public virtual void OnServerConnect(NetworkConnectionToClient conn) { } + + /// Called on the server when a client disconnects. + // Called by NetworkServer.OnTransportDisconnect! + public virtual void OnServerDisconnect(NetworkConnectionToClient conn) + { + // by default, this function destroys the connection's player. + // can be overwritten for cases like delayed logouts in MMOs to + // avoid players escaping from PvP situations by logging out. + NetworkServer.DestroyPlayerForConnection(conn); + //Debug.Log("OnServerDisconnect: Client disconnected."); + } + + /// Called on the server when a client is ready (= loaded the scene) + public virtual void OnServerReady(NetworkConnectionToClient conn) + { + if (conn.identity == null) + { + // this is now allowed (was not for a while) + //Debug.Log("Ready with no player object"); + } + NetworkServer.SetClientReady(conn); + } + + /// Called on server when a client requests to add the player. Adds playerPrefab by default. Can be overwritten. + // The default implementation for this function creates a new player object from the playerPrefab. + public virtual void OnServerAddPlayer(NetworkConnectionToClient conn) + { + Transform startPos = GetStartPosition(); + GameObject player = startPos != null + ? Instantiate(playerPrefab, startPos.position, startPos.rotation) + : Instantiate(playerPrefab); + + // instantiating a "Player" prefab gives it the name "Player(clone)" + // => appending the connectionId is WAY more useful for debugging! + player.name = $"{playerPrefab.name} [connId={conn.connectionId}]"; + NetworkServer.AddPlayerForConnection(conn, player); + } + + /// Called on server when transport raises an exception. NetworkConnection may be null. + public virtual void OnServerError(NetworkConnectionToClient conn, TransportError error, string reason) { } + + /// Called on server when transport raises an exception. NetworkConnection may be null. + public virtual void OnServerTransportException(NetworkConnectionToClient conn, Exception exception) { } + + /// Called from ServerChangeScene immediately before SceneManager.LoadSceneAsync is executed + public virtual void OnServerChangeScene(string newSceneName) { } + + /// Called on server after a scene load with ServerChangeScene() is completed. + public virtual void OnServerSceneChanged(string sceneName) { } + + /// Called on the client when connected to a server. By default it sets client as ready and adds a player. + public virtual void OnClientConnect() + { + // OnClientConnect by default calls AddPlayer but it should not do + // that when we have online/offline scenes. so we need the + // clientLoadedScene flag to prevent it. + if (!clientLoadedScene) + { + // Ready/AddPlayer is usually triggered by a scene load completing. + // if no scene was loaded, then Ready/AddPlayer it here instead. + if (!NetworkClient.ready) + NetworkClient.Ready(); + + if (autoCreatePlayer) + NetworkClient.AddPlayer(); + } + } + + /// Called on clients when disconnected from a server. + public virtual void OnClientDisconnect() { } + + // Deprecated 2023-12-05 + /// Deprecated: NetworkClient handles this now. + [Obsolete("NetworkClient handles this now.")] + public virtual void CalculateConnectionQuality() + { + // Moved to NetworkClient + } + + // Deprecated 2023-12-05 + /// Deprecated: NetworkClient handles this now. + [Obsolete("This will be removed. Subscribe to NetworkClient.onConnectionQualityChanged in your own code")] + public virtual void OnConnectionQualityChanged(ConnectionQuality previous, ConnectionQuality current) + { + // logging the change is very useful to track down user's lag reports. + // we want to include as much detail as possible for debugging. + //Debug.Log($"[Mirror] Connection Quality changed from {previous} to {current}:\n rtt={(NetworkTime.rtt * 1000):F1}ms\n rttVar={(NetworkTime.rttVariance * 1000):F1}ms\n bufferTime={(NetworkClient.bufferTime * 1000):F1}ms"); + } + + /// Called on client when transport raises an exception. + public virtual void OnClientError(TransportError error, string reason) { } + + /// Called on client when transport raises an exception. + public virtual void OnClientTransportException(Exception exception) { } + + /// Called on clients when a servers tells the client it is no longer ready, e.g. when switching scenes. + public virtual void OnClientNotReady() { } + + /// Called from ClientChangeScene immediately before SceneManager.LoadSceneAsync is executed + // customHandling: indicates if scene loading will be handled through overrides + public virtual void OnClientChangeScene(string newSceneName, SceneOperation sceneOperation, bool customHandling) { } + + /// Called on clients when a scene has completed loaded, when the scene load was initiated by the server. + // Scene changes can cause player objects to be destroyed. The default + // implementation of OnClientSceneChanged in the NetworkManager is to + // add a player object for the connection if no player object exists. + public virtual void OnClientSceneChanged() + { + // always become ready. + if (NetworkClient.connection.isAuthenticated && !NetworkClient.ready) NetworkClient.Ready(); + + // Only call AddPlayer for normal scene changes, not additive load/unload + if (NetworkClient.connection.isAuthenticated && clientSceneOperation == SceneOperation.Normal && autoCreatePlayer && NetworkClient.localPlayer == null) + { + // add player if existing one is null + NetworkClient.AddPlayer(); + } + } + + // Since there are multiple versions of StartServer, StartClient and + // StartHost, to reliably customize their functionality, users would + // need override all the versions. Instead these callbacks are invoked + // from all versions, so users only need to implement this one case. + + /// This is invoked when a host is started. + public virtual void OnStartHost() { } + + /// This is invoked when a server is started - including when a host is started. + public virtual void OnStartServer() { } + + /// This is invoked when the client is started. + public virtual void OnStartClient() { } + + /// This is called when a server is stopped - including when a host is stopped. + public virtual void OnStopServer() { } + + /// This is called when a client is stopped. + public virtual void OnStopClient() { } + + /// This is called when a host is stopped. + public virtual void OnStopHost() { } + +#if DEBUG + // keep OnGUI even in builds. useful to debug snap interp. + void OnGUI() + { + if (!timeInterpolationGui) return; + NetworkClient.OnGUI(); + } +#endif + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkManager.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkManager.cs.meta new file mode 100644 index 0000000000..c331e97767 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkManager.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8aab4c8111b7c411b9b92cf3dbc5bd4e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkManager.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkManagerHUD.cs b/Assets/ImportedAssets/Mirror/Core/NetworkManagerHUD.cs new file mode 100644 index 0000000000..62a126bc47 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkManagerHUD.cs @@ -0,0 +1,162 @@ +using UnityEngine; + +namespace Mirror +{ + /// Shows NetworkManager controls in a GUI at runtime. + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Manager HUD")] + [RequireComponent(typeof(NetworkManager))] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-manager-hud")] + public class NetworkManagerHUD : MonoBehaviour + { + NetworkManager manager; + + public int offsetX; + public int offsetY; + + void Awake() + { + manager = GetComponent(); + } + + void OnGUI() + { + // If this width is changed, also change offsetX in GUIConsole::OnGUI + int width = 300; + + GUILayout.BeginArea(new Rect(10 + offsetX, 40 + offsetY, width, 9999)); + + if (!NetworkClient.isConnected && !NetworkServer.active) + StartButtons(); + else + StatusLabels(); + + if (NetworkClient.isConnected && !NetworkClient.ready) + { + if (GUILayout.Button("Client Ready")) + { + // client ready + NetworkClient.Ready(); + if (NetworkClient.localPlayer == null) + NetworkClient.AddPlayer(); + } + } + + StopButtons(); + + GUILayout.EndArea(); + } + + void StartButtons() + { + if (!NetworkClient.active) + { +#if UNITY_WEBGL + // cant be a server in webgl build + if (GUILayout.Button("Single Player")) + { + NetworkServer.dontListen = true; + manager.StartHost(); + } +#else + // Server + Client + if (GUILayout.Button("Host (Server + Client)")) + manager.StartHost(); +#endif + + // Client + IP (+ PORT) + GUILayout.BeginHorizontal(); + + if (GUILayout.Button("Client")) + manager.StartClient(); + + manager.networkAddress = GUILayout.TextField(manager.networkAddress); + // only show a port field if we have a port transport + // we can't have "IP:PORT" in the address field since this only + // works for IPV4:PORT. + // for IPV6:PORT it would be misleading since IPV6 contains ":": + // 2001:0db8:0000:0000:0000:ff00:0042:8329 + if (Transport.active is PortTransport portTransport) + { + // use TryParse in case someone tries to enter non-numeric characters + if (ushort.TryParse(GUILayout.TextField(portTransport.Port.ToString()), out ushort port)) + portTransport.Port = port; + } + + GUILayout.EndHorizontal(); + + // Server Only +#if UNITY_WEBGL + // cant be a server in webgl build + GUILayout.Box("( WebGL cannot be server )"); +#else + if (GUILayout.Button("Server Only")) + manager.StartServer(); +#endif + } + else + { + // Connecting + GUILayout.Label($"Connecting to {manager.networkAddress}.."); + if (GUILayout.Button("Cancel Connection Attempt")) + manager.StopClient(); + } + } + + void StatusLabels() + { + // host mode + // display separately because this always confused people: + // Server: ... + // Client: ... + if (NetworkServer.active && NetworkClient.active) + { + // host mode + GUILayout.Label($"Host: running via {Transport.active}"); + } + else if (NetworkServer.active) + { + // server only + GUILayout.Label($"Server: running via {Transport.active}"); + } + else if (NetworkClient.isConnected) + { + // client only + GUILayout.Label($"Client: connected to {manager.networkAddress} via {Transport.active}"); + } + } + + void StopButtons() + { + if (NetworkServer.active && NetworkClient.isConnected) + { + GUILayout.BeginHorizontal(); +#if UNITY_WEBGL + if (GUILayout.Button("Stop Single Player")) + manager.StopHost(); +#else + // stop host if host mode + if (GUILayout.Button("Stop Host")) + manager.StopHost(); + + // stop client if host mode, leaving server up + if (GUILayout.Button("Stop Client")) + manager.StopClient(); +#endif + GUILayout.EndHorizontal(); + } + else if (NetworkClient.isConnected) + { + // stop client if client-only + if (GUILayout.Button("Stop Client")) + manager.StopClient(); + } + else if (NetworkServer.active) + { + // stop server if server-only + if (GUILayout.Button("Stop Server")) + manager.StopServer(); + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkManagerHUD.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkManagerHUD.cs.meta new file mode 100644 index 0000000000..dbdde6b04b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkManagerHUD.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 6442dc8070ceb41f094e44de0bf87274 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkManagerHUD.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkMessage.cs b/Assets/ImportedAssets/Mirror/Core/NetworkMessage.cs new file mode 100644 index 0000000000..7fc387ad45 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkMessage.cs @@ -0,0 +1,4 @@ +namespace Mirror +{ + public interface NetworkMessage {} +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkMessage.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkMessage.cs.meta new file mode 100644 index 0000000000..3d2c1b4f26 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkMessage.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: eb04e4848a2e4452aa2dbd7adb801c51 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkMessage.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkMessages.cs b/Assets/ImportedAssets/Mirror/Core/NetworkMessages.cs new file mode 100644 index 0000000000..7a70d94adb --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkMessages.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Text; +using UnityEngine; + +namespace Mirror +{ + // for performance, we (ab)use c# generics to cache the message id in a static field + // this is significantly faster than doing the computation at runtime or looking up cached results via Dictionary + // generic classes have separate static fields per type specification + public static class NetworkMessageId where T : struct, NetworkMessage + { + // automated message id from type hash. + // platform independent via stable hashcode. + // => convenient so we don't need to track messageIds across projects + // => addons can work with each other without knowing their ids before + // => 2 bytes is enough to avoid collisions. + // registering a messageId twice will log a warning anyway. + public static readonly ushort Id = CalculateId(); + + // Gets the 32bit fnv1a hash + // To get it down to 16bit but still reduce hash collisions we cant just cast it to ushort + // Instead we take the highest 16bits of the 32bit hash and fold them with xor into the lower 16bits + // This will create a more uniform 16bit hash, the method is described in: + // http://www.isthe.com/chongo/tech/comp/fnv/ in section "Changing the FNV hash size - xor-folding" + static ushort CalculateId() => typeof(T).FullName.GetStableHashCode16(); + } + + // message packing all in one place, instead of constructing headers in all + // kinds of different places + // + // MsgType (2 bytes) + // Content (ContentSize bytes) + public static class NetworkMessages + { + // size of message id header in bytes + public const int IdSize = sizeof(ushort); + + // Id <> Type lookup for debugging, profiler, etc. + // important when debugging messageId errors! + public static readonly Dictionary Lookup = + new Dictionary(); + + // dump all types for debugging + public static void LogTypes() + { + StringBuilder builder = new StringBuilder(); + builder.AppendLine("NetworkMessageIds:"); + foreach (KeyValuePair kvp in Lookup) + { + builder.AppendLine($" Id={kvp.Key} = {kvp.Value}"); + } + Debug.Log(builder.ToString()); + } + + // max message content size (without header) calculation for convenience + // -> Transport.GetMaxPacketSize is the raw maximum + // -> Every message gets serialized into <> + // -> Every serialized message get put into a batch with one timestamp per batch + // -> Every message in a batch has a varuint size header. + // use the worst case VarUInt size for the largest possible + // message size = int.max. + public static int MaxContentSize(int channelId) + { + // calculate the max possible size that can fit in a batch + int transportMax = Transport.active.GetMaxPacketSize(channelId); + return transportMax - IdSize - Batcher.MaxMessageOverhead(transportMax); + } + + // max message size which includes header + content. + public static int MaxMessageSize(int channelId) => + MaxContentSize(channelId) + IdSize; + + // automated message id from type hash. + // platform independent via stable hashcode. + // => convenient so we don't need to track messageIds across projects + // => addons can work with each other without knowing their ids before + // => 2 bytes is enough to avoid collisions. + // registering a messageId twice will log a warning anyway. + // keep this for convenience. easier to use than NetworkMessageId.Id. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort GetId() where T : struct, NetworkMessage => + NetworkMessageId.Id; + + // pack message before sending + // -> NetworkWriter passed as arg so that we can use .ToArraySegment + // and do an allocation free send before recycling it. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Pack(T message, NetworkWriter writer) + where T : struct, NetworkMessage + { + writer.WriteUShort(NetworkMessageId.Id); + writer.Write(message); + } + + // read only the message id. + // common function in case we ever change the header size. + public static bool UnpackId(NetworkReader reader, out ushort messageId) + { + // read message type + try + { + messageId = reader.ReadUShort(); + return true; + } + catch (System.IO.EndOfStreamException) + { + messageId = 0; + return false; + } + } + + // version for handlers with channelId + // inline! only exists for 20-30 messages and they call it all the time. + internal static NetworkMessageDelegate WrapHandler(Action handler, bool requireAuthentication, bool exceptionsDisconnect) + where T : struct, NetworkMessage + where C : NetworkConnection + => (conn, reader, channelId) => + { + // protect against DOS attacks if attackers try to send invalid + // data packets to crash the server/client. there are a thousand + // ways to cause an exception in data handling: + // - invalid headers + // - invalid message ids + // - invalid data causing exceptions + // - negative ReadBytesAndSize prefixes + // - invalid utf8 strings + // - etc. + // + // let's catch them all and then disconnect that connection to avoid + // further attacks. + T message = default; + // record start position for NetworkDiagnostics because reader might contain multiple messages if using batching + int startPos = reader.Position; + try + { + if (requireAuthentication && !conn.isAuthenticated) + { + // message requires authentication, but the connection was not authenticated + Debug.LogWarning($"Disconnecting connection: {conn}. Received message {typeof(T)} that required authentication, but the user has not authenticated yet"); + conn.Disconnect(); + return; + } + + //Debug.Log($"ConnectionRecv {conn} msgType:{typeof(T)} content:{BitConverter.ToString(reader.buffer.Array, reader.buffer.Offset, reader.buffer.Count)}"); + + // if it is a value type, just use default(T) + // otherwise allocate a new instance + message = reader.Read(); + } + catch (Exception exception) + { + // should we disconnect on exceptions? + if (exceptionsDisconnect) + { + Debug.LogError($"Disconnecting connection: {conn} because reading a message of type {typeof(T)} caused an Exception. This can happen if the other side accidentally (or an attacker intentionally) sent invalid data. Reason: {exception}"); + conn.Disconnect(); + return; + } + // otherwise log it but allow the connection to keep playing + else + { + Debug.LogError($"Caught an Exception when reading a message from: {conn} of type {typeof(T)}. Reason: {exception}"); + return; + } + } + finally + { + int endPos = reader.Position; + // TODO: Figure out the correct channel + NetworkDiagnostics.OnReceive(message, channelId, endPos - startPos); + } + + // user handler exception should not stop the whole server + try + { + // user implemented handler + handler((C)conn, message, channelId); + } + catch (Exception exception) + { + // should we disconnect on exceptions? + if (exceptionsDisconnect) + { + Debug.LogError($"Disconnecting connection: {conn} because handling a message of type {typeof(T)} caused an Exception. This can happen if the other side accidentally (or an attacker intentionally) sent invalid data. Reason: {exception}"); + conn.Disconnect(); + } + // otherwise log it but allow the connection to keep playing + else + { + Debug.LogError($"Caught an Exception when handling a message from: {conn} of type {typeof(T)}. Reason: {exception}"); + } + } + }; + + // version for handlers without channelId + // TODO obsolete this some day to always use the channelId version. + // all handlers in this version are wrapped with 1 extra action. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static NetworkMessageDelegate WrapHandler(Action handler, bool requireAuthentication, bool exceptionsDisconnect) + where T : struct, NetworkMessage + where C : NetworkConnection + { + // wrap action as channelId version, call original + void Wrapped(C conn, T msg, int _) => handler(conn, msg); + return WrapHandler((Action)Wrapped, requireAuthentication, exceptionsDisconnect); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkMessages.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkMessages.cs.meta new file mode 100644 index 0000000000..52dcb723c2 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkMessages.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 2db134099f0df4d96a84ae7a0cd9b4bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkMessages.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkReader.cs b/Assets/ImportedAssets/Mirror/Core/NetworkReader.cs new file mode 100644 index 0000000000..82fb7cd4a8 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkReader.cs @@ -0,0 +1,249 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text; +using Unity.Collections.LowLevel.Unsafe; +using UnityEngine; + +namespace Mirror +{ + /// Network Reader for most simple types like floats, ints, buffers, structs, etc. Use NetworkReaderPool.GetReader() to avoid allocations. + // Note: This class is intended to be extremely pedantic, + // and throw exceptions whenever stuff is going slightly wrong. + // The exceptions will be handled in NetworkServer/NetworkClient. + // + // Note that NetworkWriter can be passed in constructor thanks to implicit + // ArraySegment conversion: + // NetworkReader reader = new NetworkReader(writer); + public class NetworkReader + { + // internal buffer + // byte[] pointer would work, but we use ArraySegment to also support + // the ArraySegment constructor + internal ArraySegment buffer; + + /// Next position to read from the buffer + // 'int' is the best type for .Position. 'short' is too small if we send >32kb which would result in negative .Position + // -> converting long to int is fine until 2GB of data (MAX_INT), so we don't have to worry about overflows here + public int Position; + + /// Remaining bytes that can be read, for convenience. + public int Remaining => buffer.Count - Position; + + /// Total buffer capacity, independent of reader position. + public int Capacity => buffer.Count; + + // cache encoding for ReadString instead of creating it with each time + // 1000 readers before: 1MB GC, 30ms + // 1000 readers after: 0.8MB GC, 18ms + // member(!) to avoid static state. + // + // throwOnInvalidBytes is true. + // if false, it would silently ignore the invalid bytes but continue + // with the valid ones, creating strings like "a�������". + // instead, we want to catch it manually and return String.Empty. + // this is safer. see test: ReadString_InvalidUTF8(). + internal readonly UTF8Encoding encoding = new UTF8Encoding(false, true); + + // while allocation free ReadArraySegment is encouraged, + // some functions can allocate a new byte[], List, Texture, etc. + // we should keep a reasonable allocation size limit: + // -> server won't accidentally allocate 2GB on a mobile device + // -> client won't allocate 2GB on server for ClientToServer [SyncVar]s + // -> unlike max string length of 64 KB, we need a larger limit here. + // large enough to not break existing projects, + // small enough to reasonably limit allocation attacks. + // -> we don't know the exact size of ReadList etc. because is + // managed. instead, this is considered a 'collection length' limit. + public const int AllocationLimit = 1024 * 1024 * 16; // 16 MB * sizeof(T) + + public NetworkReader(ArraySegment segment) + { + buffer = segment; + } + +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have the implicit byte[] to segment conversion yet + public NetworkReader(byte[] bytes) + { + buffer = new ArraySegment(bytes, 0, bytes.Length); + } +#endif + + // sometimes it's useful to point a reader on another buffer instead of + // allocating a new reader (e.g. NetworkReaderPool) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetBuffer(ArraySegment segment) + { + buffer = segment; + Position = 0; + } + +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have the implicit byte[] to segment conversion yet + public void SetBuffer(byte[] bytes) + { + buffer = new ArraySegment(bytes, 0, bytes.Length); + Position = 0; + } +#endif + + // ReadBlittable from DOTSNET + // this is extremely fast, but only works for blittable types. + // => private to make sure nobody accidentally uses it for non-blittable + // + // Benchmark: see NetworkWriter.WriteBlittable! + // + // Note: + // ReadBlittable assumes same endianness for server & client. + // All Unity 2018+ platforms are little endian. + // + // This is not safe to expose to random structs. + // * StructLayout.Sequential is the default, which is safe. + // if the struct contains a reference type, it is converted to Auto. + // but since all structs here are unmanaged blittable, it's safe. + // see also: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.layoutkind?view=netframework-4.8#system-runtime-interopservices-layoutkind-sequential + // * StructLayout.Pack depends on CPU word size. + // this may be different 4 or 8 on some ARM systems, etc. + // this is not safe, and would cause bytes/shorts etc. to be padded. + // see also: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.structlayoutattribute.pack?view=net-6.0 + // * If we force pack all to '1', they would have no padding which is + // great for bandwidth. but on some android systems, CPU can't read + // unaligned memory. + // see also: https://github.com/vis2k/Mirror/issues/3044 + // * The only option would be to force explicit layout with multiples + // of word size. but this requires lots of weaver checking and is + // still questionable (IL2CPP etc.). + // + // Note: inlining ReadBlittable is enough. don't inline ReadInt etc. + // we don't want ReadBlittable to be copied in place everywhere. + internal unsafe T ReadBlittable() + where T : unmanaged + { + // check if blittable for safety +#if UNITY_EDITOR + if (!UnsafeUtility.IsBlittable(typeof(T))) + { + throw new ArgumentException($"{typeof(T)} is not blittable!"); + } +#endif + + // calculate size + // sizeof(T) gets the managed size at compile time. + // Marshal.SizeOf gets the unmanaged size at runtime (slow). + // => our 1mio writes benchmark is 6x slower with Marshal.SizeOf + // => for blittable types, sizeof(T) is even recommended: + // https://docs.microsoft.com/en-us/dotnet/standard/native-interop/best-practices + int size = sizeof(T); + + // ensure remaining + if (Remaining < size) + { + throw new EndOfStreamException($"ReadBlittable<{typeof(T)}> not enough data in buffer to read {size} bytes: {ToString()}"); + } + + // read blittable + T value; + fixed (byte* ptr = &buffer.Array[buffer.Offset + Position]) + { +#if UNITY_ANDROID + // on some android systems, reading *(T*)ptr throws a NRE if + // the ptr isn't aligned (i.e. if Position is 1,2,3,5, etc.). + // here we have to use memcpy. + // + // => we can't get a pointer of a struct in C# without + // marshalling allocations + // => instead, we stack allocate an array of type T and use that + // => stackalloc avoids GC and is very fast. it only works for + // value types, but all blittable types are anyway. + // + // this way, we can still support blittable reads on android. + // see also: https://github.com/vis2k/Mirror/issues/3044 + // (solution discovered by AIIO, FakeByte, mischa) + T* valueBuffer = stackalloc T[1]; + UnsafeUtility.MemCpy(valueBuffer, ptr, size); + value = valueBuffer[0]; +#else + // cast buffer to a T* pointer and then read from it. + value = *(T*)ptr; +#endif + } + Position += size; + return value; + } + + // blittable'?' template for code reuse + // note: bool isn't blittable. need to read as byte. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal T? ReadBlittableNullable() + where T : unmanaged => + ReadByte() != 0 ? ReadBlittable() : default(T?); + + public byte ReadByte() => ReadBlittable(); + + /// Read 'count' bytes into the bytes array + // NOTE: returns byte[] because all reader functions return something. + public byte[] ReadBytes(byte[] bytes, int count) + { + // user may call ReadBytes(ReadInt()). ensure positive count. + if (count < 0) throw new ArgumentOutOfRangeException("ReadBytes requires count >= 0"); + + // check if passed byte array is big enough + if (count > bytes.Length) + { + throw new EndOfStreamException($"ReadBytes can't read {count} + bytes because the passed byte[] only has length {bytes.Length}"); + } + // ensure remaining + if (Remaining < count) + { + throw new EndOfStreamException($"ReadBytesSegment can't read {count} bytes because it would read past the end of the stream. {ToString()}"); + } + + Array.Copy(buffer.Array, buffer.Offset + Position, bytes, 0, count); + Position += count; + return bytes; + } + + /// Read 'count' bytes allocation-free as ArraySegment that points to the internal array. + public ArraySegment ReadBytesSegment(int count) + { + // user may call ReadBytes(ReadInt()). ensure positive count. + if (count < 0) throw new ArgumentOutOfRangeException("ReadBytesSegment requires count >= 0"); + + // ensure remaining + if (Remaining < count) + { + throw new EndOfStreamException($"ReadBytesSegment can't read {count} bytes because it would read past the end of the stream. {ToString()}"); + } + + // return the segment + ArraySegment result = new ArraySegment(buffer.Array, buffer.Offset + Position, count); + Position += count; + return result; + } + + /// Reads any data type that mirror supports. Uses weaver populated Reader(T).read + public T Read() + { + Func readerDelegate = Reader.read; + if (readerDelegate == null) + { + Debug.LogError($"No reader found for {typeof(T)}. Use a type supported by Mirror or define a custom reader extension for {typeof(T)}."); + return default; + } + return readerDelegate(this); + } + + // print the full buffer with position / capacity. + public override string ToString() => + $"[{buffer.ToHexString()} @ {Position}/{Capacity}]"; + } + + /// Helper class that weaver populates with all reader types. + // Note that c# creates a different static variable for each type + // -> Weaver.ReaderWriterProcessor.InitializeReaderAndWriters() populates it + public static class Reader + { + public static Func read; + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkReader.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkReader.cs.meta new file mode 100644 index 0000000000..b43ecff22f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkReader.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 1610f05ec5bd14d6882e689f7372596a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkReader.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkReaderExtensions.cs b/Assets/ImportedAssets/Mirror/Core/NetworkReaderExtensions.cs new file mode 100644 index 0000000000..4493be3db9 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkReaderExtensions.cs @@ -0,0 +1,388 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; + +namespace Mirror +{ + // Mirror's Weaver automatically detects all NetworkReader function types, + // but they do all need to be extensions. + public static class NetworkReaderExtensions + { + public static byte ReadByte(this NetworkReader reader) => reader.ReadBlittable(); + public static byte? ReadByteNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static sbyte ReadSByte(this NetworkReader reader) => reader.ReadBlittable(); + public static sbyte? ReadSByteNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + // bool is not blittable. read as ushort. + public static char ReadChar(this NetworkReader reader) => (char)reader.ReadBlittable(); + public static char? ReadCharNullable(this NetworkReader reader) => (char?)reader.ReadBlittableNullable(); + + // bool is not blittable. read as byte. + public static bool ReadBool(this NetworkReader reader) => reader.ReadBlittable() != 0; + public static bool? ReadBoolNullable(this NetworkReader reader) + { + byte? value = reader.ReadBlittableNullable(); + return value.HasValue ? (value.Value != 0) : default(bool?); + } + + public static short ReadShort(this NetworkReader reader) => (short)reader.ReadUShort(); + public static short? ReadShortNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static ushort ReadUShort(this NetworkReader reader) => reader.ReadBlittable(); + public static ushort? ReadUShortNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static int ReadInt(this NetworkReader reader) => reader.ReadBlittable(); + public static int? ReadIntNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static uint ReadUInt(this NetworkReader reader) => reader.ReadBlittable(); + public static uint? ReadUIntNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static long ReadLong(this NetworkReader reader) => reader.ReadBlittable(); + public static long? ReadLongNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static ulong ReadULong(this NetworkReader reader) => reader.ReadBlittable(); + public static ulong? ReadULongNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static float ReadFloat(this NetworkReader reader) => reader.ReadBlittable(); + public static float? ReadFloatNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static double ReadDouble(this NetworkReader reader) => reader.ReadBlittable(); + public static double? ReadDoubleNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static decimal ReadDecimal(this NetworkReader reader) => reader.ReadBlittable(); + public static decimal? ReadDecimalNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + /// if an invalid utf8 string is sent + public static string ReadString(this NetworkReader reader) + { + // read number of bytes + ushort size = reader.ReadUShort(); + + // null support, see NetworkWriter + if (size == 0) + return null; + + ushort realSize = (ushort)(size - 1); + + // make sure it's within limits to avoid allocation attacks etc. + if (realSize > NetworkWriter.MaxStringLength) + throw new EndOfStreamException($"NetworkReader.ReadString - Value too long: {realSize} bytes. Limit is: {NetworkWriter.MaxStringLength} bytes"); + + ArraySegment data = reader.ReadBytesSegment(realSize); + + // convert directly from buffer to string via encoding + // throws in case of invalid utf8. + // see test: ReadString_InvalidUTF8() + return reader.encoding.GetString(data.Array, data.Offset, data.Count); + } + + public static byte[] ReadBytes(this NetworkReader reader, int count) + { + // prevent allocation attacks with a reasonable limit. + // server shouldn't allocate too much on client devices. + // client shouldn't allocate too much on server in ClientToServer [SyncVar]s. + if (count > NetworkReader.AllocationLimit) + { + // throw EndOfStream for consistency with ReadBlittable when out of data + throw new EndOfStreamException($"NetworkReader attempted to allocate {count} bytes, which is larger than the allowed limit of {NetworkReader.AllocationLimit} bytes."); + } + + byte[] bytes = new byte[count]; + reader.ReadBytes(bytes, count); + return bytes; + } + + /// if count is invalid + public static byte[] ReadBytesAndSize(this NetworkReader reader) + { + // count = 0 means the array was null + // otherwise count -1 is the length of the array + uint count = reader.ReadUInt(); + // Use checked() to force it to throw OverflowException if data is invalid + return count == 0 ? null : reader.ReadBytes(checked((int)(count - 1u))); + } + // Reads ArraySegment and size header + /// if count is invalid + public static ArraySegment ReadArraySegmentAndSize(this NetworkReader reader) + { + // count = 0 means the array was null + // otherwise count - 1 is the length of the array + uint count = reader.ReadUInt(); + // Use checked() to force it to throw OverflowException if data is invalid + return count == 0 ? default : reader.ReadBytesSegment(checked((int)(count - 1u))); + } + + public static Vector2 ReadVector2(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector2? ReadVector2Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Vector3 ReadVector3(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector3? ReadVector3Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Vector4 ReadVector4(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector4? ReadVector4Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Vector2Int ReadVector2Int(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector2Int? ReadVector2IntNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Vector3Int ReadVector3Int(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector3Int? ReadVector3IntNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Color ReadColor(this NetworkReader reader) => reader.ReadBlittable(); + public static Color? ReadColorNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Color32 ReadColor32(this NetworkReader reader) => reader.ReadBlittable(); + public static Color32? ReadColor32Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Quaternion ReadQuaternion(this NetworkReader reader) => reader.ReadBlittable(); + public static Quaternion? ReadQuaternionNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + // Rect is a struct with properties instead of fields + public static Rect ReadRect(this NetworkReader reader) => new Rect(reader.ReadVector2(), reader.ReadVector2()); + public static Rect? ReadRectNullable(this NetworkReader reader) => reader.ReadBool() ? ReadRect(reader) : default(Rect?); + + // Plane is a struct with properties instead of fields + public static Plane ReadPlane(this NetworkReader reader) => new Plane(reader.ReadVector3(), reader.ReadFloat()); + public static Plane? ReadPlaneNullable(this NetworkReader reader) => reader.ReadBool() ? ReadPlane(reader) : default(Plane?); + + // Ray is a struct with properties instead of fields + public static Ray ReadRay(this NetworkReader reader) => new Ray(reader.ReadVector3(), reader.ReadVector3()); + public static Ray? ReadRayNullable(this NetworkReader reader) => reader.ReadBool() ? ReadRay(reader) : default(Ray?); + + // LayerMask is a struct with properties instead of fields + public static LayerMask ReadLayerMask(this NetworkReader reader) + { + // LayerMask doesn't have a constructor that takes an initial value. + // 32 layers as a flags enum, max value of 496, we only need a UShort. + LayerMask layerMask = default; + layerMask.value = reader.ReadUShort(); + return layerMask; + } + + public static LayerMask? ReadLayerMaskNullable(this NetworkReader reader) => reader.ReadBool() ? ReadLayerMask(reader) : default(LayerMask?); + + public static Matrix4x4 ReadMatrix4x4(this NetworkReader reader) => reader.ReadBlittable(); + public static Matrix4x4? ReadMatrix4x4Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Guid ReadGuid(this NetworkReader reader) + { +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have Span yet + return new Guid(reader.ReadBytes(16)); +#else + // ReadBlittable(Guid) isn't safe. see ReadBlittable comments. + // Guid is Sequential, but we can't guarantee packing. + if (reader.Remaining >= 16) + { + ReadOnlySpan span = new ReadOnlySpan(reader.buffer.Array, reader.buffer.Offset + reader.Position, 16); + reader.Position += 16; + return new Guid(span); + } + throw new EndOfStreamException($"ReadGuid out of range: {reader}"); +#endif + } + public static Guid? ReadGuidNullable(this NetworkReader reader) => reader.ReadBool() ? ReadGuid(reader) : default(Guid?); + + public static NetworkIdentity ReadNetworkIdentity(this NetworkReader reader) + { + uint netId = reader.ReadUInt(); + if (netId == 0) + return null; + + // NOTE: a netId not being in spawned is common. + // for example, "[SyncVar] NetworkIdentity target" netId would not + // be known on client if the monster walks out of proximity for a + // moment. no need to log any error or warning here. + return Utils.GetSpawnedInServerOrClient(netId); + } + + public static NetworkBehaviour ReadNetworkBehaviour(this NetworkReader reader) + { + // read netId first. + // + // IMPORTANT: if netId != 0, writer always writes componentIndex. + // reusing ReadNetworkIdentity() might return a null NetworkIdentity + // even if netId was != 0 but the identity disappeared on the client, + // resulting in unequal amounts of data being written / read. + // https://github.com/vis2k/Mirror/issues/2972 + uint netId = reader.ReadUInt(); + if (netId == 0) + return null; + + // read component index in any case, BEFORE searching the spawned + // NetworkIdentity by netId. + byte componentIndex = reader.ReadByte(); + + // NOTE: a netId not being in spawned is common. + // for example, "[SyncVar] NetworkIdentity target" netId would not + // be known on client if the monster walks out of proximity for a + // moment. no need to log any error or warning here. + NetworkIdentity identity = Utils.GetSpawnedInServerOrClient(netId); + + return identity != null + ? identity.NetworkBehaviours[componentIndex] + : null; + } + + public static T ReadNetworkBehaviour(this NetworkReader reader) where T : NetworkBehaviour + { + return reader.ReadNetworkBehaviour() as T; + } + + public static NetworkBehaviourSyncVar ReadNetworkBehaviourSyncVar(this NetworkReader reader) + { + uint netId = reader.ReadUInt(); + byte componentIndex = default; + + // if netId is not 0, then index is also sent to read before returning + if (netId != 0) + { + componentIndex = reader.ReadByte(); + } + + return new NetworkBehaviourSyncVar(netId, componentIndex); + } + + public static Transform ReadTransform(this NetworkReader reader) + { + // Don't use null propagation here as it could lead to MissingReferenceException + NetworkIdentity networkIdentity = reader.ReadNetworkIdentity(); + return networkIdentity != null ? networkIdentity.transform : null; + } + + public static GameObject ReadGameObject(this NetworkReader reader) + { + // Don't use null propagation here as it could lead to MissingReferenceException + NetworkIdentity networkIdentity = reader.ReadNetworkIdentity(); + return networkIdentity != null ? networkIdentity.gameObject : null; + } + + // while SyncList is recommended for NetworkBehaviours, + // structs may have .List members which weaver needs to be able to + // fully serialize for NetworkMessages etc. + // note that Weaver/Readers/GenerateReader() handles this manually. + public static List ReadList(this NetworkReader reader) + { + int length = reader.ReadInt(); + + // 'null' is encoded as '-1' + if (length < 0) return null; + + // prevent allocation attacks with a reasonable limit. + // server shouldn't allocate too much on client devices. + // client shouldn't allocate too much on server in ClientToServer [SyncVar]s. + if (length > NetworkReader.AllocationLimit) + { + // throw EndOfStream for consistency with ReadBlittable when out of data + throw new EndOfStreamException($"NetworkReader attempted to allocate a List<{typeof(T)}> {length} elements, which is larger than the allowed limit of {NetworkReader.AllocationLimit}."); + } + + List result = new List(length); + for (int i = 0; i < length; i++) + { + result.Add(reader.Read()); + } + return result; + } + + // while SyncSet is recommended for NetworkBehaviours, + // structs may have .Set members which weaver needs to be able to + // fully serialize for NetworkMessages etc. + // note that Weaver/Readers/GenerateReader() handles this manually. + // TODO writer not found. need to adjust weaver first. see tests. + /* + public static HashSet ReadHashSet(this NetworkReader reader) + { + int length = reader.ReadInt(); + if (length < 0) + return null; + HashSet result = new HashSet(); + for (int i = 0; i < length; i++) + { + result.Add(reader.Read()); + } + return result; + } + */ + + public static T[] ReadArray(this NetworkReader reader) + { + int length = reader.ReadInt(); + + // 'null' is encoded as '-1' + if (length < 0) return null; + + // prevent allocation attacks with a reasonable limit. + // server shouldn't allocate too much on client devices. + // client shouldn't allocate too much on server in ClientToServer [SyncVar]s. + if (length > NetworkReader.AllocationLimit) + { + // throw EndOfStream for consistency with ReadBlittable when out of data + throw new EndOfStreamException($"NetworkReader attempted to allocate an Array<{typeof(T)}> with {length} elements, which is larger than the allowed limit of {NetworkReader.AllocationLimit}."); + } + + // we can't check if reader.Remaining < length, + // because we don't know sizeof(T) since it's a managed type. + // if (length > reader.Remaining) throw new EndOfStreamException($"Received array that is too large: {length}"); + + T[] result = new T[length]; + for (int i = 0; i < length; i++) + { + result[i] = reader.Read(); + } + return result; + } + + public static Uri ReadUri(this NetworkReader reader) + { + string uriString = reader.ReadString(); + return (string.IsNullOrWhiteSpace(uriString) ? null : new Uri(uriString)); + } + + public static Texture2D ReadTexture2D(this NetworkReader reader) + { + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 + short width = reader.ReadShort(); + if (width == -1) return null; + + // read height + short height = reader.ReadShort(); + + // prevent allocation attacks with a reasonable limit. + // server shouldn't allocate too much on client devices. + // client shouldn't allocate too much on server in ClientToServer [SyncVar]s. + // log an error and return default. + // we don't want attackers to be able to trigger exceptions. + int totalSize = width * height; + if (totalSize > NetworkReader.AllocationLimit) + { + Debug.LogWarning($"NetworkReader attempted to allocate a Texture2D with total size (width * height) of {totalSize}, which is larger than the allowed limit of {NetworkReader.AllocationLimit}."); + return null; + } + + Texture2D texture2D = new Texture2D(width, height); + + // read pixel content + Color32[] pixels = reader.ReadArray(); + texture2D.SetPixels32(pixels); + texture2D.Apply(); + return texture2D; + } + + public static Sprite ReadSprite(this NetworkReader reader) + { + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 + Texture2D texture = reader.ReadTexture2D(); + if (texture == null) return null; + + // otherwise create a valid sprite + return Sprite.Create(texture, reader.ReadRect(), reader.ReadVector2()); + } + + public static DateTime ReadDateTime(this NetworkReader reader) => DateTime.FromOADate(reader.ReadDouble()); + public static DateTime? ReadDateTimeNullable(this NetworkReader reader) => reader.ReadBool() ? ReadDateTime(reader) : default(DateTime?); + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkReaderExtensions.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkReaderExtensions.cs.meta new file mode 100644 index 0000000000..3dee678948 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkReaderExtensions.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 364a9f7ccd5541e19aa2ae0b81f0b3cf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkReaderExtensions.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkReaderPool.cs b/Assets/ImportedAssets/Mirror/Core/NetworkReaderPool.cs new file mode 100644 index 0000000000..f44adb8ea4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkReaderPool.cs @@ -0,0 +1,48 @@ +// API consistent with Microsoft's ObjectPool. +using System; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + /// Pool of NetworkReaders to avoid allocations. + public static class NetworkReaderPool + { + // reuse Pool + // we still wrap it in NetworkReaderPool.Get/Recyle so we can reset the + // position and array before reusing. + static readonly Pool Pool = new Pool( + // byte[] will be assigned in GetReader + () => new NetworkReaderPooled(new byte[]{}), + // initial capacity to avoid allocations in the first few frames + 1000 + ); + + // expose count for testing + public static int Count => Pool.Count; + + /// Get the next reader in the pool. If pool is empty, creates a new Reader + public static NetworkReaderPooled Get(byte[] bytes) + { + // grab from pool & set buffer + NetworkReaderPooled reader = Pool.Get(); + reader.SetBuffer(bytes); + return reader; + } + + /// Get the next reader in the pool. If pool is empty, creates a new Reader + public static NetworkReaderPooled Get(ArraySegment segment) + { + // grab from pool & set buffer + NetworkReaderPooled reader = Pool.Get(); + reader.SetBuffer(segment); + return reader; + } + + /// Returns a reader to the pool. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Return(NetworkReaderPooled reader) + { + Pool.Return(reader); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkReaderPool.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkReaderPool.cs.meta new file mode 100644 index 0000000000..3bff4b2c52 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkReaderPool.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 2bacff63613ad634a98f9e4d15d29dbf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkReaderPool.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkReaderPooled.cs b/Assets/ImportedAssets/Mirror/Core/NetworkReaderPooled.cs new file mode 100644 index 0000000000..53489045aa --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkReaderPooled.cs @@ -0,0 +1,15 @@ +// "NetworkReaderPooled" instead of "PooledNetworkReader" to group files, for +// easier IDE workflow and more elegant code. +using System; + +namespace Mirror +{ + /// Pooled NetworkReader, automatically returned to pool when using 'using' + // TODO make sealed again after removing obsolete NetworkReaderPooled! + public class NetworkReaderPooled : NetworkReader, IDisposable + { + internal NetworkReaderPooled(byte[] bytes) : base(bytes) {} + internal NetworkReaderPooled(ArraySegment segment) : base(segment) {} + public void Dispose() => NetworkReaderPool.Return(this); + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkReaderPooled.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkReaderPooled.cs.meta new file mode 100644 index 0000000000..031fc30183 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkReaderPooled.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: faafa97c32e44adf8e8888de817a370a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkReaderPooled.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkServer.cs b/Assets/ImportedAssets/Mirror/Core/NetworkServer.cs new file mode 100644 index 0000000000..51cc4caeca --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkServer.cs @@ -0,0 +1,2030 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Mirror.RemoteCalls; +using UnityEngine; + +namespace Mirror +{ + public enum RemovePlayerOptions + { + /// Player Object remains active on server and clients. Only ownership is removed + KeepActive, + /// Player Object is unspawned on clients but remains on server + Unspawn, + /// Player Object is destroyed on server and clients + Destroy + } + + /// NetworkServer handles remote connections and has a local connection for a local client. + public static partial class NetworkServer + { + static bool initialized; + public static int maxConnections; + + /// Server Update frequency, per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE. + // overwritten by NetworkManager (if any) + public static int tickRate = 60; + + // tick rate is in Hz. + // convert to interval in seconds for convenience where needed. + // + // send interval is 1 / sendRate. + // but for tests we need a way to set it to exactly 0. + // 1 / int.max would not be exactly 0, so handel that manually. + public static float tickInterval => tickRate < int.MaxValue ? 1f / tickRate : 0; // for 30 Hz, that's 33ms + + // time & value snapshot interpolation are separate. + // -> time is interpolated globally on NetworkClient / NetworkConnection + // -> value is interpolated per-component, i.e. NetworkTransform. + // however, both need to be on the same send interval. + public static int sendRate => tickRate; + public static float sendInterval => sendRate < int.MaxValue ? 1f / sendRate : 0; // for 30 Hz, that's 33ms + static double lastSendTime; + + /// Connection to host mode client (if any) + public static LocalConnectionToClient localConnection { get; private set; } + + /// Dictionary of all server connections, with connectionId as key + public static Dictionary connections = + new Dictionary(); + + /// Message Handlers dictionary, with messageId as key + internal static Dictionary handlers = + new Dictionary(); + + /// All spawned NetworkIdentities by netId. + // server sees ALL spawned ones. + public static readonly Dictionary spawned = + new Dictionary(); + + /// Single player mode can use dontListen to not accept incoming connections + // see also: https://github.com/vis2k/Mirror/pull/2595 + public static bool dontListen; + + /// active checks if the server has been started either has standalone or as host server. + public static bool active { get; internal set; } + + /// active checks if the server has been started in host mode. + // naming consistent with NetworkClient.activeHost. + public static bool activeHost => localConnection != null; + + // scene loading + public static bool isLoadingScene; + + // interest management component (optional) + // by default, everyone observes everyone + public static InterestManagementBase aoi; + + // For security, it is recommended to disconnect a player if a networked + // action triggers an exception\nThis could prevent components being + // accessed in an undefined state, which may be an attack vector for + // exploits. + // + // However, some games may want to allow exceptions in order to not + // interrupt the player's experience. + public static bool exceptionsDisconnect = true; // security by default + + // Mirror global disconnect inactive option, independent of Transport. + // not all Transports do this properly, and it's easiest to configure this just once. + // this is very useful for some projects, keep it. + public static bool disconnectInactiveConnections; + public static float disconnectInactiveTimeout = 60; + + // OnConnected / OnDisconnected used to be NetworkMessages that were + // invoked. this introduced a bug where external clients could send + // Connected/Disconnected messages over the network causing undefined + // behaviour. + // => public so that custom NetworkManagers can hook into it + public static Action OnConnectedEvent; + public static Action OnDisconnectedEvent; + public static Action OnErrorEvent; + public static Action OnTransportExceptionEvent; + + // keep track of actual achieved tick rate. + // might become lower under heavy load. + // very useful for profiling etc. + // measured over 1s each, same as frame rate. no EMA here. + public static int actualTickRate; + static double actualTickRateStart; // start time when counting + static int actualTickRateCounter; // current counter since start + + // profiling + // includes transport update time, because transport calls handlers etc. + // averaged over 1s by passing 'tickRate' to constructor. + public static TimeSample earlyUpdateDuration; + public static TimeSample lateUpdateDuration; + + // capture full Unity update time from before Early- to after LateUpdate + public static TimeSample fullUpdateDuration; + + /// Starts server and listens to incoming connections with max connections limit. + public static void Listen(int maxConns) + { + Initialize(); + maxConnections = maxConns; + + // only start server if we want to listen + if (!dontListen) + { + Transport.active.ServerStart(); + + if (Transport.active is PortTransport portTransport) + { + if (Utils.IsHeadless()) + { +#if !UNITY_EDITOR + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"Server listening on port {portTransport.Port}"); + Console.ResetColor(); +#else + Debug.Log($"Server listening on port {portTransport.Port}"); +#endif + } + } + else + Debug.Log("Server started listening"); + } + + active = true; + RegisterMessageHandlers(); + } + + // initialization / shutdown /////////////////////////////////////////// + static void Initialize() + { + if (initialized) + return; + + // safety: ensure Weaving succeded. + // if it silently failed, we would get lots of 'writer not found' + // and other random errors at runtime instead. this is cleaner. + if (!WeaverFuse.Weaved()) + { + // if it failed, throw an exception to early exit all Listen calls. + throw new Exception("NetworkServer won't start because Weaving failed or didn't run."); + } + + // Debug.Log($"NetworkServer Created version {Version.Current}"); + + //Make sure connections are cleared in case any old connections references exist from previous sessions + connections.Clear(); + + // reset Interest Management so that rebuild intervals + // start at 0 when starting again. + if (aoi != null) aoi.ResetState(); + + // reset NetworkTime + NetworkTime.ResetStatics(); + + Debug.Assert(Transport.active != null, "There was no active transport when calling NetworkServer.Listen, If you are calling Listen manually then make sure to set 'Transport.active' first"); + AddTransportHandlers(); + + initialized = true; + + // profiling + earlyUpdateDuration = new TimeSample(sendRate); + lateUpdateDuration = new TimeSample(sendRate); + fullUpdateDuration = new TimeSample(sendRate); + } + + static void AddTransportHandlers() + { + // += so that other systems can also hook into it (i.e. statistics) + Transport.active.OnServerConnected += OnTransportConnected; + Transport.active.OnServerDataReceived += OnTransportData; + Transport.active.OnServerDisconnected += OnTransportDisconnected; + Transport.active.OnServerError += OnTransportError; + Transport.active.OnServerTransportException += OnTransportException; + } + + /// Shuts down the server and disconnects all clients + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + public static void Shutdown() + { + if (initialized) + { + DisconnectAll(); + + // stop the server. + // we do NOT call Transport.Shutdown, because someone only + // called NetworkServer.Shutdown. we can't assume that the + // client is supposed to be shut down too! + // + // NOTE: stop no matter what, even if 'dontListen': + // someone might enabled dontListen at runtime. + // but we still need to stop the server. + // fixes https://github.com/vis2k/Mirror/issues/2536 + Transport.active.ServerStop(); + + // transport handlers are hooked into when initializing. + // so only remove them when shutting down. + RemoveTransportHandlers(); + + initialized = false; + } + + // Reset all statics here.... + dontListen = false; + isLoadingScene = false; + lastSendTime = 0; + actualTickRate = 0; + + localConnection = null; + + connections.Clear(); + connectionsCopy.Clear(); + handlers.Clear(); + + // destroy all spawned objects, _then_ set inactive. + // make sure .active is still true before calling this. + // otherwise modifying SyncLists in OnStopServer would throw + // because .IsWritable() check checks if NetworkServer.active. + // https://github.com/MirrorNetworking/Mirror/issues/3344 + CleanupSpawned(); + active = false; + + // sets nextNetworkId to 1 + // sets clientAuthorityCallback to null + // sets previousLocalPlayer to null + NetworkIdentity.ResetStatics(); + + // clear events. someone might have hooked into them before, but + // we don't want to use those hooks after Shutdown anymore. + OnConnectedEvent = null; + OnDisconnectedEvent = null; + OnErrorEvent = null; + OnTransportExceptionEvent = null; + + if (aoi != null) aoi.ResetState(); + } + + static void RemoveTransportHandlers() + { + // -= so that other systems can also hook into it (i.e. statistics) + Transport.active.OnServerConnected -= OnTransportConnected; + Transport.active.OnServerDataReceived -= OnTransportData; + Transport.active.OnServerDisconnected -= OnTransportDisconnected; + Transport.active.OnServerError -= OnTransportError; + } + + // Note: NetworkClient.DestroyAllClientObjects does the same on client. + static void CleanupSpawned() + { + // iterate a COPY of spawned. + // DestroyObject removes them from the original collection. + // removing while iterating is not allowed. + foreach (NetworkIdentity identity in spawned.Values.ToList()) + { + if (identity != null) + { + // NetworkServer.Destroy resets if scene object, destroys if prefab. + Destroy(identity.gameObject); + } + } + + spawned.Clear(); + } + + internal static void RegisterMessageHandlers() + { + RegisterHandler(OnClientReadyMessage); + RegisterHandler(OnCommandMessage); + RegisterHandler(NetworkTime.OnServerPing, false); + RegisterHandler(NetworkTime.OnServerPong, false); + RegisterHandler(OnEntityStateMessage, true); + RegisterHandler(OnTimeSnapshotMessage, true); + } + + // remote calls //////////////////////////////////////////////////////// + // Handle command from specific player, this could be one of multiple + // players on a single client + // default ready handler. + static void OnClientReadyMessage(NetworkConnectionToClient conn, ReadyMessage msg) + { + // Debug.Log($"Default handler for ready message from {conn}"); + SetClientReady(conn); + } + + static void OnCommandMessage(NetworkConnectionToClient conn, CommandMessage msg, int channelId) + { + if (!conn.isReady) + { + // Clients may be set NotReady due to scene change or other game logic by user, e.g. respawning. + // Ignore commands that may have been in flight before client received NotReadyMessage message. + // Unreliable messages may be out of order, so don't spam warnings for those. + if (channelId == Channels.Reliable) + { + // Attempt to identify the target object, component, and method to narrow down the cause of the error. + if (spawned.TryGetValue(msg.netId, out NetworkIdentity netIdentity)) + if (msg.componentIndex < netIdentity.NetworkBehaviours.Length && netIdentity.NetworkBehaviours[msg.componentIndex] is NetworkBehaviour component) + if (RemoteProcedureCalls.GetFunctionMethodName(msg.functionHash, out string methodName)) + { + Debug.LogWarning($"Command {methodName} received for {netIdentity.name} [netId={msg.netId}] component {component.name} [index={msg.componentIndex}] when client not ready.\nThis may be ignored if client intentionally set NotReady."); + return; + } + + Debug.LogWarning("Command received while client is not ready.\nThis may be ignored if client intentionally set NotReady."); + } + return; + } + + if (!spawned.TryGetValue(msg.netId, out NetworkIdentity identity)) + { + // over reliable channel, commands should always come after spawn. + // over unreliable, they might come in before the object was spawned. + // for example, NetworkTransform. + // let's not spam the console for unreliable out of order messages. + if (channelId == Channels.Reliable) + Debug.LogWarning($"Spawned object not found when handling Command message netId={msg.netId}"); + return; + } + + // Commands can be for player objects, OR other objects with client-authority + // -> so if this connection's controller has a different netId then + // only allow the command if clientAuthorityOwner + bool requiresAuthority = RemoteProcedureCalls.CommandRequiresAuthority(msg.functionHash); + if (requiresAuthority && identity.connectionToClient != conn) + { + // Attempt to identify the component and method to narrow down the cause of the error. + if (msg.componentIndex < identity.NetworkBehaviours.Length && identity.NetworkBehaviours[msg.componentIndex] is NetworkBehaviour component) + if (RemoteProcedureCalls.GetFunctionMethodName(msg.functionHash, out string methodName)) + { + Debug.LogWarning($"Command {methodName} received for {identity.name} [netId={msg.netId}] component {component.name} [index={msg.componentIndex}] without authority"); + return; + } + + Debug.LogWarning($"Command received for {identity.name} [netId={msg.netId}] without authority"); + return; + } + + // Debug.Log($"OnCommandMessage for netId:{msg.netId} conn:{conn}"); + + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(msg.payload)) + identity.HandleRemoteCall(msg.componentIndex, msg.functionHash, RemoteCallType.Command, networkReader, conn); + } + + // client to server broadcast ////////////////////////////////////////// + // for client's owned ClientToServer components. + static void OnEntityStateMessage(NetworkConnectionToClient connection, EntityStateMessage message) + { + // need to validate permissions carefully. + // an attacker may attempt to modify a not-owned or not-ClientToServer component. + + // valid netId? + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity) && identity != null) + { + // owned by the connection? + if (identity.connectionToClient == connection) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message.payload)) + { + // DeserializeServer checks permissions internally. + // failure to deserialize disconnects to prevent exploits. + if (!identity.DeserializeServer(reader)) + { + if (exceptionsDisconnect) + { + Debug.LogError($"Server failed to deserialize client state for {identity.name} with netId={identity.netId}, Disconnecting."); + connection.Disconnect(); + } + else + Debug.LogWarning($"Server failed to deserialize client state for {identity.name} with netId={identity.netId}."); + } + } + } + // An attacker may attempt to modify another connection's entity + // This could also be a race condition of message in flight when + // RemoveClientAuthority is called, so not malicious. + // Don't disconnect, just log the warning. + else + Debug.LogWarning($"EntityStateMessage from {connection} for {identity.name} without authority."); + } + // no warning. don't spam server logs. + // else Debug.LogWarning($"Did not find target for sync message for {message.netId} . Note: this can be completely normal because UDP messages may arrive out of order, so this message might have arrived after a Destroy message."); + } + + // client sends TimeSnapshotMessage every sendInterval. + // batching already includes the remoteTimestamp. + // we simply insert it on-message here. + // => only for reliable channel. unreliable would always arrive earlier. + static void OnTimeSnapshotMessage(NetworkConnectionToClient connection, TimeSnapshotMessage _) + { + // insert another snapshot for snapshot interpolation. + // before calling OnDeserialize so components can use + // NetworkTime.time and NetworkTime.timeStamp. + + // TODO validation? + // maybe we shouldn't allow timeline to deviate more than a certain %. + // for now, this is only used for client authority movement. + + // Unity 2019 doesn't have Time.timeAsDouble yet + // + // NetworkTime uses unscaled time and ignores Time.timeScale. + // fixes Time.timeScale getting server & client time out of sync: + // https://github.com/MirrorNetworking/Mirror/issues/3409 + connection.OnTimeSnapshot(new TimeSnapshot(connection.remoteTimeStamp, NetworkTime.localTime)); + } + + // connections ///////////////////////////////////////////////////////// + /// Add a connection and setup callbacks. Returns true if not added yet. + public static bool AddConnection(NetworkConnectionToClient conn) + { + if (!connections.ContainsKey(conn.connectionId)) + { + // connection cannot be null here or conn.connectionId + // would throw NRE + connections[conn.connectionId] = conn; + return true; + } + // already a connection with this id + return false; + } + + /// Removes a connection by connectionId. Returns true if removed. + public static bool RemoveConnection(int connectionId) => + connections.Remove(connectionId); + + // called by LocalClient to add itself. don't call directly. + // TODO consider internal setter instead? + internal static void SetLocalConnection(LocalConnectionToClient conn) + { + if (localConnection != null) + { + Debug.LogError("Local Connection already exists"); + return; + } + + localConnection = conn; + } + + // removes local connection to client + internal static void RemoveLocalConnection() + { + if (localConnection != null) + { + localConnection.Disconnect(); + localConnection = null; + } + RemoveConnection(0); + } + + /// True if we have external connections (that are not host) + public static bool HasExternalConnections() + { + // any connections? + if (connections.Count > 0) + { + // only host connection? + if (connections.Count == 1 && localConnection != null) + return false; + + // otherwise we have real external connections + return true; + } + return false; + } + + // send //////////////////////////////////////////////////////////////// + /// Send a message to all clients, even those that haven't joined the world yet (non ready) + public static void SendToAll(T message, int channelId = Channels.Reliable, bool sendToReadyOnly = false) + where T : struct, NetworkMessage + { + if (!active) + { + Debug.LogWarning("Can not send using NetworkServer.SendToAll(T msg) because NetworkServer is not active"); + return; + } + + // Debug.Log($"Server.SendToAll {typeof(T)}"); + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // pack message only once + NetworkMessages.Pack(message, writer); + ArraySegment segment = writer.ToArraySegment(); + + // validate packet size immediately. + // we know how much can fit into one batch at max. + // if it's larger, log an error immediately with the type . + // previously we only logged in Update() when processing batches, + // but there we don't have type information anymore. + int max = NetworkMessages.MaxMessageSize(channelId); + if (writer.Position > max) + { + Debug.LogError($"NetworkServer.SendToAll: message of type {typeof(T)} with a size of {writer.Position} bytes is larger than the max allowed message size in one batch: {max}.\nThe message was dropped, please make it smaller."); + return; + } + + // filter and then send to all internet connections at once + // -> makes code more complicated, but is HIGHLY worth it to + // avoid allocations, allow for multicast, etc. + int count = 0; + foreach (NetworkConnectionToClient conn in connections.Values) + { + if (sendToReadyOnly && !conn.isReady) + continue; + + count++; + conn.Send(segment, channelId); + } + + NetworkDiagnostics.OnSend(message, channelId, segment.Count, count); + } + } + + /// Send a message to all clients which have joined the world (are ready). + // TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady! + public static void SendToReady(T message, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + if (!active) + { + Debug.LogWarning("Can not send using NetworkServer.SendToReady(T msg) because NetworkServer is not active"); + return; + } + + SendToAll(message, channelId, true); + } + + // this is like SendToReadyObservers - but it doesn't check the ready flag on the connection. + // this is used for ObjectDestroy messages. + static void SendToObservers(NetworkIdentity identity, T message, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + // Debug.Log($"Server.SendToObservers {typeof(T)}"); + if (identity == null || identity.observers.Count == 0) + return; + + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // pack message into byte[] once + NetworkMessages.Pack(message, writer); + ArraySegment segment = writer.ToArraySegment(); + + // validate packet size immediately. + // we know how much can fit into one batch at max. + // if it's larger, log an error immediately with the type . + // previously we only logged in Update() when processing batches, + // but there we don't have type information anymore. + int max = NetworkMessages.MaxMessageSize(channelId); + if (writer.Position > max) + { + Debug.LogError($"NetworkServer.SendToObservers: message of type {typeof(T)} with a size of {writer.Position} bytes is larger than the max allowed message size in one batch: {max}.\nThe message was dropped, please make it smaller."); + return; + } + + foreach (NetworkConnectionToClient conn in identity.observers.Values) + { + conn.Send(segment, channelId); + } + + NetworkDiagnostics.OnSend(message, channelId, segment.Count, identity.observers.Count); + } + } + + /// Send a message to only clients which are ready with option to include the owner of the object identity + // TODO obsolete this later. it's not used anymore + public static void SendToReadyObservers(NetworkIdentity identity, T message, bool includeOwner = true, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + // Debug.Log($"Server.SendToReady {typeof(T)}"); + if (identity == null || identity.observers.Count == 0) + return; + + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // pack message only once + NetworkMessages.Pack(message, writer); + ArraySegment segment = writer.ToArraySegment(); + + // validate packet size immediately. + // we know how much can fit into one batch at max. + // if it's larger, log an error immediately with the type . + // previously we only logged in Update() when processing batches, + // but there we don't have type information anymore. + int max = NetworkMessages.MaxMessageSize(channelId); + if (writer.Position > max) + { + Debug.LogError($"NetworkServer.SendToReadyObservers: message of type {typeof(T)} with a size of {writer.Position} bytes is larger than the max allowed message size in one batch: {max}.\nThe message was dropped, please make it smaller."); + return; + } + + int count = 0; + foreach (NetworkConnectionToClient conn in identity.observers.Values) + { + bool isOwner = conn == identity.connectionToClient; + if ((!isOwner || includeOwner) && conn.isReady) + { + count++; + conn.Send(segment, channelId); + } + } + + NetworkDiagnostics.OnSend(message, channelId, segment.Count, count); + } + } + + /// Send a message to only clients which are ready including the owner of the NetworkIdentity + // TODO obsolete this later. it's not used anymore + public static void SendToReadyObservers(NetworkIdentity identity, T message, int channelId) + where T : struct, NetworkMessage + { + SendToReadyObservers(identity, message, true, channelId); + } + + // transport events //////////////////////////////////////////////////// + // called by transport + static void OnTransportConnected(int connectionId) + { + // Debug.Log($"Server accepted client:{connectionId}"); + + // connectionId needs to be != 0 because 0 is reserved for local player + // note that some transports like kcp generate connectionId by + // hashing which can be < 0 as well, so we need to allow < 0! + if (connectionId == 0) + { + Debug.LogError($"Server.HandleConnect: invalid connectionId: {connectionId} . Needs to be != 0, because 0 is reserved for local player."); + Transport.active.ServerDisconnect(connectionId); + return; + } + + // connectionId not in use yet? + if (connections.ContainsKey(connectionId)) + { + Transport.active.ServerDisconnect(connectionId); + // Debug.Log($"Server connectionId {connectionId} already in use...kicked client"); + return; + } + + // are more connections allowed? if not, kick + // (it's easier to handle this in Mirror, so Transports can have + // less code and third party transport might not do that anyway) + // (this way we could also send a custom 'tooFull' message later, + // Transport can't do that) + if (connections.Count < maxConnections) + { + // add connection + NetworkConnectionToClient conn = new NetworkConnectionToClient(connectionId); + OnConnected(conn); + } + else + { + // kick + Transport.active.ServerDisconnect(connectionId); + // Debug.Log($"Server full, kicked client {connectionId}"); + } + } + + internal static void OnConnected(NetworkConnectionToClient conn) + { + // Debug.Log($"Server accepted client:{conn}"); + + // add connection and invoke connected event + AddConnection(conn); + OnConnectedEvent?.Invoke(conn); + } + + static bool UnpackAndInvoke(NetworkConnectionToClient connection, NetworkReader reader, int channelId) + { + if (NetworkMessages.UnpackId(reader, out ushort msgType)) + { + // try to invoke the handler for that message + if (handlers.TryGetValue(msgType, out NetworkMessageDelegate handler)) + { + handler.Invoke(connection, reader, channelId); + connection.lastMessageTime = Time.time; + return true; + } + else + { + // message in a batch are NOT length prefixed to save bandwidth. + // every message needs to be handled and read until the end. + // otherwise it would overlap into the next message. + // => need to warn and disconnect to avoid undefined behaviour. + // => WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning($"Unknown message id: {msgType} for connection: {connection}. This can happen if no handler was registered for this message."); + // simply return false. caller is responsible for disconnecting. + //connection.Disconnect(); + return false; + } + } + else + { + // => WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning($"Invalid message header for connection: {connection}."); + // simply return false. caller is responsible for disconnecting. + //connection.Disconnect(); + return false; + } + } + + // called by transport + internal static void OnTransportData(int connectionId, ArraySegment data, int channelId) + { + if (connections.TryGetValue(connectionId, out NetworkConnectionToClient connection)) + { + // client might batch multiple messages into one packet. + // feed it to the Unbatcher. + // NOTE: we don't need to associate a channelId because we + // always process all messages in the batch. + if (!connection.unbatcher.AddBatch(data)) + { + if (exceptionsDisconnect) + { + Debug.LogError($"NetworkServer: received message from connectionId:{connectionId} was too short (messages should start with message id). Disconnecting."); + connection.Disconnect(); + } + else + Debug.LogWarning($"NetworkServer: received message from connectionId:{connectionId} was too short (messages should start with message id)."); + + return; + } + + // process all messages in the batch. + // only while NOT loading a scene. + // if we get a scene change message, then we need to stop + // processing. otherwise we might apply them to the old scene. + // => fixes https://github.com/vis2k/Mirror/issues/2651 + // + // NOTE: if scene starts loading, then the rest of the batch + // would only be processed when OnTransportData is called + // the next time. + // => consider moving processing to NetworkEarlyUpdate. + while (!isLoadingScene && + connection.unbatcher.GetNextMessage(out ArraySegment message, out double remoteTimestamp)) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message)) + { + // enough to read at least header size? + if (reader.Remaining >= NetworkMessages.IdSize) + { + // make remoteTimeStamp available to the user + connection.remoteTimeStamp = remoteTimestamp; + + // handle message + if (!UnpackAndInvoke(connection, reader, channelId)) + { + // warn, disconnect and return if failed + // -> warning because attackers might send random data + // -> messages in a batch aren't length prefixed. + // failing to read one would cause undefined + // behaviour for every message afterwards. + // so we need to disconnect. + // -> return to avoid the below unbatches.count error. + // we already disconnected and handled it. + if (exceptionsDisconnect) + { + Debug.LogError($"NetworkServer: failed to unpack and invoke message. Disconnecting {connectionId}."); + connection.Disconnect(); + } + else + Debug.LogWarning($"NetworkServer: failed to unpack and invoke message from connectionId:{connectionId}."); + + return; + } + } + // otherwise disconnect + else + { + if (exceptionsDisconnect) + { + Debug.LogError($"NetworkServer: received message from connectionId:{connectionId} was too short (messages should start with message id). Disconnecting."); + connection.Disconnect(); + } + else + Debug.LogWarning($"NetworkServer: received message from connectionId:{connectionId} was too short (messages should start with message id)."); + + return; + } + } + } + + // if we weren't interrupted by a scene change, + // then all batched messages should have been processed now. + // otherwise batches would silently grow. + // we need to log an error to avoid debugging hell. + // + // EXAMPLE: https://github.com/vis2k/Mirror/issues/2882 + // -> UnpackAndInvoke silently returned because no handler for id + // -> Reader would never be read past the end + // -> Batch would never be retired because end is never reached + // + // NOTE: prefixing every message in a batch with a length would + // avoid ever not reading to the end. for extra bandwidth. + // + // IMPORTANT: always keep this check to detect memory leaks. + // this took half a day to debug last time. + if (!isLoadingScene && connection.unbatcher.BatchesCount > 0) + { + Debug.LogError($"Still had {connection.unbatcher.BatchesCount} batches remaining after processing, even though processing was not interrupted by a scene change. This should never happen, as it would cause ever growing batches.\nPossible reasons:\n* A message didn't deserialize as much as it serialized\n*There was no message handler for a message id, so the reader wasn't read until the end."); + } + } + else Debug.LogError($"HandleData Unknown connectionId:{connectionId}"); + } + + // called by transport + // IMPORTANT: often times when disconnecting, we call this from Mirror + // too because we want to remove the connection and handle + // the disconnect immediately. + // => which is fine as long as we guarantee it only runs once + // => which we do by removing the connection! + internal static void OnTransportDisconnected(int connectionId) + { + // Debug.Log($"Server disconnect client:{connectionId}"); + if (connections.TryGetValue(connectionId, out NetworkConnectionToClient conn)) + { + conn.Cleanup(); + RemoveConnection(connectionId); + // Debug.Log($"Server lost client:{connectionId}"); + + // NetworkManager hooks into OnDisconnectedEvent to make + // DestroyPlayerForConnection(conn) optional, e.g. for PvP MMOs + // where players shouldn't be able to escape combat instantly. + if (OnDisconnectedEvent != null) + { + OnDisconnectedEvent.Invoke(conn); + } + // if nobody hooked into it, then simply call DestroyPlayerForConnection + else + { + DestroyPlayerForConnection(conn); + } + } + } + + // transport errors are forwarded to high level + static void OnTransportError(int connectionId, TransportError error, string reason) + { + // transport errors will happen. logging a warning is enough. + // make sure the user does not panic. + Debug.LogWarning($"Server Transport Error for connId={connectionId}: {error}: {reason}. This is fine."); + // try get connection. passes null otherwise. + connections.TryGetValue(connectionId, out NetworkConnectionToClient conn); + OnErrorEvent?.Invoke(conn, error, reason); + } + + // transport errors are forwarded to high level + static void OnTransportException(int connectionId, Exception exception) + { + // transport errors will happen. logging a warning is enough. + // make sure the user does not panic. + Debug.LogWarning($"Server Transport Exception for connId={connectionId}: {exception}"); + // try get connection. passes null otherwise. + connections.TryGetValue(connectionId, out NetworkConnectionToClient conn); + OnTransportExceptionEvent?.Invoke(conn, exception); + } + + /// Destroys all of the connection's owned objects on the server. + // This is used when a client disconnects, to remove the players for + // that client. This also destroys non-player objects that have client + // authority set for this connection. + public static void DestroyPlayerForConnection(NetworkConnectionToClient conn) + { + // destroy all objects owned by this connection, including the player object + conn.DestroyOwnedObjects(); + // remove connection from all of its observing entities observers + // fixes https://github.com/vis2k/Mirror/issues/2737 + // -> cleaning those up in NetworkConnection.Disconnect is NOT enough + // because voluntary disconnects from the other end don't call + // NetworkConnection.Disconnect() + conn.RemoveFromObservingsObservers(); + conn.identity = null; + } + + // message handlers //////////////////////////////////////////////////// + /// Register a handler for message type T. Most should require authentication. + // TODO obsolete this some day to always use the channelId version. + // all handlers in this version are wrapped with 1 extra action. + public static void RegisterHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + if (handlers.ContainsKey(msgType)) + { + Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning."); + } + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + handlers[msgType] = NetworkMessages.WrapHandler(handler, requireAuthentication, exceptionsDisconnect); + } + + /// Register a handler for message type T. Most should require authentication. + // This version passes channelId to the handler. + public static void RegisterHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + if (handlers.ContainsKey(msgType)) + { + Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning."); + } + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + handlers[msgType] = NetworkMessages.WrapHandler(handler, requireAuthentication, exceptionsDisconnect); + } + + /// Replace a handler for message type T. Most should require authentication. + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ReplaceHandler((_, value) => { handler(value); }, requireAuthentication); + } + + /// Replace a handler for message type T. Most should require authentication. + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + handlers[msgType] = NetworkMessages.WrapHandler(handler, requireAuthentication, exceptionsDisconnect); + } + + /// Replace a handler for message type T. Most should require authentication. + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + handlers[msgType] = NetworkMessages.WrapHandler(handler, requireAuthentication, exceptionsDisconnect); + } + + /// Unregister a handler for a message type T. + public static void UnregisterHandler() + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + handlers.Remove(msgType); + } + + /// Clears all registered message handlers. + public static void ClearHandlers() => handlers.Clear(); + + internal static bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity) + { + if (!go.TryGetComponent(out identity)) + { + Debug.LogError($"GameObject {go.name} doesn't have NetworkIdentity."); + return false; + } + return true; + } + + // disconnect ////////////////////////////////////////////////////////// + /// Disconnect all connections, including the local connection. + // synchronous: handles disconnect events and cleans up fully before returning! + public static void DisconnectAll() + { + // disconnect and remove all connections. + // we can not use foreach here because if + // conn.Disconnect -> Transport.ServerDisconnect calls + // OnDisconnect -> NetworkServer.OnDisconnect(connectionId) + // immediately then OnDisconnect would remove the connection while + // we are iterating here. + // see also: https://github.com/vis2k/Mirror/issues/2357 + // this whole process should be simplified some day. + // until then, let's copy .Values to avoid InvalidOperationException. + // note that this is only called when stopping the server, so the + // copy is no performance problem. + foreach (NetworkConnectionToClient conn in connections.Values.ToList()) + { + // disconnect via connection->transport + conn.Disconnect(); + + // we want this function to be synchronous: handle disconnect + // events and clean up fully before returning. + // -> OnTransportDisconnected can safely be called without + // waiting for the Transport's callback. + // -> it has checks to only run once. + + // call OnDisconnected unless local player in host mod + // TODO unnecessary check? + if (conn.connectionId != NetworkConnection.LocalConnectionId) + OnTransportDisconnected(conn.connectionId); + } + + // cleanup + connections.Clear(); + localConnection = null; + // this used to set active=false. + // however, then Shutdown can't properly destroy objects: + // https://github.com/MirrorNetworking/Mirror/issues/3344 + // "DisconnectAll" should only disconnect all, not set inactive. + // active = false; + } + + // add/remove/replace player /////////////////////////////////////////// + /// Called by server after AddPlayer message to add the player for the connection. + // When a player is added for a connection, the client for that + // connection is made ready automatically. The player object is + // automatically spawned, so you do not need to call NetworkServer.Spawn + // for that object. This function is used for "adding" a player, not for + // "replacing" the player on a connection. If there is already a player + // on this playerControllerId for this connection, this will fail. + public static bool AddPlayerForConnection(NetworkConnectionToClient conn, GameObject player, uint assetId) + { + if (GetNetworkIdentity(player, out NetworkIdentity identity)) + { + identity.assetId = assetId; + } + return AddPlayerForConnection(conn, player); + } + + /// Called by server after AddPlayer message to add the player for the connection. + // When a player is added for a connection, the client for that + // connection is made ready automatically. The player object is + // automatically spawned, so you do not need to call NetworkServer.Spawn + // for that object. This function is used for "adding" a player, not for + // "replacing" the player on a connection. If there is already a player + // on this playerControllerId for this connection, this will fail. + public static bool AddPlayerForConnection(NetworkConnectionToClient conn, GameObject player) + { + if (!player.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogWarning($"AddPlayer: player GameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}"); + return false; + } + + // cannot have a player object in "Add" version + if (conn.identity != null) + { + Debug.Log("AddPlayer: player object already exists"); + return false; + } + + // make sure we have a controller before we call SetClientReady + // because the observers will be rebuilt only if we have a controller + conn.identity = identity; + + // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients) + identity.SetClientOwner(conn); + + // special case, we are in host mode, set hasAuthority to true so that all overrides see it + if (conn is LocalConnectionToClient) + { + identity.isOwned = true; + NetworkClient.InternalAddPlayer(identity); + } + + // set ready if not set yet + SetClientReady(conn); + + // Debug.Log($"Adding new playerGameObject object netId: {identity.netId} asset ID: {identity.assetId}"); + + Respawn(identity); + return true; + } + + /// Replaces connection's player object. The old object is not destroyed. + // This does NOT change the ready state of the connection, so it can + // safely be used while changing scenes. + public static bool ReplacePlayerForConnection(NetworkConnectionToClient conn, GameObject player, bool keepAuthority = false) + { + if (!player.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"ReplacePlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}"); + return false; + } + + if (identity.connectionToClient != null && identity.connectionToClient != conn) + { + Debug.LogError($"Cannot replace player for connection. New player is already owned by a different connection{player}"); + return false; + } + + //NOTE: there can be an existing player + //Debug.Log("NetworkServer ReplacePlayer"); + + NetworkIdentity previousPlayer = conn.identity; + + conn.identity = identity; + + // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients) + identity.SetClientOwner(conn); + + // special case, we are in host mode, set hasAuthority to true so that all overrides see it + if (conn is LocalConnectionToClient) + { + identity.isOwned = true; + NetworkClient.InternalAddPlayer(identity); + } + + // add connection to observers AFTER the playerController was set. + // by definition, there is nothing to observe if there is no player + // controller. + // + // IMPORTANT: do this in AddPlayerForConnection & ReplacePlayerForConnection! + SpawnObserversForConnection(conn); + + //Debug.Log($"Replacing playerGameObject object netId:{player.GetComponent().netId} asset ID {player.GetComponent().assetId}"); + + Respawn(identity); + + if (keepAuthority) + { + // This needs to be sent to clear isLocalPlayer on + // client while keeping hasAuthority true + SendChangeOwnerMessage(previousPlayer, conn); + } + else + { + // This clears both isLocalPlayer and hasAuthority on client + previousPlayer.RemoveClientAuthority(); + } + + return true; + } + + /// Replaces connection's player object. The old object is not destroyed. + // This does NOT change the ready state of the connection, so it can + // safely be used while changing scenes. + public static bool ReplacePlayerForConnection(NetworkConnectionToClient conn, GameObject player, uint assetId, bool keepAuthority = false) + { + if (GetNetworkIdentity(player, out NetworkIdentity identity)) + { + identity.assetId = assetId; + } + return ReplacePlayerForConnection(conn, player, keepAuthority); + } + + /// Removes the player object from the connection + // destroyServerObject: Indicates whether the server object should be destroyed + // Deprecated 2024-06-06 + [Obsolete("Use RemovePlayerForConnection(NetworkConnectionToClient conn, RemovePlayerOptions removeOptions) instead")] + public static void RemovePlayerForConnection(NetworkConnectionToClient conn, bool destroyServerObject) + { + if (destroyServerObject) + RemovePlayerForConnection(conn, RemovePlayerOptions.Destroy); + else + RemovePlayerForConnection(conn, RemovePlayerOptions.Unspawn); + } + + /// Removes player object for the connection. Options to keep the object in play, unspawn it, or destroy it. + public static void RemovePlayerForConnection(NetworkConnectionToClient conn, RemovePlayerOptions removeOptions = RemovePlayerOptions.KeepActive) + { + if (conn.identity == null) return; + + switch (removeOptions) + { + case RemovePlayerOptions.KeepActive: + conn.identity.connectionToClient = null; + conn.owned.Remove(conn.identity); + SendChangeOwnerMessage(conn.identity, conn); + break; + case RemovePlayerOptions.Unspawn: + UnSpawn(conn.identity.gameObject); + break; + case RemovePlayerOptions.Destroy: + Destroy(conn.identity.gameObject); + break; + } + + conn.identity = null; + } + + // ready /////////////////////////////////////////////////////////////// + /// Flags client connection as ready (=joined world). + // When a client has signaled that it is ready, this method tells the + // server that the client is ready to receive spawned objects and state + // synchronization updates. This is usually called in a handler for the + // SYSTEM_READY message. If there is not specific action a game needs to + // take for this message, relying on the default ready handler function + // is probably fine, so this call wont be needed. + public static void SetClientReady(NetworkConnectionToClient conn) + { + // Debug.Log($"SetClientReadyInternal for conn:{conn}"); + + // set ready + conn.isReady = true; + + // client is ready to start spawning objects + if (conn.identity != null) + SpawnObserversForConnection(conn); + } + + static void SpawnObserversForConnection(NetworkConnectionToClient conn) + { + //Debug.Log($"Spawning {spawned.Count} objects for conn {conn}"); + + if (!conn.isReady) + { + // client needs to finish initializing before we can spawn objects + // otherwise it would not find them. + return; + } + + // let connection know that we are about to start spawning... + conn.Send(new ObjectSpawnStartedMessage()); + + // add connection to each nearby NetworkIdentity's observers, which + // internally sends a spawn message for each one to the connection. + foreach (NetworkIdentity identity in spawned.Values) + { + // try with far away ones in ummorpg! + if (identity.gameObject.activeSelf) //TODO this is different + { + //Debug.Log($"Sending spawn message for current server objects name:{identity.name} netId:{identity.netId} sceneId:{identity.sceneId:X}"); + + // we need to support three cases: + // - legacy system (identity has .visibility) + // - new system (networkserver has .aoi) + // - default case: no .visibility and no .aoi means add all + // connections by default) + // + // ForceHidden/ForceShown overwrite all systems so check it + // first! + + // ForceShown: add no matter what + if (identity.visibility == Visibility.ForceShown) + { + identity.AddObserver(conn); + } + // ForceHidden: don't show no matter what + else if (identity.visibility == Visibility.ForceHidden) + { + // do nothing + } + // default: legacy system / new system / no system support + else if (identity.visibility == Visibility.Default) + { + // aoi system + if (aoi != null) + { + // call OnCheckObserver + if (aoi.OnCheckObserver(identity, conn)) + identity.AddObserver(conn); + } + // no system: add all observers by default + else + { + identity.AddObserver(conn); + } + } + } + } + + // let connection know that we finished spawning, so it can call + // OnStartClient on each one (only after all were spawned, which + // is how Unity's Start() function works too) + conn.Send(new ObjectSpawnFinishedMessage()); + } + + /// Marks the client of the connection to be not-ready. + // Clients that are not ready do not receive spawned objects or state + // synchronization updates. They client can be made ready again by + // calling SetClientReady(). + public static void SetClientNotReady(NetworkConnectionToClient conn) + { + conn.isReady = false; + conn.RemoveFromObservingsObservers(); + conn.Send(new NotReadyMessage()); + } + + /// Marks all connected clients as no longer ready. + // All clients will no longer be sent state synchronization updates. The + // player's clients can call ClientManager.Ready() again to re-enter the + // ready state. This is useful when switching scenes. + public static void SetAllClientsNotReady() + { + foreach (NetworkConnectionToClient conn in connections.Values) + { + SetClientNotReady(conn); + } + } + + // show / hide for connection ////////////////////////////////////////// + internal static void ShowForConnection(NetworkIdentity identity, NetworkConnection conn) + { + if (conn.isReady) + SendSpawnMessage(identity, conn); + } + + internal static void HideForConnection(NetworkIdentity identity, NetworkConnection conn) + { + ObjectHideMessage msg = new ObjectHideMessage + { + netId = identity.netId + }; + conn.Send(msg); + } + + // spawning //////////////////////////////////////////////////////////// + internal static void SendSpawnMessage(NetworkIdentity identity, NetworkConnection conn) + { + if (identity.serverOnly) return; + + //Debug.Log($"Server SendSpawnMessage: name:{identity.name} sceneId:{identity.sceneId:X} netid:{identity.netId}"); + + // one writer for owner, one for observers + using (NetworkWriterPooled ownerWriter = NetworkWriterPool.Get(), observersWriter = NetworkWriterPool.Get()) + { + bool isOwner = identity.connectionToClient == conn; + ArraySegment payload = CreateSpawnMessagePayload(isOwner, identity, ownerWriter, observersWriter); + SpawnMessage message = new SpawnMessage + { + netId = identity.netId, + isLocalPlayer = conn.identity == identity, + isOwner = isOwner, + sceneId = identity.sceneId, + assetId = identity.assetId, + // use local values for VR support + position = identity.transform.localPosition, + rotation = identity.transform.localRotation, + scale = identity.transform.localScale, + payload = payload + }; + conn.Send(message); + } + } + + static ArraySegment CreateSpawnMessagePayload(bool isOwner, NetworkIdentity identity, NetworkWriterPooled ownerWriter, NetworkWriterPooled observersWriter) + { + // Only call SerializeAll if there are NetworkBehaviours + if (identity.NetworkBehaviours.Length == 0) + { + return default; + } + + // serialize all components with initialState = true + // (can be null if has none) + identity.SerializeServer(true, ownerWriter, observersWriter); + + // convert to ArraySegment to avoid reader allocations + // if nothing was written, .ToArraySegment returns an empty segment. + ArraySegment ownerSegment = ownerWriter.ToArraySegment(); + ArraySegment observersSegment = observersWriter.ToArraySegment(); + + // use owner segment if 'conn' owns this identity, otherwise + // use observers segment + ArraySegment payload = isOwner ? ownerSegment : observersSegment; + + return payload; + } + + internal static void SendChangeOwnerMessage(NetworkIdentity identity, NetworkConnectionToClient conn) + { + // Don't send if identity isn't spawned or only exists on server + if (identity.netId == 0 || identity.serverOnly) return; + + // Don't send if conn doesn't have the identity spawned yet + // May be excluded from the client by interest management + if (!conn.observing.Contains(identity)) return; + + //Debug.Log($"Server SendChangeOwnerMessage: name={identity.name} netid={identity.netId}"); + + conn.Send(new ChangeOwnerMessage + { + netId = identity.netId, + isOwner = identity.connectionToClient == conn, + isLocalPlayer = (conn.identity == identity && identity.connectionToClient == conn) + }); + } + + // check NetworkIdentity parent before spawning it. + // - without parent, they are spawned + // - with parent, only if the parent is active in hierarchy + // + // note that active parents may have inactive parents of their own. + // we need to check .activeInHierarchy. + // + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3330 + // https://github.com/vis2k/Mirror/issues/2778 + static bool ValidParent(NetworkIdentity identity) => + identity.transform.parent == null || + identity.transform.parent.gameObject.activeInHierarchy; + + /// Spawns NetworkIdentities in the scene on the server. + // NetworkIdentity objects in a scene are disabled by default. Calling + // SpawnObjects() causes these scene objects to be enabled and spawned. + // It is like calling NetworkServer.Spawn() for each of them. + public static bool SpawnObjects() + { + // only if server active + if (!active) + return false; + + // find all NetworkIdentities in the scene. + // all of them are disabled because of NetworkScenePostProcess. + NetworkIdentity[] identities = Resources.FindObjectsOfTypeAll(); + + // first pass: activate all scene objects + foreach (NetworkIdentity identity in identities) + { + // only spawn scene objects which haven't been spawned yet. + // SpawnObjects may be called multiple times for additive scenes. + // https://github.com/MirrorNetworking/Mirror/issues/3318 + // + // note that we even activate objects under inactive parents. + // while they are not spawned, they do need to be activated + // in order to be spawned later. so here, we don't check parents. + // https://github.com/MirrorNetworking/Mirror/issues/3330 + if (Utils.IsSceneObject(identity) && identity.netId == 0) + { + // Debug.Log($"SpawnObjects sceneId:{identity.sceneId:X} name:{identity.gameObject.name}"); + identity.gameObject.SetActive(true); + } + } + + // second pass: spawn all scene objects + foreach (NetworkIdentity identity in identities) + { + // scene objects may be children of inactive parents. + // users would put them under disabled parents to 'deactivate' them. + // those should not be used by Mirror at all. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3330 + // https://github.com/vis2k/Mirror/issues/2778 + if (Utils.IsSceneObject(identity) && identity.netId == 0 && ValidParent(identity)) + { + // pass connection so that authority is not lost when server loads a scene + // https://github.com/vis2k/Mirror/pull/2987 + Spawn(identity.gameObject, identity.connectionToClient); + } + } + + return true; + } + + /// Spawns an object and also assigns Client Authority to the specified client. + // This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + public static void Spawn(GameObject obj, GameObject ownerPlayer) + { + if (!ownerPlayer.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError("Player object has no NetworkIdentity"); + return; + } + + if (identity.connectionToClient == null) + { + Debug.LogError("Player object is not a player."); + return; + } + + Spawn(obj, identity.connectionToClient); + } + + static void Respawn(NetworkIdentity identity) + { + if (identity.netId == 0) + { + // If the object has not been spawned, then do a full spawn and update observers + Spawn(identity.gameObject, identity.connectionToClient); + } + else + { + // otherwise just replace his data + SendSpawnMessage(identity, identity.connectionToClient); + } + } + + /// Spawn the given game object on all clients which are ready. + // This will cause a new object to be instantiated from the registered + // prefab, or from a custom spawn function. + public static void Spawn(GameObject obj, NetworkConnection ownerConnection = null) + { + SpawnObject(obj, ownerConnection); + } + + /// Spawns an object and also assigns Client Authority to the specified client. + // This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + public static void Spawn(GameObject obj, uint assetId, NetworkConnection ownerConnection = null) + { + if (GetNetworkIdentity(obj, out NetworkIdentity identity)) + { + identity.assetId = assetId; + } + SpawnObject(obj, ownerConnection); + } + + static void SpawnObject(GameObject obj, NetworkConnection ownerConnection) + { + // verify if we can spawn this + if (Utils.IsPrefab(obj)) + { + Debug.LogError($"GameObject {obj.name} is a prefab, it can't be spawned. Instantiate it first.", obj); + return; + } + + if (!active) + { + Debug.LogError($"SpawnObject for {obj}, NetworkServer is not active. Cannot spawn objects without an active server.", obj); + return; + } + + if (!obj.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"SpawnObject {obj} has no NetworkIdentity. Please add a NetworkIdentity to {obj}", obj); + return; + } + + if (identity.SpawnedFromInstantiate) + { + // Using Instantiate on SceneObject is not allowed, so stop spawning here + // NetworkIdentity.Awake already logs error, no need to log a second error here + return; + } + + // Spawn should only be called once per netId. + // calling it twice would lead to undefined behaviour. + // https://github.com/MirrorNetworking/Mirror/pull/3205 + if (spawned.ContainsKey(identity.netId)) + { + Debug.LogWarning($"{identity.name} [netId={identity.netId}] was already spawned.", identity.gameObject); + return; + } + + identity.connectionToClient = (NetworkConnectionToClient)ownerConnection; + + // special case to make sure hasAuthority is set + // on start server in host mode + if (ownerConnection is LocalConnectionToClient) + identity.isOwned = true; + + // NetworkServer.Unspawn sets object as inactive. + // NetworkServer.Spawn needs to set them active again in case they were previously unspawned / inactive. + identity.gameObject.SetActive(true); + + // only call OnStartServer if not spawned yet. + // check used to be in NetworkIdentity. may not be necessary anymore. + if (!identity.isServer && identity.netId == 0) + { + // configure NetworkIdentity + // this may be called in host mode, so we need to initialize + // isLocalPlayer/isClient flags too. + identity.isLocalPlayer = NetworkClient.localPlayer == identity; + identity.isClient = NetworkClient.active; + identity.isServer = true; + identity.netId = NetworkIdentity.GetNextNetworkId(); + + // add to spawned (after assigning netId) + spawned[identity.netId] = identity; + + // callback after all fields were set + identity.OnStartServer(); + } + + // Debug.Log($"SpawnObject instance ID {identity.netId} asset ID {identity.assetId}"); + + if (aoi) + { + // This calls user code which might throw exceptions + // We don't want this to leave us in bad state + try + { + aoi.OnSpawned(identity); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + + RebuildObservers(identity, true); + } + + /// This takes an object that has been spawned and un-spawns it. + // The object will be removed from clients that it was spawned on, or + // the custom spawn handler function on the client will be called for + // the object. + // Unlike when calling NetworkServer.Destroy(), on the server the object + // will NOT be destroyed. This allows the server to re-use the object, + // even spawn it again later. + public static void UnSpawn(GameObject obj) + { + // Debug.Log($"DestroyObject instance:{identity.netId}"); + + // NetworkServer.Unspawn should only be called on server or host. + // on client, show a warning to explain what it does. + if (!active) + { + Debug.LogWarning("NetworkServer.Unspawn() called without an active server. Servers can only destroy while active, clients can only ask the server to destroy (for example, with a [Command]), after which the server may decide to destroy the object and broadcast the change to all clients."); + return; + } + + if (obj == null) + { + Debug.Log("NetworkServer.Unspawn(): object is null"); + return; + } + + if (!GetNetworkIdentity(obj, out NetworkIdentity identity)) + { + return; + } + + // only call OnRebuildObservers while active, + // not while shutting down + // (https://github.com/vis2k/Mirror/issues/2977) + if (active && aoi) + { + // This calls user code which might throw exceptions + // We don't want this to leave us in bad state + try + { + aoi.OnDestroyed(identity); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + + // remove from NetworkServer (this) dictionary + spawned.Remove(identity.netId); + + identity.connectionToClient?.RemoveOwnedObject(identity); + + // send object destroy message to all observers, clear observers + SendToObservers(identity, new ObjectDestroyMessage + { + netId = identity.netId + }); + identity.ClearObservers(); + + // in host mode, call OnStopClient/OnStopLocalPlayer manually + if (NetworkClient.active && activeHost) + { + if (identity.isLocalPlayer) + identity.OnStopLocalPlayer(); + + identity.OnStopClient(); + // The object may have been spawned with host client ownership, + // e.g. a pet so we need to clear hasAuthority and call + // NotifyAuthority which invokes OnStopAuthority if hasAuthority. + identity.isOwned = false; + identity.NotifyAuthority(); + + // remove from NetworkClient dictionary + NetworkClient.connection.owned.Remove(identity); + NetworkClient.spawned.Remove(identity.netId); + } + + // we are on the server. call OnStopServer. + identity.OnStopServer(); + + // finally reset the state and deactivate it + identity.ResetState(); + identity.gameObject.SetActive(false); + } + + // destroy ///////////////////////////////////////////////////////////// + /// Destroys this object and corresponding objects on all clients. + // In some cases it is useful to remove an object but not delete it on + // the server. For that, use NetworkServer.UnSpawn() instead of + // NetworkServer.Destroy(). + public static void Destroy(GameObject obj) + { + // NetworkServer.Destroy should only be called on server or host. + // on client, show a warning to explain what it does. + if (!active) + { + Debug.LogWarning("NetworkServer.Destroy() called without an active server. Servers can only destroy while active, clients can only ask the server to destroy (for example, with a [Command]), after which the server may decide to destroy the object and broadcast the change to all clients."); + return; + } + + if (obj == null) + { + Debug.Log("NetworkServer.Destroy(): object is null"); + return; + } + + // first, we unspawn it on clients and server + UnSpawn(obj); + + // additionally, if it's a prefab then we destroy it completely. + // we never destroy scene objects on server or on client, since once + // they are gone, they are gone forever and can't be instantiate again. + // for example, server may Destroy() a scene object and once a match + // restarts, the scene objects would be gone from the new match. + if (GetNetworkIdentity(obj, out NetworkIdentity identity) && + identity.sceneId == 0) + { + identity.destroyCalled = true; + + // Destroy if application is running + if (Application.isPlaying) + { + UnityEngine.Object.Destroy(obj); + } + // Destroy can't be used in Editor during tests. use DestroyImmediate. + else + { + GameObject.DestroyImmediate(obj); + } + } + } + + // interest management ///////////////////////////////////////////////// + // Helper function to add all server connections as observers. + // This is used if none of the components provides their own + // OnRebuildObservers function. + // rebuild observers default method (no AOI) - adds all connections + static void RebuildObserversDefault(NetworkIdentity identity, bool initialize) + { + // only add all connections when rebuilding the first time. + // second time we just keep them without rebuilding anything. + if (initialize) + { + // not force hidden? + if (identity.visibility != Visibility.ForceHidden) + { + AddAllReadyServerConnectionsToObservers(identity); + } + else if (identity.connectionToClient != null) + { + // force hidden, but add owner connection + identity.AddObserver(identity.connectionToClient); + } + } + } + + internal static void AddAllReadyServerConnectionsToObservers(NetworkIdentity identity) + { + // add all server connections + foreach (NetworkConnectionToClient conn in connections.Values) + { + // only if authenticated (don't send to people during logins) + if (conn.isReady) + identity.AddObserver(conn); + } + + // add local host connection (if any) + if (localConnection != null && localConnection.isReady) + { + identity.AddObserver(localConnection); + } + } + + // RebuildObservers does a local rebuild for the NetworkIdentity. + // This causes the set of players that can see this object to be rebuild. + // + // IMPORTANT: + // => global rebuild would be more simple, BUT + // => local rebuild is way faster for spawn/despawn because we can + // simply rebuild a select NetworkIdentity only + // => having both .observers and .observing is necessary for local + // rebuilds + // + // in other words, this is the perfect solution even though it's not + // completely simple (due to .observers & .observing) + // + // Mirror maintains .observing automatically in the background. best of + // both worlds without any worrying now! + public static void RebuildObservers(NetworkIdentity identity, bool initialize) + { + // if there is no interest management system, + // or if 'force shown' then add all connections + if (aoi == null || identity.visibility == Visibility.ForceShown) + { + RebuildObserversDefault(identity, initialize); + } + // otherwise let interest management system rebuild + else + { + aoi.Rebuild(identity, initialize); + } + } + + + // broadcasting //////////////////////////////////////////////////////// + // helper function to get the right serialization for a connection + static NetworkWriter SerializeForConnection(NetworkIdentity identity, NetworkConnectionToClient connection) + { + // get serialization for this entity (cached) + // IMPORTANT: int tick avoids floating point inaccuracy over days/weeks + NetworkIdentitySerialization serialization = identity.GetServerSerializationAtTick(Time.frameCount); + + // is this entity owned by this connection? + bool owned = identity.connectionToClient == connection; + + // send serialized data + // owner writer if owned + if (owned) + { + // was it dirty / did we actually serialize anything? + if (serialization.ownerWriter.Position > 0) + return serialization.ownerWriter; + } + // observers writer if not owned + else + { + // was it dirty / did we actually serialize anything? + if (serialization.observersWriter.Position > 0) + return serialization.observersWriter; + } + + // nothing was serialized + return null; + } + + // helper function to broadcast the world to a connection + static void BroadcastToConnection(NetworkConnectionToClient connection) + { + // for each entity that this connection is seeing + foreach (NetworkIdentity identity in connection.observing) + { + // make sure it's not null or destroyed. + // (which can happen if someone uses + // GameObject.Destroy instead of + // NetworkServer.Destroy) + if (identity != null) + { + // get serialization for this entity viewed by this connection + // (if anything was serialized this time) + NetworkWriter serialization = SerializeForConnection(identity, connection); + if (serialization != null) + { + EntityStateMessage message = new EntityStateMessage + { + netId = identity.netId, + payload = serialization.ToArraySegment() + }; + connection.Send(message); + } + } + // spawned list should have no null entries because we + // always call Remove in OnObjectDestroy everywhere. + // if it does have null then someone used + // GameObject.Destroy instead of NetworkServer.Destroy. + else Debug.LogWarning($"Found 'null' entry in observing list for connectionId={connection.connectionId}. Please call NetworkServer.Destroy to destroy networked objects. Don't use GameObject.Destroy."); + } + } + + // helper function to check a connection for inactivity and disconnect if necessary + // returns true if disconnected + static bool DisconnectIfInactive(NetworkConnectionToClient connection) + { + // check for inactivity + if (disconnectInactiveConnections && + !connection.IsAlive(disconnectInactiveTimeout)) + { + Debug.LogWarning($"Disconnecting {connection} for inactivity!"); + connection.Disconnect(); + return true; + } + return false; + } + + // NetworkLateUpdate called after any Update/FixedUpdate/LateUpdate + // (we add this to the UnityEngine in NetworkLoop) + // internal for tests + internal static readonly List connectionsCopy = + new List(); + + static void Broadcast() + { + // copy all connections into a helper collection so that + // OnTransportDisconnected can be called while iterating. + // -> OnTransportDisconnected removes from the collection + // -> which would throw 'can't modify while iterating' errors + // => see also: https://github.com/vis2k/Mirror/issues/2739 + // (copy nonalloc) + // TODO remove this when we move to 'lite' transports with only + // socket send/recv later. + connectionsCopy.Clear(); + connections.Values.CopyTo(connectionsCopy); + + // go through all connections + foreach (NetworkConnectionToClient connection in connectionsCopy) + { + // check for inactivity. disconnects if necessary. + if (DisconnectIfInactive(connection)) + continue; + + // has this connection joined the world yet? + // for each READY connection: + // pull in UpdateVarsMessage for each entity it observes + if (connection.isReady) + { + // send time for snapshot interpolation every sendInterval. + // BroadcastToConnection() may not send if nothing is new. + // + // sent over unreliable. + // NetworkTime / Transform both use unreliable. + // + // make sure Broadcast() is only called every sendInterval, + // even if targetFrameRate isn't set in host mode (!) + // (done via AccurateInterval) + connection.Send(new TimeSnapshotMessage(), Channels.Unreliable); + + // broadcast world state to this connection + BroadcastToConnection(connection); + } + + // update connection to flush out batched messages + connection.Update(); + } + + // TODO this is way too slow because we iterate ALL spawned :/ + // TODO this is way too complicated :/ + // to understand what this tries to prevent, consider this example: + // monster has health=100 + // we change health=200, dirty bit is set + // player comes in range, gets full serialization spawn packet. + // next Broadcast(), player gets the health=200 change because dirty bit was set. + // + // this code clears all dirty bits if no players are around to prevent it. + // BUT there are two issues: + // 1. what if a playerB was around the whole time? + // 2. why don't we handle broadcast and spawn packets both HERE? + // handling spawn separately is why we need this complex magic + // + // see test: DirtyBitsAreClearedForSpawnedWithoutObservers() + // see test: SyncObjectChanges_DontGrowWithoutObservers() + // + // PAUL: we also do this to avoid ever growing SyncList .changes + //ClearSpawnedDirtyBits(); + // + // this was moved to NetworkIdentity.AddObserver! + // same result, but no more O(N) loop in here! + // TODO remove this comment after moving spawning into Broadcast()! + } + + // update ////////////////////////////////////////////////////////////// + // NetworkEarlyUpdate called before any Update/FixedUpdate + // (we add this to the UnityEngine in NetworkLoop) + internal static void NetworkEarlyUpdate() + { + // measure update time for profiling. + if (active) + { + earlyUpdateDuration.Begin(); + fullUpdateDuration.Begin(); + } + + // process all incoming messages first before updating the world + if (Transport.active != null) + Transport.active.ServerEarlyUpdate(); + + // step each connection's local time interpolation in early update. + foreach (NetworkConnectionToClient connection in connections.Values) + connection.UpdateTimeInterpolation(); + + if (active) earlyUpdateDuration.End(); + } + + internal static void NetworkLateUpdate() + { + if (active) + { + // measure update time for profiling. + lateUpdateDuration.Begin(); + + // only broadcast world if active + // broadcast every sendInterval. + // AccurateInterval to avoid update frequency inaccuracy issues: + // https://github.com/vis2k/Mirror/pull/3153 + // + // for example, host mode server doesn't set .targetFrameRate. + // Broadcast() would be called every tick. + // snapshots might be sent way too often, etc. + // + // during tests, we always call Broadcast() though. + // + // also important for syncInterval=0 components like + // NetworkTransform, so they can sync on same interval as time + // snapshots _but_ not every single tick. + // Unity 2019 doesn't have Time.timeAsDouble yet + if (!Application.isPlaying || AccurateInterval.Elapsed(NetworkTime.localTime, sendInterval, ref lastSendTime)) + Broadcast(); + } + + // process all outgoing messages after updating the world + // (even if not active. still want to process disconnects etc.) + if (Transport.active != null) + Transport.active.ServerLateUpdate(); + + // measure actual tick rate every second. + if (active) + { + ++actualTickRateCounter; + + // NetworkTime.localTime has defines for 2019 / 2020 compatibility + if (NetworkTime.localTime >= actualTickRateStart + 1) + { + // calculate avg by exact elapsed time. + // assuming 1s wouldn't be accurate, usually a few more ms passed. + float elapsed = (float)(NetworkTime.localTime - actualTickRateStart); + actualTickRate = Mathf.RoundToInt(actualTickRateCounter / elapsed); + actualTickRateStart = NetworkTime.localTime; + actualTickRateCounter = 0; + } + + // measure total update time. including transport. + // because in early update, transport update calls handlers. + lateUpdateDuration.End(); + fullUpdateDuration.End(); + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkServer.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkServer.cs.meta new file mode 100644 index 0000000000..6c7215f9f6 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkServer.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a5f5ec068f5604c32b160bc49ee97b75 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkServer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkStartPosition.cs b/Assets/ImportedAssets/Mirror/Core/NetworkStartPosition.cs new file mode 100644 index 0000000000..e11029be64 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkStartPosition.cs @@ -0,0 +1,21 @@ +using UnityEngine; + +namespace Mirror +{ + /// Start position for player spawning, automatically registers itself in the NetworkManager. + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Start Position")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-start-position")] + public class NetworkStartPosition : MonoBehaviour + { + public void Awake() + { + NetworkManager.RegisterStartPosition(transform); + } + + public void OnDestroy() + { + NetworkManager.UnRegisterStartPosition(transform); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkStartPosition.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkStartPosition.cs.meta new file mode 100644 index 0000000000..525cabb8f0 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkStartPosition.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 41f84591ce72545258ea98cb7518d8b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkStartPosition.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkTime.cs b/Assets/ImportedAssets/Mirror/Core/NetworkTime.cs new file mode 100644 index 0000000000..6319970c45 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkTime.cs @@ -0,0 +1,243 @@ +// NetworkTime now uses NetworkClient's snapshot interpolated timeline. +// this gives ideal results & ensures everything is on the same timeline. +// previously, NetworkTransforms were on separate timelines. +// +// however, some of the old NetworkTime code remains for ping time (rtt). +// some users may still be using that. +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +#if !UNITY_2020_3_OR_NEWER +using Stopwatch = System.Diagnostics.Stopwatch; +#endif + +namespace Mirror +{ + /// Synchronizes server time to clients. + public static class NetworkTime + { + /// Ping message interval, used to calculate latency / RTT and predicted time. + // 2s was enough to get a good average RTT. + // for prediction, we want to react to latency changes more rapidly. + const float DefaultPingInterval = 0.1f; // for resets + public static float PingInterval = DefaultPingInterval; + + /// Average out the last few results from Ping + // const because it's used immediately in _rtt constructor. + public const int PingWindowSize = 50; // average over 50 * 100ms = 5s + + static double lastPingTime; + + static ExponentialMovingAverage _rtt = new ExponentialMovingAverage(PingWindowSize); + + /// Returns double precision clock time _in this system_, unaffected by the network. +#if UNITY_2020_3_OR_NEWER + public static double localTime + { + // NetworkTime uses unscaled time and ignores Time.timeScale. + // fixes Time.timeScale getting server & client time out of sync: + // https://github.com/MirrorNetworking/Mirror/issues/3409 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Time.unscaledTimeAsDouble; + } +#else + // need stopwatch for older Unity versions, but it's quite slow. + // CAREFUL: unlike Time.time, the stopwatch time is not a FRAME time. + // it changes during the frame, so we have an extra step to "cache" it in EarlyUpdate. + static readonly Stopwatch stopwatch = new Stopwatch(); + static NetworkTime() => stopwatch.Start(); + static double localFrameTime; + public static double localTime => localFrameTime; +#endif + + /// The time in seconds since the server started. + // via global NetworkClient snapshot interpolated timeline (if client). + // on server, this is simply Time.timeAsDouble. + // + // I measured the accuracy of float and I got this: + // for the same day, accuracy is better than 1 ms + // after 1 day, accuracy goes down to 7 ms + // after 10 days, accuracy is 61 ms + // after 30 days , accuracy is 238 ms + // after 60 days, accuracy is 454 ms + // in other words, if the server is running for 2 months, + // and you cast down to float, then the time will jump in 0.4s intervals. + public static double time + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => NetworkServer.active + ? localTime + : NetworkClient.localTimeline; + } + + // prediction ////////////////////////////////////////////////////////// + // NetworkTime.time is server time, behind by bufferTime. + // for prediction, we want server time, ahead by latency. + // so that client inputs at predictedTime=2 arrive on server at time=2. + // the more accurate this is, the more closesly will corrections be + // be applied and the less jitter we will see. + // + // we'll use a two step process to calculate predicted time: + // 1. move snapshot interpolated time to server time, without being behind by bufferTime + // 2. constantly send this time to server (included in ping message) + // server replies with how far off it was. + // client averages that offset and applies it to predictedTime to get ever closer. + // + // this is also very easy to test & verify: + // - add LatencySimulation with 50ms latency + // - log predictionError on server in OnServerPing, see if it gets closer to 0 + // + // credits: FakeByte, imer, NinjaKickja, mischa + // const because it's used immediately in _predictionError constructor. + + static int PredictionErrorWindowSize = 20; // average over 20 * 100ms = 2s + static ExponentialMovingAverage _predictionErrorUnadjusted = new ExponentialMovingAverage(PredictionErrorWindowSize); + public static double predictionErrorUnadjusted => _predictionErrorUnadjusted.Value; + public static double predictionErrorAdjusted { get; private set; } // for debugging + + /// Predicted timeline in order for client inputs to be timestamped with the exact time when they will most likely arrive on the server. This is the basis for all prediction like PredictedRigidbody. + // on client, this is based on localTime (aka Time.time) instead of the snapshot interpolated timeline. + // this gives much better and immediately accurate results. + // -> snapshot interpolation timeline tries to emulate a server timeline without hard offset corrections. + // -> predictedTime does have hard offset corrections, so might as well use Time.time directly for this. + // + // note that predictedTime over unreliable is enough! + // even with reliable components, it gives better results than if we were + // to implemented predictedTime over reliable channel. + public static double predictedTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => NetworkServer.active + ? localTime // server always uses it's own timeline + : localTime + predictionErrorUnadjusted; // add the offset that the server told us we are off by + } + //////////////////////////////////////////////////////////////////////// + + /// Clock difference in seconds between the client and the server. Always 0 on server. + // original implementation used 'client - server' time. keep it this way. + // TODO obsolete later. people shouldn't worry about this. + public static double offset => localTime - time; + + /// Round trip time (in seconds) that it takes a message to go client->server->client. + public static double rtt => _rtt.Value; + + /// Round trip time variance aka jitter, in seconds. + // "rttVariance" instead of "rttVar" for consistency with older versions. + public static double rttVariance => _rtt.Variance; + + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod] + public static void ResetStatics() + { + PingInterval = DefaultPingInterval; + lastPingTime = 0; + _rtt = new ExponentialMovingAverage(PingWindowSize); +#if !UNITY_2020_3_OR_NEWER + stopwatch.Restart(); +#endif + } + + internal static void UpdateClient() + { + // localTime (double) instead of Time.time for accuracy over days + if (localTime >= lastPingTime + PingInterval) + SendPing(); + } + + // Separate method so we can call it from NetworkClient directly. + internal static void SendPing() + { + // send raw predicted time without the offset applied yet. + // we then apply the offset to it after. + NetworkPingMessage pingMessage = new NetworkPingMessage + ( + localTime, + predictedTime + ); + NetworkClient.Send(pingMessage, Channels.Unreliable); + lastPingTime = localTime; + } + + // client rtt calculation ////////////////////////////////////////////// + // executed at the server when we receive a ping message + // reply with a pong containing the time from the client + // and time from the server + internal static void OnServerPing(NetworkConnectionToClient conn, NetworkPingMessage message) + { + // calculate the prediction offset that the client needs to apply to unadjusted time to reach server time. + // this will be sent back to client for corrections. + double unadjustedError = localTime - message.localTime; + + // to see how well the client's final prediction worked, compare with adjusted time. + // this is purely for debugging. + // >0 means: server is ... seconds ahead of client's prediction (good if small) + // <0 means: server is ... seconds behind client's prediction. + // in other words, client is predicting too far ahead (not good) + double adjustedError = localTime - message.predictedTimeAdjusted; + // Debug.Log($"[Server] unadjustedError:{(unadjustedError*1000):F1}ms adjustedError:{(adjustedError*1000):F1}ms"); + + // Debug.Log($"OnServerPing conn:{conn}"); + NetworkPongMessage pongMessage = new NetworkPongMessage + ( + message.localTime, + unadjustedError, + adjustedError + ); + conn.Send(pongMessage, Channels.Unreliable); + } + + // Executed at the client when we receive a Pong message + // find out how long it took since we sent the Ping + // and update time offset & prediction offset. + internal static void OnClientPong(NetworkPongMessage message) + { + // prevent attackers from sending timestamps which are in the future + if (message.localTime > localTime) return; + + // how long did this message take to come back + double newRtt = localTime - message.localTime; + _rtt.Add(newRtt); + + // feed unadjusted prediction error into our exponential moving average + // store adjusted prediction error for debug / GUI purposes + _predictionErrorUnadjusted.Add(message.predictionErrorUnadjusted); + predictionErrorAdjusted = message.predictionErrorAdjusted; + // Debug.Log($"[Client] predictionError avg={(_predictionErrorUnadjusted.Value*1000):F1} ms"); + } + + // server rtt calculation ////////////////////////////////////////////// + // Executed at the client when we receive a ping message from the server. + // in other words, this is for server sided ping + rtt calculation. + // reply with a pong containing the time from the server + internal static void OnClientPing(NetworkPingMessage message) + { + // Debug.Log($"OnClientPing conn:{conn}"); + NetworkPongMessage pongMessage = new NetworkPongMessage + ( + message.localTime, + 0, 0 // server doesn't predict + ); + NetworkClient.Send(pongMessage, Channels.Unreliable); + } + + // Executed at the server when we receive a Pong message back. + // find out how long it took since we sent the Ping + // and update time offset + internal static void OnServerPong(NetworkConnectionToClient conn, NetworkPongMessage message) + { + // prevent attackers from sending timestamps which are in the future + if (message.localTime > localTime) return; + + // how long did this message take to come back + double newRtt = localTime - message.localTime; + conn._rtt.Add(newRtt); + } + + internal static void EarlyUpdate() + { +#if !UNITY_2020_3_OR_NEWER + localFrameTime = stopwatch.Elapsed.TotalSeconds; +#endif + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkTime.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkTime.cs.meta new file mode 100644 index 0000000000..3127e56b20 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkTime.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 09a0c241fc4a5496dbf4a0ab6e9a312c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkTime.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkWriter.cs b/Assets/ImportedAssets/Mirror/Core/NetworkWriter.cs new file mode 100644 index 0000000000..7ecf126435 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkWriter.cs @@ -0,0 +1,249 @@ +using System; +using System.Runtime.CompilerServices; +using System.Text; +using Unity.Collections.LowLevel.Unsafe; +using UnityEngine; + +namespace Mirror +{ + /// Network Writer for most simple types like floats, ints, buffers, structs, etc. Use NetworkWriterPool.GetReader() to avoid allocations. + public class NetworkWriter + { + // the limit of ushort is so we can write string size prefix as only 2 bytes. + // -1 so we can still encode 'null' into it too. + public const ushort MaxStringLength = ushort.MaxValue - 1; + + // create writer immediately with it's own buffer so no one can mess with it and so that we can resize it. + // note: BinaryWriter allocates too much, so we only use a MemoryStream + // => 1500 bytes by default because on average, most packets will be <= MTU + public const int DefaultCapacity = 1500; + internal byte[] buffer = new byte[DefaultCapacity]; + + /// Next position to write to the buffer + public int Position; + + /// Current capacity. Automatically resized if necessary. + public int Capacity => buffer.Length; + + // cache encoding for WriteString instead of creating it each time. + // 1000 readers before: 1MB GC, 30ms + // 1000 readers after: 0.8MB GC, 18ms + // not(!) static for thread safety. + // + // throwOnInvalidBytes is true. + // writer should throw and user should fix if this ever happens. + // unlike reader, which needs to expect it to happen from attackers. + internal readonly UTF8Encoding encoding = new UTF8Encoding(false, true); + + /// Reset both the position and length of the stream + // Leaves the capacity the same so that we can reuse this writer without + // extra allocations + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Reset() + { + Position = 0; + } + + // NOTE that our runtime resizing comes at no extra cost because: + // 1. 'has space' checks are necessary even for fixed sized writers. + // 2. all writers will eventually be large enough to stop resizing. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void EnsureCapacity(int value) + { + if (buffer.Length < value) + { + int capacity = Math.Max(value, buffer.Length * 2); + Array.Resize(ref buffer, capacity); + } + } + + /// Copies buffer until 'Position' to a new array. + // Try to use ToArraySegment instead to avoid allocations! + public byte[] ToArray() + { + byte[] data = new byte[Position]; + Array.ConstrainedCopy(buffer, 0, data, 0, Position); + return data; + } + + /// Returns allocation-free ArraySegment until 'Position'. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ArraySegment ToArraySegment() => + new ArraySegment(buffer, 0, Position); + + // implicit conversion for convenience + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ArraySegment(NetworkWriter w) => + w.ToArraySegment(); + + // WriteBlittable from DOTSNET. + // this is extremely fast, but only works for blittable types. + // + // Benchmark: + // WriteQuaternion x 100k, Macbook Pro 2015 @ 2.2Ghz, Unity 2018 LTS (debug mode) + // + // | Median | Min | Max | Avg | Std | (ms) + // before | 30.35 | 29.86 | 48.99 | 32.54 | 4.93 | + // blittable* | 5.69 | 5.52 | 27.51 | 7.78 | 5.65 | + // + // * without IsBlittable check + // => 4-6x faster! + // + // WriteQuaternion x 100k, Macbook Pro 2015 @ 2.2Ghz, Unity 2020.1 (release mode) + // + // | Median | Min | Max | Avg | Std | (ms) + // before | 9.41 | 8.90 | 23.02 | 10.72 | 3.07 | + // blittable* | 1.48 | 1.40 | 16.03 | 2.60 | 2.71 | + // + // * without IsBlittable check + // => 6x faster! + // + // Note: + // WriteBlittable assumes same endianness for server & client. + // All Unity 2018+ platforms are little endian. + // => run NetworkWriterTests.BlittableOnThisPlatform() to verify! + // + // This is not safe to expose to random structs. + // * StructLayout.Sequential is the default, which is safe. + // if the struct contains a reference type, it is converted to Auto. + // but since all structs here are unmanaged blittable, it's safe. + // see also: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.layoutkind?view=netframework-4.8#system-runtime-interopservices-layoutkind-sequential + // * StructLayout.Pack depends on CPU word size. + // this may be different 4 or 8 on some ARM systems, etc. + // this is not safe, and would cause bytes/shorts etc. to be padded. + // see also: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.structlayoutattribute.pack?view=net-6.0 + // * If we force pack all to '1', they would have no padding which is + // great for bandwidth. but on some android systems, CPU can't read + // unaligned memory. + // see also: https://github.com/vis2k/Mirror/issues/3044 + // * The only option would be to force explicit layout with multiples + // of word size. but this requires lots of weaver checking and is + // still questionable (IL2CPP etc.). + // + // Note: inlining WriteBlittable is enough. don't inline WriteInt etc. + // we don't want WriteBlittable to be copied in place everywhere. + internal unsafe void WriteBlittable(T value) + where T : unmanaged + { + // check if blittable for safety +#if UNITY_EDITOR + if (!UnsafeUtility.IsBlittable(typeof(T))) + { + Debug.LogError($"{typeof(T)} is not blittable!"); + return; + } +#endif + // calculate size + // sizeof(T) gets the managed size at compile time. + // Marshal.SizeOf gets the unmanaged size at runtime (slow). + // => our 1mio writes benchmark is 6x slower with Marshal.SizeOf + // => for blittable types, sizeof(T) is even recommended: + // https://docs.microsoft.com/en-us/dotnet/standard/native-interop/best-practices + int size = sizeof(T); + + // ensure capacity + // NOTE that our runtime resizing comes at no extra cost because: + // 1. 'has space' checks are necessary even for fixed sized writers. + // 2. all writers will eventually be large enough to stop resizing. + EnsureCapacity(Position + size); + + // write blittable + fixed (byte* ptr = &buffer[Position]) + { +#if UNITY_ANDROID + // on some android systems, assigning *(T*)ptr throws a NRE if + // the ptr isn't aligned (i.e. if Position is 1,2,3,5, etc.). + // here we have to use memcpy. + // + // => we can't get a pointer of a struct in C# without + // marshalling allocations + // => instead, we stack allocate an array of type T and use that + // => stackalloc avoids GC and is very fast. it only works for + // value types, but all blittable types are anyway. + // + // this way, we can still support blittable reads on android. + // see also: https://github.com/vis2k/Mirror/issues/3044 + // (solution discovered by AIIO, FakeByte, mischa) + T* valueBuffer = stackalloc T[1]{value}; + UnsafeUtility.MemCpy(ptr, valueBuffer, size); +#else + // cast buffer to T* pointer, then assign value to the area + *(T*)ptr = value; +#endif + } + Position += size; + } + + // blittable'?' template for code reuse + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void WriteBlittableNullable(T? value) + where T : unmanaged + { + // bool isn't blittable. write as byte. + WriteByte((byte)(value.HasValue ? 0x01 : 0x00)); + + // only write value if exists. saves bandwidth. + if (value.HasValue) + WriteBlittable(value.Value); + } + + public void WriteByte(byte value) => WriteBlittable(value); + + // for byte arrays with consistent size, where the reader knows how many to read + // (like a packet opcode that's always the same) + public void WriteBytes(byte[] array, int offset, int count) + { + EnsureCapacity(Position + count); + Array.ConstrainedCopy(array, offset, this.buffer, Position, count); + Position += count; + } + // write an unsafe byte* array. + // useful for bit tree compression, etc. + public unsafe bool WriteBytes(byte* ptr, int offset, int size) + { + EnsureCapacity(Position + size); + + fixed (byte* destination = &buffer[Position]) + { + // write 'size' bytes at position + // 10 mio writes: 868ms + // Array.Copy(value.Array, value.Offset, buffer, Position, value.Count); + // 10 mio writes: 775ms + // Buffer.BlockCopy(value.Array, value.Offset, buffer, Position, value.Count); + // 10 mio writes: 637ms + UnsafeUtility.MemCpy(destination, ptr + offset, size); + } + + Position += size; + return true; + } + + /// Writes any type that mirror supports. Uses weaver populated Writer(T).write. + public void Write(T value) + { + Action writeDelegate = Writer.write; + if (writeDelegate == null) + { + Debug.LogError($"No writer found for {typeof(T)}. This happens either if you are missing a NetworkWriter extension for your custom type, or if weaving failed. Try to reimport a script to weave again."); + } + else + { + writeDelegate(this, value); + } + } + + // print with buffer content for easier debugging. + // [content, position / capacity]. + // showing "position / space" would be too confusing. + public override string ToString() => + $"[{ToArraySegment().ToHexString()} @ {Position}/{Capacity}]"; + } + + /// Helper class that weaver populates with all writer types. + // Note that c# creates a different static variable for each type + // -> Weaver.ReaderWriterProcessor.InitializeReaderAndWriters() populates it + public static class Writer + { + public static Action write; + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkWriter.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkWriter.cs.meta new file mode 100644 index 0000000000..c936a5fd82 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkWriter.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 48d2207bcef1f4477b624725f075f9bd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkWriter.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkWriterExtensions.cs b/Assets/ImportedAssets/Mirror/Core/NetworkWriterExtensions.cs new file mode 100644 index 0000000000..fef9f613af --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkWriterExtensions.cs @@ -0,0 +1,430 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // Mirror's Weaver automatically detects all NetworkWriter function types, + // but they do all need to be extensions. + public static class NetworkWriterExtensions + { + public static void WriteByte(this NetworkWriter writer, byte value) => writer.WriteBlittable(value); + public static void WriteByteNullable(this NetworkWriter writer, byte? value) => writer.WriteBlittableNullable(value); + + public static void WriteSByte(this NetworkWriter writer, sbyte value) => writer.WriteBlittable(value); + public static void WriteSByteNullable(this NetworkWriter writer, sbyte? value) => writer.WriteBlittableNullable(value); + + // char is not blittable. convert to ushort. + public static void WriteChar(this NetworkWriter writer, char value) => writer.WriteBlittable((ushort)value); + public static void WriteCharNullable(this NetworkWriter writer, char? value) => writer.WriteBlittableNullable((ushort?)value); + + // bool is not blittable. convert to byte. + public static void WriteBool(this NetworkWriter writer, bool value) => writer.WriteBlittable((byte)(value ? 1 : 0)); + public static void WriteBoolNullable(this NetworkWriter writer, bool? value) => writer.WriteBlittableNullable(value.HasValue ? ((byte)(value.Value ? 1 : 0)) : new byte?()); + + public static void WriteShort(this NetworkWriter writer, short value) => writer.WriteBlittable(value); + public static void WriteShortNullable(this NetworkWriter writer, short? value) => writer.WriteBlittableNullable(value); + + public static void WriteUShort(this NetworkWriter writer, ushort value) => writer.WriteBlittable(value); + public static void WriteUShortNullable(this NetworkWriter writer, ushort? value) => writer.WriteBlittableNullable(value); + + public static void WriteInt(this NetworkWriter writer, int value) => writer.WriteBlittable(value); + public static void WriteIntNullable(this NetworkWriter writer, int? value) => writer.WriteBlittableNullable(value); + + public static void WriteUInt(this NetworkWriter writer, uint value) => writer.WriteBlittable(value); + public static void WriteUIntNullable(this NetworkWriter writer, uint? value) => writer.WriteBlittableNullable(value); + + public static void WriteLong(this NetworkWriter writer, long value) => writer.WriteBlittable(value); + public static void WriteLongNullable(this NetworkWriter writer, long? value) => writer.WriteBlittableNullable(value); + + public static void WriteULong(this NetworkWriter writer, ulong value) => writer.WriteBlittable(value); + public static void WriteULongNullable(this NetworkWriter writer, ulong? value) => writer.WriteBlittableNullable(value); + + public static void WriteFloat(this NetworkWriter writer, float value) => writer.WriteBlittable(value); + public static void WriteFloatNullable(this NetworkWriter writer, float? value) => writer.WriteBlittableNullable(value); + + public static void WriteDouble(this NetworkWriter writer, double value) => writer.WriteBlittable(value); + public static void WriteDoubleNullable(this NetworkWriter writer, double? value) => writer.WriteBlittableNullable(value); + + public static void WriteDecimal(this NetworkWriter writer, decimal value) => writer.WriteBlittable(value); + public static void WriteDecimalNullable(this NetworkWriter writer, decimal? value) => writer.WriteBlittableNullable(value); + + public static void WriteString(this NetworkWriter writer, string value) + { + // write 0 for null support, increment real size by 1 + // (note: original HLAPI would write "" for null strings, but if a + // string is null on the server then it should also be null + // on the client) + if (value == null) + { + writer.WriteUShort(0); + return; + } + + // WriteString copies into the buffer manually. + // need to ensure capacity here first, manually. + int maxSize = writer.encoding.GetMaxByteCount(value.Length); + writer.EnsureCapacity(writer.Position + 2 + maxSize); // 2 bytes position + N bytes encoding + + // encode it into the buffer first. + // reserve 2 bytes for header after we know how much was written. + int written = writer.encoding.GetBytes(value, 0, value.Length, writer.buffer, writer.Position + 2); + + // check if within max size, otherwise Reader can't read it. + if (written > NetworkWriter.MaxStringLength) + throw new IndexOutOfRangeException($"NetworkWriter.WriteString - Value too long: {written} bytes. Limit: {NetworkWriter.MaxStringLength} bytes"); + + // .Position is unchanged, so fill in the size header now. + // we already ensured that max size fits into ushort.max-1. + writer.WriteUShort(checked((ushort)(written + 1))); // Position += 2 + + // now update position by what was written above + writer.Position += written; + } + + // Weaver needs a write function with just one byte[] parameter + // (we don't name it .Write(byte[]) because it's really a WriteBytesAndSize since we write size / null info too) + public static void WriteBytesAndSize(this NetworkWriter writer, byte[] buffer) + { + // buffer might be null, so we can't use .Length in that case + writer.WriteBytesAndSize(buffer, 0, buffer != null ? buffer.Length : 0); + } + + // for byte arrays with dynamic size, where the reader doesn't know how many will come + // (like an inventory with different items etc.) + public static void WriteBytesAndSize(this NetworkWriter writer, byte[] buffer, int offset, int count) + { + // null is supported because [SyncVar]s might be structs with null byte[] arrays + // write 0 for null array, increment normal size by 1 to save bandwidth + // (using size=-1 for null would limit max size to 32kb instead of 64kb) + if (buffer == null) + { + writer.WriteUInt(0u); + return; + } + writer.WriteUInt(checked((uint)count) + 1u); + writer.WriteBytes(buffer, offset, count); + } + + // writes ArraySegment of byte (most common type) and size header + public static void WriteArraySegmentAndSize(this NetworkWriter writer, ArraySegment segment) + { + writer.WriteBytesAndSize(segment.Array, segment.Offset, segment.Count); + } + + // writes ArraySegment of any type, and size header + public static void WriteArraySegment(this NetworkWriter writer, ArraySegment segment) + { + int length = segment.Count; + writer.WriteInt(length); + for (int i = 0; i < length; i++) + { + writer.Write(segment.Array[segment.Offset + i]); + } + } + + public static void WriteVector2(this NetworkWriter writer, Vector2 value) => writer.WriteBlittable(value); + public static void WriteVector2Nullable(this NetworkWriter writer, Vector2? value) => writer.WriteBlittableNullable(value); + + public static void WriteVector3(this NetworkWriter writer, Vector3 value) => writer.WriteBlittable(value); + public static void WriteVector3Nullable(this NetworkWriter writer, Vector3? value) => writer.WriteBlittableNullable(value); + + public static void WriteVector4(this NetworkWriter writer, Vector4 value) => writer.WriteBlittable(value); + public static void WriteVector4Nullable(this NetworkWriter writer, Vector4? value) => writer.WriteBlittableNullable(value); + + public static void WriteVector2Int(this NetworkWriter writer, Vector2Int value) => writer.WriteBlittable(value); + public static void WriteVector2IntNullable(this NetworkWriter writer, Vector2Int? value) => writer.WriteBlittableNullable(value); + + public static void WriteVector3Int(this NetworkWriter writer, Vector3Int value) => writer.WriteBlittable(value); + public static void WriteVector3IntNullable(this NetworkWriter writer, Vector3Int? value) => writer.WriteBlittableNullable(value); + + public static void WriteColor(this NetworkWriter writer, Color value) => writer.WriteBlittable(value); + public static void WriteColorNullable(this NetworkWriter writer, Color? value) => writer.WriteBlittableNullable(value); + + public static void WriteColor32(this NetworkWriter writer, Color32 value) => writer.WriteBlittable(value); + public static void WriteColor32Nullable(this NetworkWriter writer, Color32? value) => writer.WriteBlittableNullable(value); + + public static void WriteQuaternion(this NetworkWriter writer, Quaternion value) => writer.WriteBlittable(value); + public static void WriteQuaternionNullable(this NetworkWriter writer, Quaternion? value) => writer.WriteBlittableNullable(value); + + // Rect is a struct with properties instead of fields + public static void WriteRect(this NetworkWriter writer, Rect value) + { + writer.WriteVector2(value.position); + writer.WriteVector2(value.size); + } + public static void WriteRectNullable(this NetworkWriter writer, Rect? value) + { + writer.WriteBool(value.HasValue); + if (value.HasValue) + writer.WriteRect(value.Value); + } + + // Plane is a struct with properties instead of fields + public static void WritePlane(this NetworkWriter writer, Plane value) + { + writer.WriteVector3(value.normal); + writer.WriteFloat(value.distance); + } + public static void WritePlaneNullable(this NetworkWriter writer, Plane? value) + { + writer.WriteBool(value.HasValue); + if (value.HasValue) + writer.WritePlane(value.Value); + } + + // Ray is a struct with properties instead of fields + public static void WriteRay(this NetworkWriter writer, Ray value) + { + writer.WriteVector3(value.origin); + writer.WriteVector3(value.direction); + } + public static void WriteRayNullable(this NetworkWriter writer, Ray? value) + { + writer.WriteBool(value.HasValue); + if (value.HasValue) + writer.WriteRay(value.Value); + } + + // LayerMask is a struct with properties instead of fields + public static void WriteLayerMask(this NetworkWriter writer, LayerMask layerMask) + { + // 32 layers as a flags enum, max value of 496, we only need a UShort. + writer.WriteUShort((ushort)layerMask.value); + } + public static void WriteLayerMaskNullable(this NetworkWriter writer, LayerMask? layerMask) + { + writer.WriteBool(layerMask.HasValue); + if (layerMask.HasValue) + writer.WriteLayerMask(layerMask.Value); + } + + public static void WriteMatrix4x4(this NetworkWriter writer, Matrix4x4 value) => writer.WriteBlittable(value); + public static void WriteMatrix4x4Nullable(this NetworkWriter writer, Matrix4x4? value) => writer.WriteBlittableNullable(value); + + public static void WriteGuid(this NetworkWriter writer, Guid value) + { +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have Span yet + byte[] data = value.ToByteArray(); + writer.WriteBytes(data, 0, data.Length); +#else + // WriteBlittable(Guid) isn't safe. see WriteBlittable comments. + // Guid is Sequential, but we can't guarantee packing. + // TryWriteBytes is safe and allocation free. + writer.EnsureCapacity(writer.Position + 16); + value.TryWriteBytes(new Span(writer.buffer, writer.Position, 16)); + writer.Position += 16; +#endif + } + public static void WriteGuidNullable(this NetworkWriter writer, Guid? value) + { + writer.WriteBool(value.HasValue); + if (value.HasValue) + writer.WriteGuid(value.Value); + } + + public static void WriteNetworkIdentity(this NetworkWriter writer, NetworkIdentity value) + { + if (value == null) + { + writer.WriteUInt(0); + return; + } + + // users might try to use unspawned / prefab GameObjects in + // rpcs/cmds/syncvars/messages. they would be null on the other + // end, and it might not be obvious why. let's make it obvious. + // https://github.com/vis2k/Mirror/issues/2060 + // + // => warning (instead of exception) because we also use a warning + // if a GameObject doesn't have a NetworkIdentity component etc. + if (value.netId == 0) + Debug.LogWarning($"Attempted to serialize unspawned GameObject: {value.name}. Prefabs and unspawned GameObjects would always be null on the other side. Please spawn it before using it in [SyncVar]s/Rpcs/Cmds/NetworkMessages etc."); + + writer.WriteUInt(value.netId); + } + + public static void WriteNetworkBehaviour(this NetworkWriter writer, NetworkBehaviour value) + { + if (value == null) + { + writer.WriteUInt(0); + return; + } + + // users might try to use unspawned / prefab NetworkBehaviours in + // rpcs/cmds/syncvars/messages. they would be null on the other + // end, and it might not be obvious why. let's make it obvious. + // https://github.com/vis2k/Mirror/issues/2060 + // and more recently https://github.com/MirrorNetworking/Mirror/issues/3399 + // + // => warning (instead of exception) because we also use a warning + // when writing an unspawned NetworkIdentity + if (value.netId == 0) + { + Debug.LogWarning($"Attempted to serialize unspawned NetworkBehaviour: of type {value.GetType()} on GameObject {value.name}. Prefabs and unspawned GameObjects would always be null on the other side. Please spawn it before using it in [SyncVar]s/Rpcs/Cmds/NetworkMessages etc."); + writer.WriteUInt(0); + return; + } + + writer.WriteUInt(value.netId); + writer.WriteByte(value.ComponentIndex); + } + + public static void WriteTransform(this NetworkWriter writer, Transform value) + { + if (value == null) + { + writer.WriteUInt(0); + return; + } + if (value.TryGetComponent(out NetworkIdentity identity)) + { + writer.WriteUInt(identity.netId); + } + else + { + // if users attempt to pass a transform without NetworkIdentity + // to a [Command] or [SyncVar], it should show an obvious warning. + Debug.LogWarning($"Attempted to sync a Transform ({value}) which isn't networked. Transforms without a NetworkIdentity component can't be synced."); + writer.WriteUInt(0); + } + } + + public static void WriteGameObject(this NetworkWriter writer, GameObject value) + { + if (value == null) + { + writer.WriteUInt(0); + return; + } + + // warn if the GameObject doesn't have a NetworkIdentity, + if (!value.TryGetComponent(out NetworkIdentity identity)) + Debug.LogWarning($"Attempted to sync a GameObject ({value}) which isn't networked. GameObject without a NetworkIdentity component can't be synced."); + + // serialize the correct amount of data in any case to make sure + // that the other end can read the expected amount of data too. + writer.WriteNetworkIdentity(identity); + } + + // while SyncList is recommended for NetworkBehaviours, + // structs may have .List members which weaver needs to be able to + // fully serialize for NetworkMessages etc. + // note that Weaver/Writers/GenerateWriter() handles this manually. + public static void WriteList(this NetworkWriter writer, List list) + { + // 'null' is encoded as '-1' + if (list is null) + { + writer.WriteInt(-1); + return; + } + + // check if within max size, otherwise Reader can't read it. + if (list.Count > NetworkReader.AllocationLimit) + throw new IndexOutOfRangeException($"NetworkWriter.WriteList - List<{typeof(T)}> too big: {list.Count} elements. Limit: {NetworkReader.AllocationLimit}"); + + writer.WriteInt(list.Count); + for (int i = 0; i < list.Count; i++) + writer.Write(list[i]); + } + + // while SyncSet is recommended for NetworkBehaviours, + // structs may have .Set members which weaver needs to be able to + // fully serialize for NetworkMessages etc. + // note that Weaver/Writers/GenerateWriter() handles this manually. + // TODO writer not found. need to adjust weaver first. see tests. + /* + public static void WriteHashSet(this NetworkWriter writer, HashSet hashSet) + { + if (hashSet is null) + { + writer.WriteInt(-1); + return; + } + writer.WriteInt(hashSet.Count); + foreach (T item in hashSet) + writer.Write(item); + } + */ + + public static void WriteArray(this NetworkWriter writer, T[] array) + { + // 'null' is encoded as '-1' + if (array is null) + { + writer.WriteInt(-1); + return; + } + + // check if within max size, otherwise Reader can't read it. + if (array.Length > NetworkReader.AllocationLimit) + throw new IndexOutOfRangeException($"NetworkWriter.WriteArray - Array<{typeof(T)}> too big: {array.Length} elements. Limit: {NetworkReader.AllocationLimit}"); + + writer.WriteInt(array.Length); + for (int i = 0; i < array.Length; i++) + writer.Write(array[i]); + } + + public static void WriteUri(this NetworkWriter writer, Uri uri) + { + writer.WriteString(uri?.ToString()); + } + + public static void WriteTexture2D(this NetworkWriter writer, Texture2D texture2D) + { + // TODO allocation protection when sending textures to server. + // currently can allocate 32k x 32k x 4 byte = 3.8 GB + + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 + // simply send -1 for width. + if (texture2D == null) + { + writer.WriteShort(-1); + return; + } + + // check if within max size, otherwise Reader can't read it. + int totalSize = texture2D.width * texture2D.height; + if (totalSize > NetworkReader.AllocationLimit) + throw new IndexOutOfRangeException($"NetworkWriter.WriteTexture2D - Texture2D total size (width*height) too big: {totalSize}. Limit: {NetworkReader.AllocationLimit}"); + + // write dimensions first so reader can create the texture with size + // 32k x 32k short is more than enough + writer.WriteShort((short)texture2D.width); + writer.WriteShort((short)texture2D.height); + writer.WriteArray(texture2D.GetPixels32()); + } + + public static void WriteSprite(this NetworkWriter writer, Sprite sprite) + { + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 + // simply send a 'null' for texture content. + if (sprite == null) + { + writer.WriteTexture2D(null); + return; + } + + writer.WriteTexture2D(sprite.texture); + writer.WriteRect(sprite.rect); + writer.WriteVector2(sprite.pivot); + } + + public static void WriteDateTime(this NetworkWriter writer, DateTime dateTime) + { + writer.WriteDouble(dateTime.ToOADate()); + } + + public static void WriteDateTimeNullable(this NetworkWriter writer, DateTime? dateTime) + { + writer.WriteBool(dateTime.HasValue); + if (dateTime.HasValue) + writer.WriteDouble(dateTime.Value.ToOADate()); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkWriterExtensions.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkWriterExtensions.cs.meta new file mode 100644 index 0000000000..2610a096c7 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkWriterExtensions.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 94259792df2a404892c3e2377f58d0cb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkWriterExtensions.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkWriterPool.cs b/Assets/ImportedAssets/Mirror/Core/NetworkWriterPool.cs new file mode 100644 index 0000000000..23f60269f1 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkWriterPool.cs @@ -0,0 +1,40 @@ +// API consistent with Microsoft's ObjectPool. +using System.Runtime.CompilerServices; + +namespace Mirror +{ + /// Pool of NetworkWriters to avoid allocations. + public static class NetworkWriterPool + { + // reuse Pool + // we still wrap it in NetworkWriterPool.Get/Recycle so we can reset the + // position before reusing. + // this is also more consistent with NetworkReaderPool where we need to + // assign the internal buffer before reusing. + static readonly Pool Pool = new Pool( + () => new NetworkWriterPooled(), + // initial capacity to avoid allocations in the first few frames + // 1000 * 1200 bytes = around 1 MB. + 1000 + ); + + // expose count for testing + public static int Count => Pool.Count; + + /// Get a writer from the pool. Creates new one if pool is empty. + public static NetworkWriterPooled Get() + { + // grab from pool & reset position + NetworkWriterPooled writer = Pool.Get(); + writer.Reset(); + return writer; + } + + /// Return a writer to the pool. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Return(NetworkWriterPooled writer) + { + Pool.Return(writer); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkWriterPool.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkWriterPool.cs.meta new file mode 100644 index 0000000000..e287f31913 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkWriterPool.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 3f34b53bea38e4f259eb8dc211e4fdb6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkWriterPool.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkWriterPooled.cs b/Assets/ImportedAssets/Mirror/Core/NetworkWriterPooled.cs new file mode 100644 index 0000000000..5ac371db8c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkWriterPooled.cs @@ -0,0 +1,13 @@ +// "NetworkWriterPooled" instead of "PooledNetworkWriter" to group files, for +// easier IDE workflow and more elegant code. +using System; + +namespace Mirror +{ + /// Pooled NetworkWriter, automatically returned to pool when using 'using' + // TODO make sealed again after removing obsolete NetworkWriterPooled! + public class NetworkWriterPooled : NetworkWriter, IDisposable + { + public void Dispose() => NetworkWriterPool.Return(this); + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/NetworkWriterPooled.cs.meta b/Assets/ImportedAssets/Mirror/Core/NetworkWriterPooled.cs.meta new file mode 100644 index 0000000000..cddb14112c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/NetworkWriterPooled.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a9fab936bf3c4716a452d94ad5ecbebe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/NetworkWriterPooled.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/PortTransport.cs b/Assets/ImportedAssets/Mirror/Core/PortTransport.cs new file mode 100644 index 0000000000..19a7dfd43b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/PortTransport.cs @@ -0,0 +1,13 @@ +// convenience interface for transports which use a port. +// useful for cases where someone wants to 'just set the port' independent of +// which transport it is. +// +// note that not all transports have ports, but most do. + +namespace Mirror +{ + public interface PortTransport + { + ushort Port { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/PortTransport.cs.meta b/Assets/ImportedAssets/Mirror/Core/PortTransport.cs.meta new file mode 100644 index 0000000000..51d0d27a05 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/PortTransport.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: f7c7c2820d7974cb28c7bfe9aae890a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/PortTransport.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Prediction.meta b/Assets/ImportedAssets/Mirror/Core/Prediction.meta new file mode 100644 index 0000000000..83fb83bb40 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Prediction.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7e8e801f9c7f4b858d9a6c162e64ca84 +timeCreated: 1694005962 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Core/Prediction/Prediction.cs b/Assets/ImportedAssets/Mirror/Core/Prediction/Prediction.cs new file mode 100644 index 0000000000..d66994527d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Prediction/Prediction.cs @@ -0,0 +1,195 @@ +// standalone, easy to test algorithms for prediction +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // prediction may capture Rigidbody3D/2D/etc. state + // have a common interface. + public interface PredictedState + { + double timestamp { get; } + + // use Vector3 for both Rigidbody3D and Rigidbody2D, that's fine + Vector3 position { get; set; } + Vector3 positionDelta { get; set; } + + Quaternion rotation { get; set; } + Quaternion rotationDelta { get; set; } + + Vector3 velocity { get; set; } + Vector3 velocityDelta { get; set; } + + Vector3 angularVelocity { get; set; } + Vector3 angularVelocityDelta { get; set; } + } + + public static class Prediction + { + // get the two states closest to a given timestamp. + // those can be used to interpolate the exact state at that time. + // => RingBuffer: see prediction_ringbuffer_2 branch, but it's slower! + public static bool Sample( + SortedList history, + double timestamp, // current server time + out T before, + out T after, + out int afterIndex, + out double t) // interpolation factor + { + before = default; + after = default; + t = 0; + afterIndex = -1; + + // can't sample an empty history + // interpolation needs at least two entries. + // can't Lerp(A, A, 1.5). dist(A, A) * 1.5 is always 0. + if (history.Count < 2) { + return false; + } + + // older than oldest + if (timestamp < history.Keys[0]) { + return false; + } + + // iterate through the history + // TODO this needs to be faster than O(N) + // search around that area. + // should be O(1) most of the time, unless sampling was off. + int index = 0; // manually count when iterating. easier than for-int loop. + KeyValuePair prev = new KeyValuePair(); + + // SortedList foreach iteration allocates a LOT. use for-int instead. + // foreach (KeyValuePair entry in history) { + for (int i = 0; i < history.Count; ++i) + { + double key = history.Keys[i]; + T value = history.Values[i]; + + // exact match? + if (timestamp == key) + { + before = value; + after = value; + afterIndex = index; + t = Mathd.InverseLerp(key, key, timestamp); + return true; + } + + // did we check beyond timestamp? then return the previous two. + if (key > timestamp) + { + before = prev.Value; + after = value; + afterIndex = index; + t = Mathd.InverseLerp(prev.Key, key, timestamp); + return true; + } + + // remember the last + prev = new KeyValuePair(key, value); + index += 1; + } + + return false; + } + + // inserts a server state into the client's history. + // readjust the deltas of the states after the inserted one. + // returns the corrected final position. + // => RingBuffer: see prediction_ringbuffer_2 branch, but it's slower! + public static T CorrectHistory( + SortedList history, + int stateHistoryLimit, + T corrected, // corrected state with timestamp + T before, // state in history before the correction + T after, // state in history after the correction + int afterIndex) // index of the 'after' value so we don't need to find it again here + where T: PredictedState + { + // respect the limit + // TODO unit test to check if it respects max size + if (history.Count >= stateHistoryLimit) + { + history.RemoveAt(0); + afterIndex -= 1; // we removed the first value so all indices are off by one now + } + + // PERFORMANCE OPTIMIZATION: avoid O(N) insertion, only readjust all values after. + // the end result is the same since after.delta and after.position are both recalculated. + // it's technically not correct if we were to reconstruct final position from 0..after..end but + // we never do, we only ever iterate from after..end! + // + // insert the corrected state into the history, or overwrite if already exists + // SortedList insertions are O(N)! + // history[corrected.timestamp] = corrected; + // afterIndex += 1; // we inserted the corrected value before the previous index + + // the entry behind the inserted one still has the delta from (before, after). + // we need to correct it to (corrected, after). + // + // for example: + // before: (t=1.0, delta=10, position=10) + // after: (t=3.0, delta=20, position=30) + // + // then we insert: + // corrected: (t=2.5, delta=__, position=25) + // + // previous delta was from t=1.0 to t=3.0 => 2.0 + // inserted delta is from t=2.5 to t=3.0 => 0.5 + // multiplier is 0.5 / 2.0 = 0.25 + // multiply 'after.delta(20)' by 0.25 to get the new 'after.delta(5) + // + // so the new history is: + // before: (t=1.0, delta=10, position=10) + // corrected: (t=2.5, delta=__, position=25) + // after: (t=3.0, delta= 5, position=__) + // + // so when we apply the correction, the new after.position would be: + // corrected.position(25) + after.delta(5) = 30 + // + double previousDeltaTime = after.timestamp - before.timestamp; // 3.0 - 1.0 = 2.0 + double correctedDeltaTime = after.timestamp - corrected.timestamp; // 3.0 - 2.5 = 0.5 + + // fix multiplier becoming NaN if previousDeltaTime is 0: + // double multiplier = correctedDeltaTime / previousDeltaTime; + double multiplier = previousDeltaTime != 0 ? correctedDeltaTime / previousDeltaTime : 0; // 0.5 / 2.0 = 0.25 + + // recalculate 'after.delta' with the multiplier + after.positionDelta = Vector3.Lerp(Vector3.zero, after.positionDelta, (float)multiplier); + after.velocityDelta = Vector3.Lerp(Vector3.zero, after.velocityDelta, (float)multiplier); + after.angularVelocityDelta = Vector3.Lerp(Vector3.zero, after.angularVelocityDelta, (float)multiplier); + // Quaternions always need to be normalized in order to be a valid rotation after operations + after.rotationDelta = Quaternion.Slerp(Quaternion.identity, after.rotationDelta, (float)multiplier).normalized; + + // changes aren't saved until we overwrite them in the history + history[after.timestamp] = after; + + // second step: readjust all absolute values by rewinding client's delta moves on top of it. + T last = corrected; + for (int i = afterIndex; i < history.Count; ++i) + { + double key = history.Keys[i]; + T value = history.Values[i]; + + // correct absolute position based on last + delta. + value.position = last.position + value.positionDelta; + value.velocity = last.velocity + value.velocityDelta; + value.angularVelocity = last.angularVelocity + value.angularVelocityDelta; + // Quaternions always need to be normalized in order to be a valid rotation after operations + value.rotation = (value.rotationDelta * last.rotation).normalized; // quaternions add delta by multiplying in this order + + // save the corrected entry into history. + history[key] = value; + + // save last + last = value; + } + + // third step: return the final recomputed state. + return last; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Prediction/Prediction.cs.meta b/Assets/ImportedAssets/Mirror/Core/Prediction/Prediction.cs.meta new file mode 100644 index 0000000000..c8eb081bdf --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Prediction/Prediction.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 216d494d910445ea8a7acc7c889212d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Prediction/Prediction.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/RemoteCalls.cs b/Assets/ImportedAssets/Mirror/Core/RemoteCalls.cs new file mode 100644 index 0000000000..5dbe52f640 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/RemoteCalls.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror.RemoteCalls +{ + // invoke type for Cmd/Rpc + public enum RemoteCallType { Command, ClientRpc } + + // remote call function delegate + public delegate void RemoteCallDelegate(NetworkBehaviour obj, NetworkReader reader, NetworkConnectionToClient senderConnection); + + class Invoker + { + // GameObjects might have multiple components of TypeA.CommandA(). + // when invoking, we check if 'TypeA' is an instance of the type. + // the hash itself isn't enough because we wouldn't know which component + // to invoke it on if there are multiple of the same type. + public Type componentType; + public RemoteCallType callType; + public RemoteCallDelegate function; + public bool cmdRequiresAuthority; + + public bool AreEqual(Type componentType, RemoteCallType remoteCallType, RemoteCallDelegate invokeFunction) => + this.componentType == componentType && + this.callType == remoteCallType && + this.function == invokeFunction; + } + + /// Used to help manage remote calls for NetworkBehaviours + public static class RemoteProcedureCalls + { + public const string InvokeRpcPrefix = "InvokeUserCode_"; + + // one lookup for all remote calls. + // allows us to easily add more remote call types without duplicating code. + // note: do not clear those with [RuntimeInitializeOnLoad] + // + // IMPORTANT: cmd/rpc functions are identified via **HASHES**. + // an index would requires half the bandwidth, but introduces issues + // where static constructors are lazily called, so index order isn't + // guaranteed. keep hashes to avoid: + // https://github.com/vis2k/Mirror/pull/3135 + // https://github.com/vis2k/Mirror/issues/3138 + // BUT: 2 byte hash is enough if we check for collisions. that's what we + // do for NetworkMessage as well. + static readonly Dictionary remoteCallDelegates = new Dictionary(); + + static bool CheckIfDelegateExists(Type componentType, RemoteCallType remoteCallType, RemoteCallDelegate func, ushort functionHash) + { + if (remoteCallDelegates.ContainsKey(functionHash)) + { + // something already registered this hash. + // it's okay if it was the same function. + Invoker oldInvoker = remoteCallDelegates[functionHash]; + if (oldInvoker.AreEqual(componentType, remoteCallType, func)) + { + return true; + } + + // otherwise notify user. there is a rare chance of string + // hash collisions. + Debug.LogError($"Function {oldInvoker.componentType}.{oldInvoker.function.GetMethodName()} and {componentType}.{func.GetMethodName()} have the same hash. Please rename one of them. To save bandwidth, we only use 2 bytes for the hash, which has a small chance of collisions."); + } + + return false; + } + + // pass full function name to avoid ClassA.Func & ClassB.Func collisions + internal static ushort RegisterDelegate(Type componentType, string functionFullName, RemoteCallType remoteCallType, RemoteCallDelegate func, bool cmdRequiresAuthority = true) + { + // type+func so Inventory.RpcUse != Equipment.RpcUse + ushort hash = (ushort)(functionFullName.GetStableHashCode() & 0xFFFF); + + if (CheckIfDelegateExists(componentType, remoteCallType, func, hash)) + return hash; + + remoteCallDelegates[hash] = new Invoker + { + callType = remoteCallType, + componentType = componentType, + function = func, + cmdRequiresAuthority = cmdRequiresAuthority + }; + return hash; + } + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + // need to pass componentType to support invoking on GameObjects with + // multiple components of same type with same remote call. + public static void RegisterCommand(Type componentType, string functionFullName, RemoteCallDelegate func, bool requiresAuthority) => + RegisterDelegate(componentType, functionFullName, RemoteCallType.Command, func, requiresAuthority); + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + // need to pass componentType to support invoking on GameObjects with + // multiple components of same type with same remote call. + public static void RegisterRpc(Type componentType, string functionFullName, RemoteCallDelegate func) => + RegisterDelegate(componentType, functionFullName, RemoteCallType.ClientRpc, func); + + // to clean up tests + internal static void RemoveDelegate(ushort hash) => + remoteCallDelegates.Remove(hash); + + internal static bool GetFunctionMethodName(ushort functionHash, out string methodName) + { + if (remoteCallDelegates.TryGetValue(functionHash, out Invoker invoker)) + { + methodName = invoker.function.GetMethodName().Replace(InvokeRpcPrefix, ""); + return true; + } + methodName = ""; + return false; + } + + // note: no need to throw an error if not found. + // an attacker might just try to call a cmd with an rpc's hash etc. + // returning false is enough. + static bool GetInvokerForHash(ushort functionHash, RemoteCallType remoteCallType, out Invoker invoker) => + remoteCallDelegates.TryGetValue(functionHash, out invoker) && + invoker != null && + invoker.callType == remoteCallType; + + // InvokeCmd/Rpc Delegate can all use the same function here + internal static bool Invoke(ushort functionHash, RemoteCallType remoteCallType, NetworkReader reader, NetworkBehaviour component, NetworkConnectionToClient senderConnection = null) + { + // IMPORTANT: we check if the message's componentIndex component is + // actually of the right type. prevents attackers trying + // to invoke remote calls on wrong components. + if (GetInvokerForHash(functionHash, remoteCallType, out Invoker invoker) && + invoker.componentType.IsInstanceOfType(component)) + { + // invoke function on this component + invoker.function(component, reader, senderConnection); + return true; + } + return false; + } + + // check if the command 'requiresAuthority' which is set in the attribute + internal static bool CommandRequiresAuthority(ushort cmdHash) => + GetInvokerForHash(cmdHash, RemoteCallType.Command, out Invoker invoker) && + invoker.cmdRequiresAuthority; + + /// Gets the handler function by hash. Useful for profilers and debuggers. + public static RemoteCallDelegate GetDelegate(ushort functionHash) => + remoteCallDelegates.TryGetValue(functionHash, out Invoker invoker) + ? invoker.function + : null; + } +} + diff --git a/Assets/ImportedAssets/Mirror/Core/RemoteCalls.cs.meta b/Assets/ImportedAssets/Mirror/Core/RemoteCalls.cs.meta new file mode 100644 index 0000000000..cf009a8eb2 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/RemoteCalls.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: d2cdbcbd1e377d6408a91acbec31ba16 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/RemoteCalls.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation.meta b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation.meta new file mode 100644 index 0000000000..85ac9a9c30 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4468e736f87964eaebb9d55fc3e132f7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/Snapshot.cs b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/Snapshot.cs new file mode 100644 index 0000000000..6b8ba8adf0 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/Snapshot.cs @@ -0,0 +1,17 @@ +// Snapshot interface so we can reuse it for all kinds of systems. +// for example, NetworkTransform, NetworkRigidbody, CharacterController etc. +// NOTE: we use '' and 'where T : Snapshot' to avoid boxing. +// List would cause allocations through boxing. +namespace Mirror +{ + public interface Snapshot + { + // the remote timestamp (when it was sent by the remote) + double remoteTime { get; set; } + + // the local timestamp (when it was received on our end) + // technically not needed for basic snapshot interpolation. + // only for dynamic buffer time adjustment. + double localTime { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/Snapshot.cs.meta b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/Snapshot.cs.meta new file mode 100644 index 0000000000..50e2faf866 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/Snapshot.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 12afea28fdb94154868a0a3b7a9df55b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/Snapshot.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs new file mode 100644 index 0000000000..2d1a2fc55f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs @@ -0,0 +1,390 @@ +// snapshot interpolation V2 by mischa +// +// Unity independent to be engine agnostic & easy to test. +// boxing: in C#, uses does not box! passing the interface would box! +// +// credits: +// glenn fiedler: https://gafferongames.com/post/snapshot_interpolation/ +// fholm: netcode streams +// fakebyte: standard deviation for dynamic adjustment +// ninjakicka: math & debugging +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class SortedListExtensions + { + // removes the first 'amount' elements from the sorted list + public static void RemoveRange(this SortedList list, int amount) + { + // remove the first element 'amount' times. + // handles -1 and > count safely. + for (int i = 0; i < amount && i < list.Count; ++i) + list.RemoveAt(0); + } + } + + public static class SnapshotInterpolation + { + // calculate timescale for catch-up / slow-down + // note that negative threshold should be <0. + // caller should verify (i.e. Unity OnValidate). + // improves branch prediction. + public static double Timescale( + double drift, // how far we are off from bufferTime + double catchupSpeed, // in % [0,1] + double slowdownSpeed, // in % [0,1] + double absoluteCatchupNegativeThreshold, // in seconds (careful, we may run out of snapshots) + double absoluteCatchupPositiveThreshold) // in seconds + { + // if the drift time is too large, it means we are behind more time. + // so we need to speed up the timescale. + // note the threshold should be sendInterval * catchupThreshold. + if (drift > absoluteCatchupPositiveThreshold) + { + // localTimeline += 0.001; // too simple, this would ping pong + return 1 + catchupSpeed; // n% faster + } + + // if the drift time is too small, it means we are ahead of time. + // so we need to slow down the timescale. + // note the threshold should be sendInterval * catchupThreshold. + if (drift < absoluteCatchupNegativeThreshold) + { + // localTimeline -= 0.001; // too simple, this would ping pong + return 1 - slowdownSpeed; // n% slower + } + + // keep constant timescale while within threshold. + // this way we have perfectly smooth speed most of the time. + return 1; + } + + // calculate dynamic buffer time adjustment + public static double DynamicAdjustment( + double sendInterval, + double jitterStandardDeviation, + double dynamicAdjustmentTolerance) + { + // jitter is equal to delivery time standard variation. + // delivery time is made up of 'sendInterval+jitter'. + // .Average would be dampened by the constant sendInterval + // .StandardDeviation is the changes in 'jitter' that we want + // so add it to send interval again. + double intervalWithJitter = sendInterval + jitterStandardDeviation; + + // how many multiples of sendInterval is that? + // we want to convert to bufferTimeMultiplier later. + double multiples = intervalWithJitter / sendInterval; + + // add the tolerance + double safezone = multiples + dynamicAdjustmentTolerance; + // UnityEngine.Debug.Log($"sendInterval={sendInterval:F3} jitter std={jitterStandardDeviation:F3} => that is ~{multiples:F1} x sendInterval + {dynamicAdjustmentTolerance} => dynamic bufferTimeMultiplier={safezone}"); + return safezone; + } + + // helper function to insert a snapshot if it doesn't exist yet. + // extra function so we can use it for both cases: + // NetworkClient global timeline insertions & adjustments via Insert. + // NetworkBehaviour local insertion without any time adjustments. + public static bool InsertIfNotExists( + SortedList buffer, // snapshot buffer + int bufferLimit, // don't grow infinitely + T snapshot) // the newly received snapshot + where T : Snapshot + { + // slow clients may not be able to process incoming snapshots fast enough. + // infinitely growing snapshots would make it even worse. + // for example, run NetworkRigidbodyBenchmark while deep profiling client. + // the client just grows and reallocates the buffer forever. + if (buffer.Count >= bufferLimit) return false; + + // SortedList does not allow duplicates. + // we don't need to check ContainsKey (which is expensive). + // simply add and compare count before/after for the return value. + + //if (buffer.ContainsKey(snapshot.remoteTime)) return false; // too expensive + // buffer.Add(snapshot.remoteTime, snapshot); // throws if key exists + + int before = buffer.Count; + buffer[snapshot.remoteTime] = snapshot; // overwrites if key exists + return buffer.Count > before; + } + + // clamp timeline for cases where it gets too far behind. + // for example, a client app may go into the background and get updated + // with 1hz for a while. by the time it's back it's at least 30 frames + // behind, possibly more if the transport also queues up. In this + // scenario, at 1% catch up it took around 20+ seconds to finally catch + // up. For these kinds of scenarios it will be better to snap / clamp. + // + // to reproduce, try snapshot interpolation demo and press the button to + // simulate the client timeline at multiple seconds behind. it'll take + // a long time to catch up if the timeline is a long time behind. + public static double TimelineClamp( + double localTimeline, + double bufferTime, + double latestRemoteTime) + { + // we want local timeline to always be 'bufferTime' behind remote. + double targetTime = latestRemoteTime - bufferTime; + + // we define a boundary of 'bufferTime' around the target time. + // this is where catchup / slowdown will happen. + // outside of the area, we clamp. + double lowerBound = targetTime - bufferTime; // how far behind we can get + double upperBound = targetTime + bufferTime; // how far ahead we can get + return Mathd.Clamp(localTimeline, lowerBound, upperBound); + } + + // call this for every received snapshot. + // adds / inserts it to the list & initializes local time if needed. + public static void InsertAndAdjust( + SortedList buffer, // snapshot buffer + int bufferLimit, // don't grow infinitely + T snapshot, // the newly received snapshot + ref double localTimeline, // local interpolation time based on server time + ref double localTimescale, // timeline multiplier to apply catchup / slowdown over time + float sendInterval, // for debugging + double bufferTime, // offset for buffering + double catchupSpeed, // in % [0,1] + double slowdownSpeed, // in % [0,1] + ref ExponentialMovingAverage driftEma, // for catchup / slowdown + float catchupNegativeThreshold, // in % of sendInteral (careful, we may run out of snapshots) + float catchupPositiveThreshold, // in % of sendInterval + ref ExponentialMovingAverage deliveryTimeEma) // for dynamic buffer time adjustment + where T : Snapshot + { + // first snapshot? + // initialize local timeline. + // we want it to be behind by 'offset'. + // + // note that the first snapshot may be a lagging packet. + // so we would always be behind by that lag. + // this requires catchup later. + if (buffer.Count == 0) + localTimeline = snapshot.remoteTime - bufferTime; + + // insert into the buffer. + // + // note that we might insert it between our current interpolation + // which is fine, it adds another data point for accuracy. + // + // note that insert may be called twice for the same key. + // by default, this would throw. + // need to handle it silently. + if (InsertIfNotExists(buffer, bufferLimit, snapshot)) + { + // dynamic buffer adjustment needs delivery interval jitter + if (buffer.Count >= 2) + { + // note that this is not entirely accurate for scrambled inserts. + // + // we always use the last two, not what we just inserted + // even if we were to use the diff for what we just inserted, + // a scrambled insert would still not be 100% accurate: + // => assume a buffer of AC, with delivery time C-A + // => we then insert B, with delivery time B-A + // => but then technically the first C-A wasn't correct, + // as it would have to be C-B + // + // in practice, scramble is rare and won't make much difference + double previousLocalTime = buffer.Values[buffer.Count - 2].localTime; + double lastestLocalTime = buffer.Values[buffer.Count - 1].localTime; + + // this is the delivery time since last snapshot + double localDeliveryTime = lastestLocalTime - previousLocalTime; + + // feed the local delivery time to the EMA. + // this is what the original stream did too. + // our final dynamic buffer adjustment is different though. + // we use standard deviation instead of average. + deliveryTimeEma.Add(localDeliveryTime); + } + + // adjust timescale to catch up / slow down after each insertion + // because that is when we add new values to our EMA. + + // we want localTimeline to be about 'bufferTime' behind. + // for that, we need the delivery time EMA. + // snapshots may arrive out of order, we can not use last-timeline. + // we need to use the inserted snapshot's time - timeline. + double latestRemoteTime = snapshot.remoteTime; + + // ensure timeline stays within a reasonable bound behind/ahead. + localTimeline = TimelineClamp(localTimeline, bufferTime, latestRemoteTime); + + // calculate timediff after localTimeline override changes + double timeDiff = latestRemoteTime - localTimeline; + + // next, calculate average of a few seconds worth of timediffs. + // this gives smoother results. + // + // to calculate the average, we could simply loop through the + // last 'n' seconds worth of timediffs, but: + // - our buffer may only store a few snapshots (bufferTime) + // - looping through seconds worth of snapshots every time is + // expensive + // + // to solve this, we use an exponential moving average. + // https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average + // which is basically fancy math to do the same but faster. + // additionally, it allows us to look at more timeDiff values + // than we sould have access to in our buffer :) + driftEma.Add(timeDiff); + + // timescale depends on driftEma. + // driftEma only changes when inserting. + // therefore timescale only needs to be calculated when inserting. + // saves CPU cycles in Update. + + // next up, calculate how far we are currently away from bufferTime + double drift = driftEma.Value - bufferTime; + + // convert relative thresholds to absolute values based on sendInterval + double absoluteNegativeThreshold = sendInterval * catchupNegativeThreshold; + double absolutePositiveThreshold = sendInterval * catchupPositiveThreshold; + + // next, set localTimescale to catchup consistently in Update(). + // we quantize between default/catchup/slowdown, + // this way we have 'default' speed most of the time(!). + // and only catch up / slow down for a little bit occasionally. + // a consistent multiplier would never be exactly 1.0. + localTimescale = Timescale(drift, catchupSpeed, slowdownSpeed, absoluteNegativeThreshold, absolutePositiveThreshold); + + // debug logging + // UnityEngine.Debug.Log($"sendInterval={sendInterval:F3} bufferTime={bufferTime:F3} drift={drift:F3} driftEma={driftEma.Value:F3} timescale={localTimescale:F3} deliveryIntervalEma={deliveryTimeEma.Value:F3}"); + } + } + + // sample snapshot buffer to find the pair around the given time. + // returns indices so we can use it with RemoveRange to clear old snaps. + // make sure to use use buffer.Values[from/to], not buffer[from/to]. + // make sure to only call this is we have > 0 snapshots. + public static void Sample( + SortedList buffer, // snapshot buffer + double localTimeline, // local interpolation time based on server time + out int from, // the snapshot <= time + out int to, // the snapshot >= time + out double t) // interpolation factor + where T : Snapshot + { + from = -1; + to = -1; + t = 0; + + // sample from [0,count-1] so we always have two at 'i' and 'i+1'. + for (int i = 0; i < buffer.Count - 1; ++i) + { + // is local time between these two? + T first = buffer.Values[i]; + T second = buffer.Values[i + 1]; + if (localTimeline >= first.remoteTime && + localTimeline <= second.remoteTime) + { + // use these two snapshots + from = i; + to = i + 1; + t = Mathd.InverseLerp(first.remoteTime, second.remoteTime, localTimeline); + return; + } + } + + // didn't find two snapshots around local time. + // so pick either the first or last, depending on which is closer. + + // oldest snapshot ahead of local time? + if (buffer.Values[0].remoteTime > localTimeline) + { + from = to = 0; + t = 0; + } + // otherwise initialize both to the last one + else + { + from = to = buffer.Count - 1; + t = 0; + } + } + + // progress local timeline every update. + // + // ONLY CALL IF SNAPSHOTS.COUNT > 0! + // + // decoupled from Step for easier testing and so we can progress + // time only once in NetworkClient, while stepping for each component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void StepTime( + double deltaTime, // engine delta time (unscaled) + ref double localTimeline, // local interpolation time based on server time + double localTimescale) // catchup / slowdown is applied to time every update) + { + // move local forward in time, scaled with catchup / slowdown applied + localTimeline += deltaTime * localTimescale; + } + + // sample, clear old. + // call this every update. + // + // ONLY CALL IF SNAPSHOTS.COUNT > 0! + // + // returns true if there is anything to apply (requires at least 1 snap) + // from/to/t are out parameters instead of an interpolated 'computed'. + // this allows us to store from/to/t globally (i.e. in NetworkClient) + // and have each component apply the interpolation manually. + // besides, passing "Func Interpolate" would allocate anyway. + public static void StepInterpolation( + SortedList buffer, // snapshot buffer + double localTimeline, // local interpolation time based on server time + out T fromSnapshot, // we interpolate 'from' this snapshot + out T toSnapshot, // 'to' this snapshot + out double t) // at ratio 't' [0,1] + where T : Snapshot + { + // check this in caller: + // nothing to do if there are no snapshots at all yet + // if (buffer.Count == 0) return false; + + // sample snapshot buffer at local interpolation time + Sample(buffer, localTimeline, out int from, out int to, out t); + + // save from/to + fromSnapshot = buffer.Values[from]; + toSnapshot = buffer.Values[to]; + + // remove older snapshots that we definitely don't need anymore. + // after(!) using the indices. + // + // if we have 3 snapshots and we are between 2nd and 3rd: + // from = 1, to = 2 + // then we need to remove the first one, which is exactly 'from'. + // because 'from-1' = 0 would remove none. + buffer.RemoveRange(from); + } + + // update time, sample, clear old. + // call this every update. + // + // ONLY CALL IF SNAPSHOTS.COUNT > 0! + // + // returns true if there is anything to apply (requires at least 1 snap) + // from/to/t are out parameters instead of an interpolated 'computed'. + // this allows us to store from/to/t globally (i.e. in NetworkClient) + // and have each component apply the interpolation manually. + // besides, passing "Func Interpolate" would allocate anyway. + public static void Step( + SortedList buffer, // snapshot buffer + double deltaTime, // engine delta time (unscaled) + ref double localTimeline, // local interpolation time based on server time + double localTimescale, // catchup / slowdown is applied to time every update + out T fromSnapshot, // we interpolate 'from' this snapshot + out T toSnapshot, // 'to' this snapshot + out double t) // at ratio 't' [0,1] + where T : Snapshot + { + StepTime(deltaTime, ref localTimeline, localTimescale); + StepInterpolation(buffer, localTimeline, out fromSnapshot, out toSnapshot, out t); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs.meta b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs.meta new file mode 100644 index 0000000000..d41677f139 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 72c16070d85334011853813488ab1431 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs new file mode 100644 index 0000000000..74feae40c2 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs @@ -0,0 +1,70 @@ +// snapshot interpolation settings struct. +// can easily be exposed in Unity inspectors. +using System; +using UnityEngine; + +namespace Mirror +{ + // class so we can define defaults easily + [Serializable] + public class SnapshotInterpolationSettings + { + // decrease bufferTime at runtime to see the catchup effect. + // increase to see slowdown. + // 'double' so we can have very precise dynamic adjustment without rounding + [Header("Buffering")] + [Tooltip("Local simulation is behind by sendInterval * multiplier seconds.\n\nThis guarantees that we always have enough snapshots in the buffer to mitigate lags & jitter.\n\nIncrease this if the simulation isn't smooth. By default, it should be around 2.")] + public double bufferTimeMultiplier = 2; + + [Tooltip("If a client can't process snapshots fast enough, don't store too many.")] + public int bufferLimit = 32; + + // catchup ///////////////////////////////////////////////////////////// + // catchup thresholds in 'frames'. + // half a frame might be too aggressive. + [Header("Catchup / Slowdown")] + [Tooltip("Slowdown begins when the local timeline is moving too fast towards remote time. Threshold is in frames worth of snapshots.\n\nThis needs to be negative.\n\nDon't modify unless you know what you are doing.")] + public float catchupNegativeThreshold = -1; // careful, don't want to run out of snapshots + + [Tooltip("Catchup begins when the local timeline is moving too slow and getting too far away from remote time. Threshold is in frames worth of snapshots.\n\nThis needs to be positive.\n\nDon't modify unless you know what you are doing.")] + public float catchupPositiveThreshold = 1; + + [Tooltip("Local timeline acceleration in % while catching up.")] + [Range(0, 1)] + public double catchupSpeed = 0.02f; // see snap interp demo. 1% is too slow. + + [Tooltip("Local timeline slowdown in % while slowing down.")] + [Range(0, 1)] + public double slowdownSpeed = 0.04f; // slow down a little faster so we don't encounter empty buffer (= jitter) + + [Tooltip("Catchup/Slowdown is adjusted over n-second exponential moving average.")] + public int driftEmaDuration = 1; // shouldn't need to modify this, but expose it anyway + + // dynamic buffer time adjustment ////////////////////////////////////// + // dynamically adjusts bufferTimeMultiplier for smooth results. + // to understand how this works, try this manually: + // + // - disable dynamic adjustment + // - set jitter = 0.2 (20% is a lot!) + // - notice some stuttering + // - disable interpolation to see just how much jitter this really is(!) + // - enable interpolation again + // - manually increase bufferTimeMultiplier to 3-4 + // ... the cube slows down (blue) until it's smooth + // - with dynamic adjustment enabled, it will set 4 automatically + // ... the cube slows down (blue) until it's smooth as well + // + // note that 20% jitter is extreme. + // for this to be perfectly smooth, set the safety tolerance to '2'. + // but realistically this is not necessary, and '1' is enough. + [Header("Dynamic Adjustment")] + [Tooltip("Automatically adjust bufferTimeMultiplier for smooth results.\nSets a low multiplier on stable connections, and a high multiplier on jittery connections.")] + public bool dynamicAdjustment = true; + + [Tooltip("Safety buffer that is always added to the dynamic bufferTimeMultiplier adjustment.")] + public float dynamicAdjustmentTolerance = 1; // 1 is realistically just fine, 2 is very very safe even for 20% jitter. can be half a frame too. (see above comments) + + [Tooltip("Dynamic adjustment is computed over n-second exponential moving average standard deviation.")] + public int deliveryTimeEmaDuration = 2; // 1-2s recommended to capture average delivery time + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs.meta b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs.meta new file mode 100644 index 0000000000..558cc9fd40 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f955b76b7956417088c03992b3622dc9 +timeCreated: 1678507210 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs new file mode 100644 index 0000000000..5bfdd3a99e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs @@ -0,0 +1,15 @@ +namespace Mirror +{ + // empty snapshot that is only used to progress client's local timeline. + public struct TimeSnapshot : Snapshot + { + public double remoteTime { get; set; } + public double localTime { get; set; } + + public TimeSnapshot(double remoteTime, double localTime) + { + this.remoteTime = remoteTime; + this.localTime = localTime; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs.meta b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs.meta new file mode 100644 index 0000000000..d5574eb24b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: afe2b5ed49634971a2aec720ad74e5cd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/SyncDictionary.cs b/Assets/ImportedAssets/Mirror/Core/SyncDictionary.cs new file mode 100644 index 0000000000..3cf73f5197 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SyncDictionary.cs @@ -0,0 +1,366 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Mirror +{ + public class SyncIDictionary : SyncObject, IDictionary, IReadOnlyDictionary + { + /// This is called after the item is added with TKey + public Action OnAdd; + + /// This is called after the item is changed with TKey. TValue is the OLD item + public Action OnSet; + + /// This is called after the item is removed with TKey. TValue is the OLD item + public Action OnRemove; + + /// + /// This is called for all changes to the Dictionary. + /// For OP_ADD, TValue is the NEW value of the entry. + /// For OP_SET and OP_REMOVE, TValue is the OLD value of the entry. + /// For OP_CLEAR, both TKey and TValue are default. + /// + public Action OnChange; + + /// This is called before the data is cleared + public Action OnClear; + + // Deprecated 2024-03-22 + [Obsolete("Use individual Actions, which pass OLD values where appropriate, instead.")] + public Action Callback; + + protected readonly IDictionary objects; + + public SyncIDictionary(IDictionary objects) + { + this.objects = objects; + } + + public int Count => objects.Count; + public bool IsReadOnly => !IsWritable(); + + public enum Operation : byte + { + OP_ADD, + OP_CLEAR, + OP_REMOVE, + OP_SET + } + + struct Change + { + internal Operation operation; + internal TKey key; + internal TValue item; + } + + // list of changes. + // -> insert/delete/clear is only ONE change + // -> changing the same slot 10x causes 10 changes. + // -> note that this grows until next sync(!) + // TODO Dictionary to avoid ever growing changes / redundant changes! + readonly List changes = new List(); + + // how many changes we need to ignore + // this is needed because when we initialize the list, + // we might later receive changes that have already been applied + // so we need to skip them + int changesAhead; + + public ICollection Keys => objects.Keys; + + public ICollection Values => objects.Values; + + IEnumerable IReadOnlyDictionary.Keys => objects.Keys; + + IEnumerable IReadOnlyDictionary.Values => objects.Values; + + public override void OnSerializeAll(NetworkWriter writer) + { + // if init, write the full list content + writer.WriteUInt((uint)objects.Count); + + foreach (KeyValuePair syncItem in objects) + { + writer.Write(syncItem.Key); + writer.Write(syncItem.Value); + } + + // all changes have been applied already + // thus the client will need to skip all the pending changes + // or they would be applied again. + // So we write how many changes are pending + writer.WriteUInt((uint)changes.Count); + } + + public override void OnSerializeDelta(NetworkWriter writer) + { + // write all the queued up changes + writer.WriteUInt((uint)changes.Count); + + for (int i = 0; i < changes.Count; i++) + { + Change change = changes[i]; + writer.WriteByte((byte)change.operation); + + switch (change.operation) + { + case Operation.OP_ADD: + case Operation.OP_SET: + writer.Write(change.key); + writer.Write(change.item); + break; + case Operation.OP_REMOVE: + writer.Write(change.key); + break; + case Operation.OP_CLEAR: + break; + } + } + } + + public override void OnDeserializeAll(NetworkReader reader) + { + // if init, write the full list content + int count = (int)reader.ReadUInt(); + + objects.Clear(); + changes.Clear(); + + for (int i = 0; i < count; i++) + { + TKey key = reader.Read(); + TValue obj = reader.Read(); + objects.Add(key, obj); + } + + // We will need to skip all these changes + // the next time the list is synchronized + // because they have already been applied + changesAhead = (int)reader.ReadUInt(); + } + + public override void OnDeserializeDelta(NetworkReader reader) + { + int changesCount = (int)reader.ReadUInt(); + + for (int i = 0; i < changesCount; i++) + { + Operation operation = (Operation)reader.ReadByte(); + + // apply the operation only if it is a new change + // that we have not applied yet + bool apply = changesAhead == 0; + TKey key = default; + TValue item = default; + + switch (operation) + { + case Operation.OP_ADD: + case Operation.OP_SET: + key = reader.Read(); + item = reader.Read(); + if (apply) + { + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + if (objects.TryGetValue(key, out TValue oldItem)) + { + objects[key] = item; // assign after TryGetValue + AddOperation(Operation.OP_SET, key, item, oldItem, false); + } + else + { + objects[key] = item; // assign after TryGetValue + AddOperation(Operation.OP_ADD, key, item, default, false); + } + } + break; + + case Operation.OP_CLEAR: + if (apply) + { + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_CLEAR, default, default, default, false); + // clear after invoking the callback so users can iterate the dictionary + // and take appropriate action on the items before they are wiped. + objects.Clear(); + } + break; + + case Operation.OP_REMOVE: + key = reader.Read(); + if (apply) + { + if (objects.TryGetValue(key, out TValue oldItem)) + { + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + objects.Remove(key); + AddOperation(Operation.OP_REMOVE, key, oldItem, oldItem, false); + } + } + break; + } + + if (!apply) + { + // we just skipped this change + changesAhead--; + } + } + } + + // throw away all the changes + // this should be called after a successful sync + public override void ClearChanges() => changes.Clear(); + + public override void Reset() + { + changes.Clear(); + changesAhead = 0; + objects.Clear(); + } + + public TValue this[TKey i] + { + get => objects[i]; + set + { + if (ContainsKey(i)) + { + TValue oldItem = objects[i]; + objects[i] = value; + AddOperation(Operation.OP_SET, i, value, oldItem, true); + } + else + { + objects[i] = value; + AddOperation(Operation.OP_ADD, i, value, default, true); + } + } + } + + public bool TryGetValue(TKey key, out TValue value) => objects.TryGetValue(key, out value); + + public bool ContainsKey(TKey key) => objects.ContainsKey(key); + + public bool Contains(KeyValuePair item) => TryGetValue(item.Key, out TValue val) && EqualityComparer.Default.Equals(val, item.Value); + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + if (arrayIndex < 0 || arrayIndex > array.Length) + throw new System.ArgumentOutOfRangeException(nameof(arrayIndex), "Array Index Out of Range"); + + if (array.Length - arrayIndex < Count) + throw new System.ArgumentException("The number of items in the SyncDictionary is greater than the available space from arrayIndex to the end of the destination array"); + + int i = arrayIndex; + foreach (KeyValuePair item in objects) + { + array[i] = item; + i++; + } + } + + public void Add(KeyValuePair item) => Add(item.Key, item.Value); + + public void Add(TKey key, TValue value) + { + objects.Add(key, value); + AddOperation(Operation.OP_ADD, key, value, default, true); + } + + public bool Remove(TKey key) + { + if (objects.TryGetValue(key, out TValue oldItem) && objects.Remove(key)) + { + AddOperation(Operation.OP_REMOVE, key, oldItem, oldItem, true); + return true; + } + return false; + } + + public bool Remove(KeyValuePair item) + { + bool result = objects.Remove(item.Key); + if (result) + AddOperation(Operation.OP_REMOVE, item.Key, item.Value, item.Value, true); + + return result; + } + + public void Clear() + { + AddOperation(Operation.OP_CLEAR, default, default, default, true); + // clear after invoking the callback so users can iterate the dictionary + // and take appropriate action on the items before they are wiped. + objects.Clear(); + } + + void AddOperation(Operation op, TKey key, TValue item, TValue oldItem, bool checkAccess) + { + if (checkAccess && IsReadOnly) + throw new InvalidOperationException("SyncDictionaries can only be modified by the owner."); + + Change change = new Change + { + operation = op, + key = key, + item = item + }; + + if (IsRecording()) + { + changes.Add(change); + OnDirty?.Invoke(); + } + + switch (op) + { + case Operation.OP_ADD: + OnAdd?.Invoke(key); + OnChange?.Invoke(op, key, item); + break; + case Operation.OP_SET: + OnSet?.Invoke(key, oldItem); + OnChange?.Invoke(op, key, oldItem); + break; + case Operation.OP_REMOVE: + OnRemove?.Invoke(key, oldItem); + OnChange?.Invoke(op, key, oldItem); + break; + case Operation.OP_CLEAR: + OnClear?.Invoke(); + OnChange?.Invoke(op, default, default); + break; + } + +#pragma warning disable CS0618 // Type or member is obsolete + Callback?.Invoke(op, key, item); +#pragma warning restore CS0618 // Type or member is obsolete + } + + public IEnumerator> GetEnumerator() => objects.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => objects.GetEnumerator(); + } + + public class SyncDictionary : SyncIDictionary + { + public SyncDictionary() : base(new Dictionary()) { } + public SyncDictionary(IEqualityComparer eq) : base(new Dictionary(eq)) { } + public SyncDictionary(IDictionary d) : base(new Dictionary(d)) { } + public new Dictionary.ValueCollection Values => ((Dictionary)objects).Values; + public new Dictionary.KeyCollection Keys => ((Dictionary)objects).Keys; + public new Dictionary.Enumerator GetEnumerator() => ((Dictionary)objects).GetEnumerator(); + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/SyncDictionary.cs.meta b/Assets/ImportedAssets/Mirror/Core/SyncDictionary.cs.meta new file mode 100644 index 0000000000..caa8a05e4b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SyncDictionary.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 4b346c49cfdb668488a364c3023590e2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/SyncDictionary.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/SyncList.cs b/Assets/ImportedAssets/Mirror/Core/SyncList.cs new file mode 100644 index 0000000000..6f4952e4e8 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SyncList.cs @@ -0,0 +1,467 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Mirror +{ + public class SyncList : SyncObject, IList, IReadOnlyList + { + public enum Operation : byte + { + OP_ADD, + OP_SET, + OP_INSERT, + OP_REMOVEAT, + OP_CLEAR + } + + /// This is called after the item is added with index + public Action OnAdd; + + /// This is called after the item is inserted with inedx + public Action OnInsert; + + /// This is called after the item is set with index and OLD Value + public Action OnSet; + + /// This is called after the item is removed with index and OLD Value + public Action OnRemove; + + /// + /// This is called for all changes to the List. + /// For OP_ADD and OP_INSERT, T is the NEW value of the entry. + /// For OP_SET and OP_REMOVE, T is the OLD value of the entry. + /// For OP_CLEAR, T is default. + /// + public Action OnChange; + + /// This is called before the list is cleared so the list can be iterated + public Action OnClear; + + // Deprecated 2024-03-23 + [Obsolete("Use individual Actions, which pass OLD values where appropriate, instead.")] + public Action Callback; + + readonly IList objects; + readonly IEqualityComparer comparer; + + public int Count => objects.Count; + public bool IsReadOnly => !IsWritable(); + + struct Change + { + internal Operation operation; + internal int index; + internal T item; + } + + // list of changes. + // -> insert/delete/clear is only ONE change + // -> changing the same slot 10x caues 10 changes. + // -> note that this grows until next sync(!) + readonly List changes = new List(); + + // how many changes we need to ignore + // this is needed because when we initialize the list, + // we might later receive changes that have already been applied + // so we need to skip them + int changesAhead; + + public SyncList() : this(EqualityComparer.Default) { } + + public SyncList(IEqualityComparer comparer) + { + this.comparer = comparer ?? EqualityComparer.Default; + objects = new List(); + } + + public SyncList(IList objects, IEqualityComparer comparer = null) + { + this.comparer = comparer ?? EqualityComparer.Default; + this.objects = objects; + } + + // throw away all the changes + // this should be called after a successful sync + public override void ClearChanges() => changes.Clear(); + + public override void Reset() + { + changes.Clear(); + changesAhead = 0; + objects.Clear(); + } + + void AddOperation(Operation op, int itemIndex, T oldItem, T newItem, bool checkAccess) + { + if (checkAccess && IsReadOnly) + throw new InvalidOperationException("Synclists can only be modified by the owner."); + + Change change = new Change + { + operation = op, + index = itemIndex, + item = newItem + }; + + if (IsRecording()) + { + changes.Add(change); + OnDirty?.Invoke(); + } + + switch (op) + { + case Operation.OP_ADD: + OnAdd?.Invoke(itemIndex); + OnChange?.Invoke(op, itemIndex, newItem); + break; + case Operation.OP_INSERT: + OnInsert?.Invoke(itemIndex); + OnChange?.Invoke(op, itemIndex, newItem); + break; + case Operation.OP_SET: + OnSet?.Invoke(itemIndex, oldItem); + OnChange?.Invoke(op, itemIndex, oldItem); + break; + case Operation.OP_REMOVEAT: + OnRemove?.Invoke(itemIndex, oldItem); + OnChange?.Invoke(op, itemIndex, oldItem); + break; + case Operation.OP_CLEAR: + OnClear?.Invoke(); + OnChange?.Invoke(op, itemIndex, default); + break; + } + +#pragma warning disable CS0618 // Type or member is obsolete + Callback?.Invoke(op, itemIndex, oldItem, newItem); +#pragma warning restore CS0618 // Type or member is obsolete + } + + public override void OnSerializeAll(NetworkWriter writer) + { + // if init, write the full list content + writer.WriteUInt((uint)objects.Count); + + for (int i = 0; i < objects.Count; i++) + { + T obj = objects[i]; + writer.Write(obj); + } + + // all changes have been applied already + // thus the client will need to skip all the pending changes + // or they would be applied again. + // So we write how many changes are pending + writer.WriteUInt((uint)changes.Count); + } + + public override void OnSerializeDelta(NetworkWriter writer) + { + // write all the queued up changes + writer.WriteUInt((uint)changes.Count); + + for (int i = 0; i < changes.Count; i++) + { + Change change = changes[i]; + writer.WriteByte((byte)change.operation); + + switch (change.operation) + { + case Operation.OP_ADD: + writer.Write(change.item); + break; + + case Operation.OP_CLEAR: + break; + + case Operation.OP_REMOVEAT: + writer.WriteUInt((uint)change.index); + break; + + case Operation.OP_INSERT: + case Operation.OP_SET: + writer.WriteUInt((uint)change.index); + writer.Write(change.item); + break; + } + } + } + + public override void OnDeserializeAll(NetworkReader reader) + { + // if init, write the full list content + int count = (int)reader.ReadUInt(); + + objects.Clear(); + changes.Clear(); + + for (int i = 0; i < count; i++) + { + T obj = reader.Read(); + objects.Add(obj); + } + + // We will need to skip all these changes + // the next time the list is synchronized + // because they have already been applied + changesAhead = (int)reader.ReadUInt(); + } + + public override void OnDeserializeDelta(NetworkReader reader) + { + int changesCount = (int)reader.ReadUInt(); + + for (int i = 0; i < changesCount; i++) + { + Operation operation = (Operation)reader.ReadByte(); + + // apply the operation only if it is a new change + // that we have not applied yet + bool apply = changesAhead == 0; + int index = 0; + T oldItem = default; + T newItem = default; + + switch (operation) + { + case Operation.OP_ADD: + newItem = reader.Read(); + if (apply) + { + index = objects.Count; + objects.Add(newItem); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_ADD, objects.Count - 1, default, newItem, false); + } + break; + + case Operation.OP_CLEAR: + if (apply) + { + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_CLEAR, 0, default, default, false); + // clear after invoking the callback so users can iterate the list + // and take appropriate action on the items before they are wiped. + objects.Clear(); + } + break; + + case Operation.OP_INSERT: + index = (int)reader.ReadUInt(); + newItem = reader.Read(); + if (apply) + { + objects.Insert(index, newItem); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_INSERT, index, default, newItem, false); + } + break; + + case Operation.OP_REMOVEAT: + index = (int)reader.ReadUInt(); + if (apply) + { + oldItem = objects[index]; + objects.RemoveAt(index); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_REMOVEAT, index, oldItem, default, false); + } + break; + + case Operation.OP_SET: + index = (int)reader.ReadUInt(); + newItem = reader.Read(); + if (apply) + { + oldItem = objects[index]; + objects[index] = newItem; + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_SET, index, oldItem, newItem, false); + } + break; + } + + if (!apply) + { + // we just skipped this change + changesAhead--; + } + } + } + + public void Add(T item) + { + objects.Add(item); + AddOperation(Operation.OP_ADD, objects.Count - 1, default, item, true); + } + + public void AddRange(IEnumerable range) + { + foreach (T entry in range) + Add(entry); + } + + public void Clear() + { + AddOperation(Operation.OP_CLEAR, 0, default, default, true); + // clear after invoking the callback so users can iterate the list + // and take appropriate action on the items before they are wiped. + objects.Clear(); + } + + public bool Contains(T item) => IndexOf(item) >= 0; + + public void CopyTo(T[] array, int index) => objects.CopyTo(array, index); + + public int IndexOf(T item) + { + for (int i = 0; i < objects.Count; ++i) + if (comparer.Equals(item, objects[i])) + return i; + return -1; + } + + public int FindIndex(Predicate match) + { + for (int i = 0; i < objects.Count; ++i) + if (match(objects[i])) + return i; + return -1; + } + + public T Find(Predicate match) + { + int i = FindIndex(match); + return (i != -1) ? objects[i] : default; + } + + public List FindAll(Predicate match) + { + List results = new List(); + for (int i = 0; i < objects.Count; ++i) + if (match(objects[i])) + results.Add(objects[i]); + return results; + } + + public void Insert(int index, T item) + { + objects.Insert(index, item); + AddOperation(Operation.OP_INSERT, index, default, item, true); + } + + public void InsertRange(int index, IEnumerable range) + { + foreach (T entry in range) + { + Insert(index, entry); + index++; + } + } + + public bool Remove(T item) + { + int index = IndexOf(item); + bool result = index >= 0; + if (result) + RemoveAt(index); + + return result; + } + + public void RemoveAt(int index) + { + T oldItem = objects[index]; + objects.RemoveAt(index); + AddOperation(Operation.OP_REMOVEAT, index, oldItem, default, true); + } + + public int RemoveAll(Predicate match) + { + List toRemove = new List(); + for (int i = 0; i < objects.Count; ++i) + if (match(objects[i])) + toRemove.Add(objects[i]); + + foreach (T entry in toRemove) + Remove(entry); + + return toRemove.Count; + } + + public T this[int i] + { + get => objects[i]; + set + { + if (!comparer.Equals(objects[i], value)) + { + T oldItem = objects[i]; + objects[i] = value; + AddOperation(Operation.OP_SET, i, oldItem, value, true); + } + } + } + + public Enumerator GetEnumerator() => new Enumerator(this); + + IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); + + IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); + + // default Enumerator allocates. we need a custom struct Enumerator to + // not allocate on the heap. + // (System.Collections.Generic.List source code does the same) + // + // benchmark: + // uMMORPG with 800 monsters, Skills.GetHealthBonus() which runs a + // foreach on skills SyncList: + // before: 81.2KB GC per frame + // after: 0KB GC per frame + // => this is extremely important for MMO scale networking + public struct Enumerator : IEnumerator + { + readonly SyncList list; + int index; + + public T Current { get; private set; } + + public Enumerator(SyncList list) + { + this.list = list; + index = -1; + Current = default; + } + + public bool MoveNext() + { + if (++index >= list.Count) + return false; + + Current = list[index]; + return true; + } + + public void Reset() => index = -1; + object IEnumerator.Current => Current; + public void Dispose() { } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/SyncList.cs.meta b/Assets/ImportedAssets/Mirror/Core/SyncList.cs.meta new file mode 100644 index 0000000000..e33bbaa535 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SyncList.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 744fc71f748fe40d5940e04bf42b29f3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/SyncList.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/SyncObject.cs b/Assets/ImportedAssets/Mirror/Core/SyncObject.cs new file mode 100644 index 0000000000..405e240da6 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SyncObject.cs @@ -0,0 +1,53 @@ +using System; + +namespace Mirror +{ + /// SyncObjects sync state between server and client. E.g. SyncLists. + // SyncObject should be a class (instead of an interface) for a few reasons: + // * NetworkBehaviour stores SyncObjects in a list. structs would be a copy + // and OnSerialize would use the copy instead of the original struct. + // * Obsolete functions like Flush() don't need to be defined by each type + // * OnDirty/IsRecording etc. default functions can be defined once here + // for example, handling 'OnDirty wasn't initialized' with a default + // function that throws an exception will be useful for SyncVar + public abstract class SyncObject + { + /// Used internally to set owner NetworkBehaviour's dirty mask bit when changed. + public Action OnDirty; + + /// Used internally to check if we are currently tracking changes. + // prevents ever growing .changes lists: + // if a monster has no observers but we keep modifying a SyncObject, + // then the changes would never be flushed and keep growing, + // because OnSerialize isn't called without observers. + // => Func so we can set it to () => observers.Count > 0 + // without depending on NetworkComponent/NetworkIdentity here. + // => virtual so it simply always records by default + public Func IsRecording = () => true; + + // SyncList/Set/etc. shouldn't be modifiable if not owned. + // otherwise they would silently get out of sync. + // need a lambda because InitSyncObject is called in ctor, when + // 'isClient' etc. aren't initialized yet. + public Func IsWritable = () => true; + + /// Discard all the queued changes + // Consider the object fully synchronized with clients + public abstract void ClearChanges(); + + /// Write a full copy of the object + public abstract void OnSerializeAll(NetworkWriter writer); + + /// Write the changes made to the object since last sync + public abstract void OnSerializeDelta(NetworkWriter writer); + + /// Reads a full copy of the object + public abstract void OnDeserializeAll(NetworkReader reader); + + /// Reads the changes made to the object since last sync + public abstract void OnDeserializeDelta(NetworkReader reader); + + /// Resets the SyncObject so that it can be re-used + public abstract void Reset(); + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/SyncObject.cs.meta b/Assets/ImportedAssets/Mirror/Core/SyncObject.cs.meta new file mode 100644 index 0000000000..ad51c63cae --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SyncObject.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ae226d17a0c844041aa24cc2c023dd49 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/SyncObject.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/SyncSet.cs b/Assets/ImportedAssets/Mirror/Core/SyncSet.cs new file mode 100644 index 0000000000..3d19b0e898 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SyncSet.cs @@ -0,0 +1,390 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Mirror +{ + public class SyncSet : SyncObject, ISet + { + /// This is called after the item is added. T is the new item. + public Action OnAdd; + + /// This is called after the item is removed. T is the OLD item + public Action OnRemove; + + /// + /// This is called for all changes to the Set. + /// For OP_ADD, T is the NEW value of the entry. + /// For OP_REMOVE, T is the OLD value of the entry. + /// For OP_CLEAR, T is default. + /// + public Action OnChange; + + /// This is called BEFORE the data is cleared + public Action OnClear; + + // Deprecated 2024-03-22 + [Obsolete("Use individual Actions, which pass OLD value where appropriate, instead.")] + public Action Callback; + + protected readonly ISet objects; + + public int Count => objects.Count; + public bool IsReadOnly => !IsWritable(); + + public enum Operation : byte + { + OP_ADD, + OP_REMOVE, + OP_CLEAR + } + + struct Change + { + internal Operation operation; + internal T item; + } + + // list of changes. + // -> insert/delete/clear is only ONE change + // -> changing the same slot 10x caues 10 changes. + // -> note that this grows until next sync(!) + // TODO Dictionary to avoid ever growing changes / redundant changes! + readonly List changes = new List(); + + // how many changes we need to ignore + // this is needed because when we initialize the list, + // we might later receive changes that have already been applied + // so we need to skip them + int changesAhead; + + public SyncSet(ISet objects) + { + this.objects = objects; + } + + public override void Reset() + { + changes.Clear(); + changesAhead = 0; + objects.Clear(); + } + + // throw away all the changes + // this should be called after a successful sync + public override void ClearChanges() => changes.Clear(); + + void AddOperation(Operation op, T oldItem, T newItem, bool checkAccess) + { + if (checkAccess && IsReadOnly) + throw new InvalidOperationException("SyncSets can only be modified by the owner."); + + Change change = default; + switch (op) + { + case Operation.OP_ADD: + change = new Change + { + operation = op, + item = newItem + }; + break; + case Operation.OP_REMOVE: + change = new Change + { + operation = op, + item = oldItem + }; + break; + case Operation.OP_CLEAR: + change = new Change + { + operation = op, + item = default + }; + break; + } + + if (IsRecording()) + { + changes.Add(change); + OnDirty?.Invoke(); + } + + switch (op) + { + case Operation.OP_ADD: + OnAdd?.Invoke(newItem); + OnChange?.Invoke(op, newItem); +#pragma warning disable CS0618 // Type or member is obsolete + Callback?.Invoke(op, newItem); +#pragma warning restore CS0618 // Type or member is obsolete + break; + case Operation.OP_REMOVE: + OnRemove?.Invoke(oldItem); + OnChange?.Invoke(op, oldItem); +#pragma warning disable CS0618 // Type or member is obsolete + Callback?.Invoke(op, oldItem); +#pragma warning restore CS0618 // Type or member is obsolete + break; + case Operation.OP_CLEAR: + OnClear?.Invoke(); + OnChange?.Invoke(op, default); +#pragma warning disable CS0618 // Type or member is obsolete + Callback?.Invoke(op, default); +#pragma warning restore CS0618 // Type or member is obsolete + break; + } + } + + void AddOperation(Operation op, bool checkAccess) => AddOperation(op, default, default, checkAccess); + + public override void OnSerializeAll(NetworkWriter writer) + { + // if init, write the full list content + writer.WriteUInt((uint)objects.Count); + + foreach (T obj in objects) + writer.Write(obj); + + // all changes have been applied already + // thus the client will need to skip all the pending changes + // or they would be applied again. + // So we write how many changes are pending + writer.WriteUInt((uint)changes.Count); + } + + public override void OnSerializeDelta(NetworkWriter writer) + { + // write all the queued up changes + writer.WriteUInt((uint)changes.Count); + + for (int i = 0; i < changes.Count; i++) + { + Change change = changes[i]; + writer.WriteByte((byte)change.operation); + + switch (change.operation) + { + case Operation.OP_ADD: + writer.Write(change.item); + break; + case Operation.OP_REMOVE: + writer.Write(change.item); + break; + case Operation.OP_CLEAR: + break; + } + } + } + + public override void OnDeserializeAll(NetworkReader reader) + { + // if init, write the full list content + int count = (int)reader.ReadUInt(); + + objects.Clear(); + changes.Clear(); + + for (int i = 0; i < count; i++) + { + T obj = reader.Read(); + objects.Add(obj); + } + + // We will need to skip all these changes + // the next time the list is synchronized + // because they have already been applied + changesAhead = (int)reader.ReadUInt(); + } + + public override void OnDeserializeDelta(NetworkReader reader) + { + int changesCount = (int)reader.ReadUInt(); + + for (int i = 0; i < changesCount; i++) + { + Operation operation = (Operation)reader.ReadByte(); + + // apply the operation only if it is a new change + // that we have not applied yet + bool apply = changesAhead == 0; + T oldItem = default; + T newItem = default; + + switch (operation) + { + case Operation.OP_ADD: + newItem = reader.Read(); + if (apply) + { + objects.Add(newItem); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_ADD, default, newItem, false); + } + break; + + case Operation.OP_REMOVE: + oldItem = reader.Read(); + if (apply) + { + objects.Remove(oldItem); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_REMOVE, oldItem, default, false); + } + break; + + case Operation.OP_CLEAR: + if (apply) + { + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_CLEAR, false); + // clear after invoking the callback so users can iterate the set + // and take appropriate action on the items before they are wiped. + objects.Clear(); + } + break; + } + + if (!apply) + { + // we just skipped this change + changesAhead--; + } + } + } + + public bool Add(T item) + { + if (objects.Add(item)) + { + AddOperation(Operation.OP_ADD, default, item, true); + return true; + } + return false; + } + + void ICollection.Add(T item) + { + if (objects.Add(item)) + AddOperation(Operation.OP_ADD, default, item, true); + } + + public void Clear() + { + AddOperation(Operation.OP_CLEAR, true); + // clear after invoking the callback so users can iterate the set + // and take appropriate action on the items before they are wiped. + objects.Clear(); + } + + public bool Contains(T item) => objects.Contains(item); + + public void CopyTo(T[] array, int index) => objects.CopyTo(array, index); + + public bool Remove(T item) + { + if (objects.Remove(item)) + { + AddOperation(Operation.OP_REMOVE, item, default, true); + return true; + } + return false; + } + + public IEnumerator GetEnumerator() => objects.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public void ExceptWith(IEnumerable other) + { + if (other == this) + { + Clear(); + return; + } + + // remove every element in other from this + foreach (T element in other) + Remove(element); + } + + public void IntersectWith(IEnumerable other) + { + if (other is ISet otherSet) + IntersectWithSet(otherSet); + else + { + HashSet otherAsSet = new HashSet(other); + IntersectWithSet(otherAsSet); + } + } + + void IntersectWithSet(ISet otherSet) + { + List elements = new List(objects); + + foreach (T element in elements) + if (!otherSet.Contains(element)) + Remove(element); + } + + public bool IsProperSubsetOf(IEnumerable other) => objects.IsProperSubsetOf(other); + + public bool IsProperSupersetOf(IEnumerable other) => objects.IsProperSupersetOf(other); + + public bool IsSubsetOf(IEnumerable other) => objects.IsSubsetOf(other); + + public bool IsSupersetOf(IEnumerable other) => objects.IsSupersetOf(other); + + public bool Overlaps(IEnumerable other) => objects.Overlaps(other); + + public bool SetEquals(IEnumerable other) => objects.SetEquals(other); + + // custom implementation so we can do our own Clear/Add/Remove for delta + public void SymmetricExceptWith(IEnumerable other) + { + if (other == this) + Clear(); + else + foreach (T element in other) + if (!Remove(element)) + Add(element); + } + + // custom implementation so we can do our own Clear/Add/Remove for delta + public void UnionWith(IEnumerable other) + { + if (other != this) + foreach (T element in other) + Add(element); + } + } + + public class SyncHashSet : SyncSet + { + public SyncHashSet() : this(EqualityComparer.Default) { } + public SyncHashSet(IEqualityComparer comparer) : base(new HashSet(comparer ?? EqualityComparer.Default)) { } + + // allocation free enumerator + public new HashSet.Enumerator GetEnumerator() => ((HashSet)objects).GetEnumerator(); + } + + public class SyncSortedSet : SyncSet + { + public SyncSortedSet() : this(Comparer.Default) { } + public SyncSortedSet(IComparer comparer) : base(new SortedSet(comparer ?? Comparer.Default)) { } + + // allocation free enumerator + public new SortedSet.Enumerator GetEnumerator() => ((SortedSet)objects).GetEnumerator(); + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/SyncSet.cs.meta b/Assets/ImportedAssets/Mirror/Core/SyncSet.cs.meta new file mode 100644 index 0000000000..ff79ae8e22 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/SyncSet.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8a31599d9f9dd4ef9999f7b9707c832c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/SyncSet.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Threading.meta b/Assets/ImportedAssets/Mirror/Core/Threading.meta new file mode 100644 index 0000000000..037993e70d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 752fcafbee1ec45c9a43c0cf65da39de +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPool.cs b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPool.cs new file mode 100644 index 0000000000..c0bc926b66 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPool.cs @@ -0,0 +1,45 @@ +// API consistent with Microsoft's ObjectPool. +// thread safe. +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class ConcurrentNetworkWriterPool + { + // initial capacity to avoid allocations in the first few frames + // 1000 * 1200 bytes = around 1 MB. + public const int InitialCapacity = 1000; + + + // reuse ConcurrentPool + // we still wrap it in NetworkWriterPool.Get/Recycle so we can reset the + // position before reusing. + // this is also more consistent with NetworkReaderPool where we need to + // assign the internal buffer before reusing. + static readonly ConcurrentPool pool = + new ConcurrentPool( + // new object function + () => new ConcurrentNetworkWriterPooled(), + // initial capacity to avoid allocations in the first few frames + // 1000 * 1200 bytes = around 1 MB. + InitialCapacity + ); + + // pool size access for debugging & tests + public static int Count => pool.Count; + + public static ConcurrentNetworkWriterPooled Get() + { + // grab from pool & reset position + ConcurrentNetworkWriterPooled writer = pool.Get(); + writer.Position = 0; + return writer; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Return(ConcurrentNetworkWriterPooled writer) + { + pool.Return(writer); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPool.cs.meta b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPool.cs.meta new file mode 100644 index 0000000000..40d343a01c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPool.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: fdf46e334f52400c854c9732f6fcf005 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPool.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPooled.cs b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPooled.cs new file mode 100644 index 0000000000..ccb1e47bc5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPooled.cs @@ -0,0 +1,11 @@ +using System; + +namespace Mirror +{ + /// Pooled (not threadsafe) NetworkWriter used from Concurrent pool (thread safe). Automatically returned to concurrent pool when using 'using' + // TODO make sealed again after removing obsolete NetworkWriterPooled! + public class ConcurrentNetworkWriterPooled : NetworkWriter, IDisposable + { + public void Dispose() => ConcurrentNetworkWriterPool.Return(this); + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPooled.cs.meta b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPooled.cs.meta new file mode 100644 index 0000000000..aae2b6718f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPooled.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9163d963b36b4e389318f312bfd8e488 +timeCreated: 1691485295 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentNetworkWriterPooled.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentPool.cs b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentPool.cs new file mode 100644 index 0000000000..eeac0cc460 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentPool.cs @@ -0,0 +1,44 @@ +// Pool to avoid allocations (from libuv2k) +// API consistent with Microsoft's ObjectPool. +// concurrent for thread safe access. +// +// currently not in use. keep it in case we need it again. +using System; +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public class ConcurrentPool + { + // Mirror is single threaded, no need for concurrent collections + // concurrent bag is for items who's order doesn't matter. + // just about right for our use case here. + readonly ConcurrentBag objects = new ConcurrentBag(); + + // some types might need additional parameters in their constructor, so + // we use a Func generator + readonly Func objectGenerator; + + public ConcurrentPool(Func objectGenerator, int initialCapacity) + { + this.objectGenerator = objectGenerator; + + // allocate an initial pool so we have fewer (if any) + // allocations in the first few frames (or seconds). + for (int i = 0; i < initialCapacity; ++i) + objects.Add(objectGenerator()); + } + + // take an element from the pool, or create a new one if empty + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T Get() => objects.TryTake(out T obj) ? obj : objectGenerator(); + + // return an element to the pool + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Return(T item) => objects.Add(item); + + // count to see how many objects are in the pool. useful for tests. + public int Count => objects.Count; + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentPool.cs.meta b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentPool.cs.meta new file mode 100644 index 0000000000..ce217d0cdd --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentPool.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ed304bd790ff478ca37233f66d04d1c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Threading/ConcurrentPool.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/ThreadLog.cs b/Assets/ImportedAssets/Mirror/Core/Threading/ThreadLog.cs new file mode 100644 index 0000000000..36dca5fd9d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/ThreadLog.cs @@ -0,0 +1,112 @@ +// threaded Debug.Log support (mischa 2022) +// +// Editor shows Debug.Logs from different threads. +// Builds don't show Debug.Logs from different threads. +// +// need to hook into logMessageReceivedThreaded to receive them in builds too. +using System.Collections.Concurrent; +using System.Threading; +using UnityEngine; + +namespace Mirror +{ + public static class ThreadLog + { + // queue log messages from threads + struct LogEntry + { + public int threadId; + public LogType type; + public string message; + public string stackTrace; + + public LogEntry(int threadId, LogType type, string message, string stackTrace) + { + this.threadId = threadId; + this.type = type; + this.message = message; + this.stackTrace = stackTrace; + } + } + + // ConcurrentQueue allocations are fine here. + // logs allocate anywway. + static readonly ConcurrentQueue logs = + new ConcurrentQueue(); + + // main thread id + static int mainThreadId; + +#if !UNITY_EDITOR + // Editor as of Unity 2021 does log threaded messages. + // only builds don't. + // do nothing in editor, otherwise we would log twice. + // before scene load ensures thread logs are all caught. + // otherwise some component's Awake may be called before we hooked it up. + // for example, ThreadedTransport's early logs wouldn't be caught. + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + static void Initialize() + { + + // set main thread id + mainThreadId = Thread.CurrentThread.ManagedThreadId; + + // receive threaded log calls + Application.logMessageReceivedThreaded -= OnLog; // remove old first. TODO unnecessary? + Application.logMessageReceivedThreaded += OnLog; + + // process logs on main thread Update + NetworkLoop.OnLateUpdate -= OnLateUpdate; // remove old first. TODO unnecessary? + NetworkLoop.OnLateUpdate += OnLateUpdate; + + // log for debugging + Debug.Log("ThreadLog initialized."); + } +#endif + + static bool IsMainThread() => + Thread.CurrentThread.ManagedThreadId == mainThreadId; + + // callback runs on the same thread where the Debug.Log is called. + // we can use this to buffer messages for main thread here. + static void OnLog(string message, string stackTrace, LogType type) + { + // only enqueue messages from other threads. + // otherwise OnLateUpdate main thread logging would be enqueued + // as well, causing deadlock. + if (IsMainThread()) return; + + // queue for logging from main thread later + logs.Enqueue(new LogEntry(Thread.CurrentThread.ManagedThreadId, type, message, stackTrace)); + } + + static void OnLateUpdate() + { + // process queued logs on main thread + while (logs.TryDequeue(out LogEntry entry)) + { + switch (entry.type) + { + // add [Thread#] prefix to make it super obvious where this log message comes from. + // some projects may see unexpected messages that were previously hidden, + // since Unity wouldn't log them without ThreadLog.cs. + case LogType.Log: + Debug.Log($"[Thread{entry.threadId}] {entry.message}\n{entry.stackTrace}"); + break; + case LogType.Warning: + Debug.LogWarning($"[Thread{entry.threadId}] {entry.message}\n{entry.stackTrace}"); + break; + case LogType.Error: + Debug.LogError($"[Thread{entry.threadId}] {entry.message}\n{entry.stackTrace}"); + break; + case LogType.Exception: + Debug.LogError($"[Thread{entry.threadId}] {entry.message}\n{entry.stackTrace}"); + break; + case LogType.Assert: + Debug.LogAssertion($"[Thread{entry.threadId}] {entry.message}\n{entry.stackTrace}"); + break; + } + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/ThreadLog.cs.meta b/Assets/ImportedAssets/Mirror/Core/Threading/ThreadLog.cs.meta new file mode 100644 index 0000000000..3d4ece5d14 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/ThreadLog.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 22360406b3844808b0a305486758a703 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Threading/ThreadLog.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/WorkerThread.cs b/Assets/ImportedAssets/Mirror/Core/Threading/WorkerThread.cs new file mode 100644 index 0000000000..4b037c0bf4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/WorkerThread.cs @@ -0,0 +1,165 @@ +// worker thread for Unity (mischa 2022) +// thread with proper exception handling, profling, init, cleanup, etc. for Unity. +// use this from main thread. +using System; +using System.Diagnostics; +using System.Threading; +using UnityEngine.Profiling; +using Debug = UnityEngine.Debug; + +namespace Mirror +{ + public class WorkerThread + { + readonly Thread thread; + + protected volatile bool active; + + // stopwatch so we don't need to use Unity's Time (engine independent) + readonly Stopwatch watch = new Stopwatch(); + + // callbacks need to be set after constructor. + // inheriting classes can't pass their member funcs to base ctor. + // don't set them while the thread is running! + public Action Init; + public Action Tick; + public Action Cleanup; + + public WorkerThread(string identifier) + { + // start the thread wrapped in safety guard + // if main application terminates, this thread needs to terminate too + thread = new Thread( + () => Guard(identifier) + ); + thread.IsBackground = true; + } + + public void Start() + { + // only if thread isn't already running + if (thread.IsAlive) + { + Debug.LogWarning("WorkerThread is still active, can't start it again."); + return; + } + + active = true; + thread.Start(); + } + + // signal the thread to stop gracefully. + // returns immediately, but the thread may take a while to stop. + // may be overwritten to clear more flags like 'computing' etc. + public virtual void SignalStop() => active = false; + + // wait for the thread to fully stop + public bool StopBlocking(float timeout) + { + // only if alive + if (!thread.IsAlive) return true; + + // double precision for long running servers. + watch.Restart(); + + // signal to stop + SignalStop(); + + // wait while thread is still alive + while (IsAlive) + { + // simply wait.. + Thread.Sleep(0); + + // deadlock detection + if (watch.Elapsed.TotalSeconds >= timeout) + { + // force kill all threads as last resort to stop them. + // return false to indicate deadlock. + Interrupt(); + return false; + } + } + return true; + } + + public bool IsAlive => thread.IsAlive; + + // signal an interrupt in the thread. + // this function is very safe to use. + // https://stackoverflow.com/questions/5950994/thread-abort-vs-thread-interrupt + // + // note this does not always kill the thread: + // "If this thread is not currently blocked in a wait, sleep, or join + // state, it will be interrupted when it next begins to block." + // https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.interrupt?view=net-6.0 + // + // in other words, "while (true) {}" wouldn't throw an interrupt exception. + // and that's _okay_. using interrupt is safe & best practice. + // => Unity still aborts deadlocked threads on script reload. + // => and we catch + warn on AbortException. + public void Interrupt() => thread.Interrupt(); + + // thread constructor needs callbacks. + // always define them, and make them call actions. + // those can be set at any time. + void OnInit() => Init?.Invoke(); + void OnTick() => Tick?.Invoke(); + void OnCleanup() => Cleanup?.Invoke(); + + // guarded wrapper for thread code. + // catches exceptions which would otherwise be silent. + // shows in Unity profiler. + // etc. + public void Guard(string identifier) + { + try + { + // log when work begins = thread starts. + // very important for debugging threads. + Debug.Log($"{identifier}: started."); + + // show this thread in Unity profiler + Profiler.BeginThreadProfiling("Mirror Worker Threads", $"{identifier}"); + + // run init once + OnInit(); + + // run thread func while active + while (active) + { + OnTick(); + } + } + // Thread.Interrupt() will gracefully raise a InterruptedException. + catch (ThreadInterruptedException) + { + Debug.Log($"{identifier}: interrupted. That's okay."); + } + // Unity domain reload will cause a ThreadAbortException. + // for example, when saving a changed script while in play mode. + catch (ThreadAbortException) + { + Debug.LogWarning($"{identifier}: aborted. This may happen after domain reload. That's okay."); + } + catch (Exception e) + { + Debug.LogException(e); + } + finally + { + // run cleanup (if any) + active = false; + OnCleanup(); + + // remove this thread from Unity profiler + Profiler.EndThreadProfiling(); + + // log when work ends = thread terminates. + // very important for debugging threads. + // 'finally' to log no matter what (even if exceptions) + Debug.Log($"{identifier}: ended."); + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Threading/WorkerThread.cs.meta b/Assets/ImportedAssets/Mirror/Core/Threading/WorkerThread.cs.meta new file mode 100644 index 0000000000..68e3bdbf70 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Threading/WorkerThread.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 605fa1d7e32f40a08e5549bb43fc5c07 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Threading/WorkerThread.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools.meta b/Assets/ImportedAssets/Mirror/Core/Tools.meta new file mode 100644 index 0000000000..8319cae3b3 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d9c73cc2749d43268600b80df0b55c4d +timeCreated: 1667486812 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/AccurateInterval.cs b/Assets/ImportedAssets/Mirror/Core/Tools/AccurateInterval.cs new file mode 100644 index 0000000000..9d2ce0e9c3 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/AccurateInterval.cs @@ -0,0 +1,86 @@ +// accurate interval from Mirror II. +// for sync / send intervals where it matters. +// does not(!) do catch-up. +// +// first, let's understand the problem. +// say we need an interval of 10 Hz, so every 100ms in Update we do: +// if (Time.time >= lastTime + interval) +// { +// lastTime = Time.time; +// ... +// } +// +// this seems fine, but actually Time.time will always be a few ms beyond +// the interval. but since lastTime is reset to Time.time, the remainder +// is always ignored away. +// with fixed tickRate servers (say 30 Hz), the remainder is significant! +// +// in practice if we have a 30 Hz tickRate server with a 30 Hz sendRate, +// the above way to measure the interval would result in a 18-19 Hz sendRate! +// => this is not just a little off. this is _way_ off, by almost half. +// => displaying actual + target tick/send rate will show this very easily. +// +// we need an accurate way to measure intervals for where it matters. +// and it needs to be testable to guarantee results. +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class AccurateInterval + { + // static func instead of storing interval + lastTime struct. + // + don't need to initialize struct ctor with interval in Awake + // + allows for interval changes at runtime too + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Elapsed(double time, double interval, ref double lastTime) + { + // enough time elapsed? + if (time < lastTime + interval) + return false; + + // naive implementation: + //lastTime = time; + + // accurate but doesn't handle heavy load situations: + //lastTime += interval; + + // heavy load edge case: + // * interval is 100ms + // * server is under heavy load, Updates slow down to 1/s + // * Elapsed(1.000) returns true. + // technically 10 intervals have elapsed. + // * server recovers to normal, Updates are every 10ms again + // * Elapsed(1.010) should return false again until 1.100. + // + // increasing lastTime by interval would require 10 more calls + // to ever catch up again: + // lastTime += interval + // + // as result, the next 10 calls to Elapsed would return true. + // Elapsed(1.001) => true + // Elapsed(1.002) => true + // Elapsed(1.003) => true + // ... + // even though technically the delta was not >= interval. + // + // this would keep the server under heavy load, and it may never + // catch-up. this is not ideal for large virtual worlds. + // + // instead, we want to skip multiples of 'interval' and only + // keep the remainder. + // + // see also: AccurateIntervalTests.Slowdown() + + // easy to understand: + //double elapsed = time - lastTime; + //double remainder = elapsed % interval; + //lastTime = time - remainder; + + // easier: set to rounded multiples of interval (fholm). + // long to match double time. + long multiplier = (long)(time / interval); + lastTime = multiplier * interval; + return true; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/AccurateInterval.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/AccurateInterval.cs.meta new file mode 100644 index 0000000000..eca2141f29 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/AccurateInterval.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: c1b18064e25046f28b88db65a4012ec1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/AccurateInterval.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Compression.cs b/Assets/ImportedAssets/Mirror/Core/Tools/Compression.cs new file mode 100644 index 0000000000..d04b566b1b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Compression.cs @@ -0,0 +1,556 @@ +// Quaternion compression from DOTSNET +using System; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + /// Functions to Compress Quaternions and Floats + public static class Compression + { + // divide by precision (functions backported from Mirror II) + // for example, 0.1 cm precision converts '5.0f' float to '50' long. + // + // 'long' instead of 'int' to allow for large enough worlds. + // value / precision exceeds int.max range too easily. + // Convert.ToInt32/64 would throw. + // https://github.com/vis2k/DOTSNET/issues/59 + // + // 'long' and 'int' will result in the same bandwidth though. + // for example, ScaleToLong(10.5, 0.1) = 105. + // int: 0x00000069 + // long: 0x0000000000000069 + // delta compression will reduce both to 1 byte. + // + // returns + // 'true' if scaling was possible within 'long' bounds. + // 'false' if clamping was necessary. + // never throws. checking result is optional. + public static bool ScaleToLong(float value, float precision, out long result) + { + // user might try to pass precision = 0 to disable rounding. + // this is not supported. + // throw to make the user fix this immediately. + // otherwise we would have to reinterpret-cast if ==0 etc. + // this function should be kept simple. + // if rounding isn't wanted, this function shouldn't be called. + if (precision == 0) throw new DivideByZeroException($"ScaleToLong: precision=0 would cause null division. If rounding isn't wanted, don't call this function."); + + // catch OverflowException if value/precision > long.max. + // attackers should never be able to throw exceptions. + try + { + result = Convert.ToInt64(value / precision); + return true; + } + // clamp to .max/.min. + // returning '0' would make far away entities reset to origin. + // returning 'max' would keep them stuck at the end of the world. + // the latter is much easier to debug. + catch (OverflowException) + { + result = value > 0 ? long.MaxValue : long.MinValue; + return false; + } + } + + // returns + // 'true' if scaling was possible within 'long' bounds. + // 'false' if clamping was necessary. + // never throws. checking result is optional. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ScaleToLong(Vector3 value, float precision, out long x, out long y, out long z) + { + // attempt to convert every component. + // do not return early if one conversion returned 'false'. + // the return value is optional. always attempt to convert all. + bool result = true; + result &= ScaleToLong(value.x, precision, out x); + result &= ScaleToLong(value.y, precision, out y); + result &= ScaleToLong(value.z, precision, out z); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ScaleToLong(Vector3 value, float precision, out Vector3Long quantized) + { + quantized = Vector3Long.zero; + return ScaleToLong(value, precision, out quantized.x, out quantized.y, out quantized.z); + } + + // multiple by precision. + // for example, 0.1 cm precision converts '50' long to '5.0f' float. + public static float ScaleToFloat(long value, float precision) + { + // user might try to pass precision = 0 to disable rounding. + // this is not supported. + // throw to make the user fix this immediately. + // otherwise we would have to reinterpret-cast if ==0 etc. + // this function should be kept simple. + // if rounding isn't wanted, this function shouldn't be called. + if (precision == 0) throw new DivideByZeroException($"ScaleToLong: precision=0 would cause null division. If rounding isn't wanted, don't call this function."); + + return value * precision; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 ScaleToFloat(long x, long y, long z, float precision) + { + Vector3 v; + v.x = ScaleToFloat(x, precision); + v.y = ScaleToFloat(y, precision); + v.z = ScaleToFloat(z, precision); + return v; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 ScaleToFloat(Vector3Long value, float precision) => + ScaleToFloat(value.x, value.y, value.z, precision); + + // scale a float within min/max range to an ushort between min/max range + // note: can also use this for byte range from byte.MinValue to byte.MaxValue + public static ushort ScaleFloatToUShort(float value, float minValue, float maxValue, ushort minTarget, ushort maxTarget) + { + // note: C# ushort - ushort => int, hence so many casts + // max ushort - min ushort only fits into something bigger + int targetRange = maxTarget - minTarget; + float valueRange = maxValue - minValue; + float valueRelative = value - minValue; + return (ushort)(minTarget + (ushort)(valueRelative / valueRange * targetRange)); + } + + // scale an ushort within min/max range to a float between min/max range + // note: can also use this for byte range from byte.MinValue to byte.MaxValue + public static float ScaleUShortToFloat(ushort value, ushort minValue, ushort maxValue, float minTarget, float maxTarget) + { + // note: C# ushort - ushort => int, hence so many casts + float targetRange = maxTarget - minTarget; + ushort valueRange = (ushort)(maxValue - minValue); + ushort valueRelative = (ushort)(value - minValue); + return minTarget + (valueRelative / (float)valueRange * targetRange); + } + + // quaternion compression ////////////////////////////////////////////// + // smallest three: https://gafferongames.com/post/snapshot_compression/ + // compresses 16 bytes quaternion into 4 bytes + + // helper function to find largest absolute element + // returns the index of the largest one + public static int LargestAbsoluteComponentIndex(Vector4 value, out float largestAbs, out Vector3 withoutLargest) + { + // convert to abs + Vector4 abs = new Vector4(Mathf.Abs(value.x), Mathf.Abs(value.y), Mathf.Abs(value.z), Mathf.Abs(value.w)); + + // set largest to first abs (x) + largestAbs = abs.x; + withoutLargest = new Vector3(value.y, value.z, value.w); + int largestIndex = 0; + + // compare to the others, starting at second value + // performance for 100k calls + // for-loop: 25ms + // manual checks: 22ms + if (abs.y > largestAbs) + { + largestIndex = 1; + largestAbs = abs.y; + withoutLargest = new Vector3(value.x, value.z, value.w); + } + if (abs.z > largestAbs) + { + largestIndex = 2; + largestAbs = abs.z; + withoutLargest = new Vector3(value.x, value.y, value.w); + } + if (abs.w > largestAbs) + { + largestIndex = 3; + largestAbs = abs.w; + withoutLargest = new Vector3(value.x, value.y, value.z); + } + + return largestIndex; + } + + const float QuaternionMinRange = -0.707107f; + const float QuaternionMaxRange = 0.707107f; + const ushort TenBitsMax = 0b11_1111_1111; + + // note: assumes normalized quaternions + public static uint CompressQuaternion(Quaternion q) + { + // note: assuming normalized quaternions is enough. no need to force + // normalize here. we already normalize when decompressing. + + // find the largest component index [0,3] + value + int largestIndex = LargestAbsoluteComponentIndex(new Vector4(q.x, q.y, q.z, q.w), out float _, out Vector3 withoutLargest); + + // from here on, we work with the 3 components without largest! + + // "You might think you need to send a sign bit for [largest] in + // case it is negative, but you don’t, because you can make + // [largest] always positive by negating the entire quaternion if + // [largest] is negative. in quaternion space (x,y,z,w) and + // (-x,-y,-z,-w) represent the same rotation." + if (q[largestIndex] < 0) + withoutLargest = -withoutLargest; + + // put index & three floats into one integer. + // => index is 2 bits (4 values require 2 bits to store them) + // => the three floats are between [-0.707107,+0.707107] because: + // "If v is the absolute value of the largest quaternion + // component, the next largest possible component value occurs + // when two components have the same absolute value and the + // other two components are zero. The length of that quaternion + // (v,v,0,0) is 1, therefore v^2 + v^2 = 1, 2v^2 = 1, + // v = 1/sqrt(2). This means you can encode the smallest three + // components in [-0.707107,+0.707107] instead of [-1,+1] giving + // you more precision with the same number of bits." + // => the article recommends storing each float in 9 bits + // => our uint has 32 bits, so we might as well store in (32-2)/3=10 + // 10 bits max value: 1023=0x3FF (use OSX calc to flip 10 bits) + ushort aScaled = ScaleFloatToUShort(withoutLargest.x, QuaternionMinRange, QuaternionMaxRange, 0, TenBitsMax); + ushort bScaled = ScaleFloatToUShort(withoutLargest.y, QuaternionMinRange, QuaternionMaxRange, 0, TenBitsMax); + ushort cScaled = ScaleFloatToUShort(withoutLargest.z, QuaternionMinRange, QuaternionMaxRange, 0, TenBitsMax); + + // now we just need to pack them into one integer + // -> index is 2 bit and needs to be shifted to 31..32 + // -> a is 10 bit and needs to be shifted 20..30 + // -> b is 10 bit and needs to be shifted 10..20 + // -> c is 10 bit and needs to be at 0..10 + return (uint)(largestIndex << 30 | aScaled << 20 | bScaled << 10 | cScaled); + } + + // Quaternion normalizeSAFE from ECS math.normalizesafe() + // => useful to produce valid quaternions even if client sends invalid + // data + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static Quaternion QuaternionNormalizeSafe(Quaternion value) + { + // The smallest positive normal number representable in a float. + const float FLT_MIN_NORMAL = 1.175494351e-38F; + + Vector4 v = new Vector4(value.x, value.y, value.z, value.w); + float length = Vector4.Dot(v, v); + return length > FLT_MIN_NORMAL + ? value.normalized + : Quaternion.identity; + } + + // note: gives normalized quaternions + public static Quaternion DecompressQuaternion(uint data) + { + // get cScaled which is at 0..10 and ignore the rest + ushort cScaled = (ushort)(data & TenBitsMax); + + // get bScaled which is at 10..20 and ignore the rest + ushort bScaled = (ushort)((data >> 10) & TenBitsMax); + + // get aScaled which is at 20..30 and ignore the rest + ushort aScaled = (ushort)((data >> 20) & TenBitsMax); + + // get 2 bit largest index, which is at 31..32 + int largestIndex = (int)(data >> 30); + + // scale back to floats + float a = ScaleUShortToFloat(aScaled, 0, TenBitsMax, QuaternionMinRange, QuaternionMaxRange); + float b = ScaleUShortToFloat(bScaled, 0, TenBitsMax, QuaternionMinRange, QuaternionMaxRange); + float c = ScaleUShortToFloat(cScaled, 0, TenBitsMax, QuaternionMinRange, QuaternionMaxRange); + + // calculate the omitted component based on a²+b²+c²+d²=1 + float d = Mathf.Sqrt(1 - a*a - b*b - c*c); + + // reconstruct based on largest index + Vector4 value; + switch (largestIndex) + { + case 0: value = new Vector4(d, a, b, c); break; + case 1: value = new Vector4(a, d, b, c); break; + case 2: value = new Vector4(a, b, d, c); break; + default: value = new Vector4(a, b, c, d); break; + } + + // ECS Rotation only works with normalized quaternions. + // make sure that's always the case here to avoid ECS bugs where + // everything stops moving if the quaternion isn't normalized. + // => NormalizeSafe returns a normalized quaternion even if we pass + // in NaN from deserializing invalid values! + return QuaternionNormalizeSafe(new Quaternion(value.x, value.y, value.z, value.w)); + } + + // varint compression ////////////////////////////////////////////////// + // helper function to predict varint size for a given number. + // useful when checking if a message + size header will fit, etc. + public static int VarUIntSize(ulong value) + { + if (value <= 240) + return 1; + if (value <= 2287) + return 2; + if (value <= 67823) + return 3; + if (value <= 16777215) + return 4; + if (value <= 4294967295) + return 5; + if (value <= 1099511627775) + return 6; + if (value <= 281474976710655) + return 7; + if (value <= 72057594037927935) + return 8; + return 9; + } + + // helper function to predict varint size for a given number. + // useful when checking if a message + size header will fit, etc. + public static int VarIntSize(long value) + { + // CompressVarInt zigzags it first + ulong zigzagged = (ulong)((value >> 63) ^ (value << 1)); + return VarUIntSize(zigzagged); + } + + // compress ulong varint. + // same result for ulong, uint, ushort and byte. only need one function. + // NOT an extension. otherwise weaver might accidentally use it. + public static void CompressVarUInt(NetworkWriter writer, ulong value) + { + // straight forward implementation: + // keep this for understanding & debugging. + /* + if (value <= 240) + { + writer.WriteByte((byte)value); + return; + } + if (value <= 2287) + { + writer.WriteByte((byte)(((value - 240) >> 8) + 241)); + writer.WriteByte((byte)((value - 240) & 0xFF)); + return; + } + if (value <= 67823) + { + writer.WriteByte((byte)249); + writer.WriteByte((byte)((value - 2288) >> 8)); + writer.WriteByte((byte)((value - 2288) & 0xFF)); + return; + } + if (value <= 16777215) + { + writer.WriteByte((byte)250); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + return; + } + if (value <= 4294967295) + { + writer.WriteByte((byte)251); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + return; + } + if (value <= 1099511627775) + { + writer.WriteByte((byte)252); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + writer.WriteByte((byte)((value >> 32) & 0xFF)); + return; + } + if (value <= 281474976710655) + { + writer.WriteByte((byte)253); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + writer.WriteByte((byte)((value >> 32) & 0xFF)); + writer.WriteByte((byte)((value >> 40) & 0xFF)); + return; + } + if (value <= 72057594037927935) + { + writer.WriteByte((byte)254); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + writer.WriteByte((byte)((value >> 32) & 0xFF)); + writer.WriteByte((byte)((value >> 40) & 0xFF)); + writer.WriteByte((byte)((value >> 48) & 0xFF)); + return; + } + + // all others + { + writer.WriteByte((byte)255); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + writer.WriteByte((byte)((value >> 32) & 0xFF)); + writer.WriteByte((byte)((value >> 40) & 0xFF)); + writer.WriteByte((byte)((value >> 48) & 0xFF)); + writer.WriteByte((byte)((value >> 56) & 0xFF)); + } + */ + + // faster implementation writes multiple bytes at once. + // avoids extra Space, WriteBlittable overhead. + // VarInt is in hot path, performance matters here. + if (value <= 240) + { + byte a = (byte)value; + writer.WriteByte(a); + return; + } + if (value <= 2287) + { + byte a = (byte)(((value - 240) >> 8) + 241); + byte b = (byte)((value - 240) & 0xFF); + writer.WriteUShort((ushort)(b << 8 | a)); + return; + } + if (value <= 67823) + { + byte a = (byte)249; + byte b = (byte)((value - 2288) >> 8); + byte c = (byte)((value - 2288) & 0xFF); + writer.WriteByte(a); + writer.WriteUShort((ushort)(c << 8 | b)); + return; + } + if (value <= 16777215) + { + byte a = (byte)250; + uint b = (uint)(value << 8); + writer.WriteUInt(b | a); + return; + } + if (value <= 4294967295) + { + byte a = (byte)251; + uint b = (uint)value; + writer.WriteByte(a); + writer.WriteUInt(b); + return; + } + if (value <= 1099511627775) + { + byte a = (byte)252; + byte b = (byte)(value & 0xFF); + uint c = (uint)(value >> 8); + writer.WriteUShort((ushort)(b << 8 | a)); + writer.WriteUInt(c); + return; + } + if (value <= 281474976710655) + { + byte a = (byte)253; + byte b = (byte)(value & 0xFF); + byte c = (byte)((value >> 8) & 0xFF); + uint d = (uint)(value >> 16); + writer.WriteByte(a); + writer.WriteUShort((ushort)(c << 8 | b)); + writer.WriteUInt(d); + return; + } + if (value <= 72057594037927935) + { + byte a = 254; + ulong b = value << 8; + writer.WriteULong(b | a); + return; + } + + // all others + { + writer.WriteByte(255); + writer.WriteULong(value); + } + } + + // zigzag encoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CompressVarInt(NetworkWriter writer, long i) + { + ulong zigzagged = (ulong)((i >> 63) ^ (i << 1)); + CompressVarUInt(writer, zigzagged); + } + + // NOT an extension. otherwise weaver might accidentally use it. + public static ulong DecompressVarUInt(NetworkReader reader) + { + byte a0 = reader.ReadByte(); + if (a0 < 241) + { + return a0; + } + + byte a1 = reader.ReadByte(); + if (a0 <= 248) + { + return 240 + ((a0 - (ulong)241) << 8) + a1; + } + + byte a2 = reader.ReadByte(); + if (a0 == 249) + { + return 2288 + ((ulong)a1 << 8) + a2; + } + + byte a3 = reader.ReadByte(); + if (a0 == 250) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16); + } + + byte a4 = reader.ReadByte(); + if (a0 == 251) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24); + } + + byte a5 = reader.ReadByte(); + if (a0 == 252) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32); + } + + byte a6 = reader.ReadByte(); + if (a0 == 253) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32) + (((ulong)a6) << 40); + } + + byte a7 = reader.ReadByte(); + if (a0 == 254) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32) + (((ulong)a6) << 40) + (((ulong)a7) << 48); + } + + byte a8 = reader.ReadByte(); + if (a0 == 255) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32) + (((ulong)a6) << 40) + (((ulong)a7) << 48) + (((ulong)a8) << 56); + } + + throw new IndexOutOfRangeException($"DecompressVarInt failure: {a0}"); + } + + // zigzag decoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long DecompressVarInt(NetworkReader reader) + { + ulong data = DecompressVarUInt(reader); + return ((long)(data >> 1)) ^ -((long)data & 1); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Compression.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/Compression.cs.meta new file mode 100644 index 0000000000..952a95df89 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Compression.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 5c28963f9c4b97e418252a55500fb91e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/Compression.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/DeltaCompression.cs b/Assets/ImportedAssets/Mirror/Core/Tools/DeltaCompression.cs new file mode 100644 index 0000000000..a59370a2b1 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/DeltaCompression.cs @@ -0,0 +1,38 @@ +// manual delta compression for some types. +// varint(b-a) +// Mirror can't use Mirror II's bit-tree delta compression. +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class DeltaCompression + { + // delta (usually small), then zigzag varint to support +- changes + // parameter order: (last, current) makes most sense (Q3 does this too). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Compress(NetworkWriter writer, long last, long current) => + Compression.CompressVarInt(writer, current - last); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long Decompress(NetworkReader reader, long last) => + last + Compression.DecompressVarInt(reader); + + // delta (usually small), then zigzag varint to support +- changes + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Compress(NetworkWriter writer, Vector3Long last, Vector3Long current) + { + Compress(writer, last.x, current.x); + Compress(writer, last.y, current.y); + Compress(writer, last.z, current.z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long Decompress(NetworkReader reader, Vector3Long last) + { + long x = Decompress(reader, last.x); + long y = Decompress(reader, last.y); + long z = Decompress(reader, last.z); + return new Vector3Long(x, y, z); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/DeltaCompression.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/DeltaCompression.cs.meta new file mode 100644 index 0000000000..6d629b2129 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/DeltaCompression.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 6b8f3fffcb4754c15bc5ed4c33e2497b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/DeltaCompression.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/ExponentialMovingAverage.cs b/Assets/ImportedAssets/Mirror/Core/Tools/ExponentialMovingAverage.cs new file mode 100644 index 0000000000..674abb8c16 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/ExponentialMovingAverage.cs @@ -0,0 +1,53 @@ +// N-day EMA implementation from Mirror with a few changes (struct etc.) +// it calculates an exponential moving average roughly equivalent to the last n observations +// https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average +using System; + +namespace Mirror +{ + public struct ExponentialMovingAverage + { + readonly double alpha; + bool initialized; + + public double Value; + public double Variance; + public double StandardDeviation; // absolute value, see test + + public ExponentialMovingAverage(int n) + { + // standard N-day EMA alpha calculation + alpha = 2.0 / (n + 1); + initialized = false; + Value = 0; + Variance = 0; + StandardDeviation = 0; + } + + public void Add(double newValue) + { + // simple algorithm for EMA described here: + // https://en.wikipedia.org/wiki/Moving_average#Exponentially_weighted_moving_variance_and_standard_deviation + if (initialized) + { + double delta = newValue - Value; + Value += alpha * delta; + Variance = (1 - alpha) * (Variance + alpha * delta * delta); + StandardDeviation = Math.Sqrt(Variance); + } + else + { + Value = newValue; + initialized = true; + } + } + + public void Reset() + { + initialized = false; + Value = 0; + Variance = 0; + StandardDeviation = 0; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/ExponentialMovingAverage.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/ExponentialMovingAverage.cs.meta new file mode 100644 index 0000000000..7142e3921b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/ExponentialMovingAverage.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 05e858cbaa54b4ce4a48c8c7f50c1914 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/ExponentialMovingAverage.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Extensions.cs b/Assets/ImportedAssets/Mirror/Core/Tools/Extensions.cs new file mode 100644 index 0000000000..cd29a2a6e8 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Extensions.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Net; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + public static class Extensions + { + public static string ToHexString(this ArraySegment segment) => + BitConverter.ToString(segment.Array, segment.Offset, segment.Count); + + // string.GetHashCode is not guaranteed to be the same on all + // machines, but we need one that is the same on all machines. + // Uses fnv1a as hash function for more uniform distribution http://www.isthe.com/chongo/tech/comp/fnv/ + // Tests: https://softwareengineering.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed + // NOTE: Do not call this from hot path because it's slow O(N) for long method names. + // - As of 2012-02-16 There are 2 design-time callers (weaver) and 1 runtime caller that caches. + public static int GetStableHashCode(this string text) + { + unchecked + { + uint hash = 0x811c9dc5; + uint prime = 0x1000193; + + for (int i = 0; i < text.Length; ++i) + { + byte value = (byte)text[i]; + hash = hash ^ value; + hash *= prime; + } + + //UnityEngine.Debug.Log($"Created stable hash {(ushort)hash} for {text}"); + return (int)hash; + } + } + + // smaller version of our GetStableHashCode. + // careful, this significantly increases chance of collisions. + public static ushort GetStableHashCode16(this string text) + { + // deterministic hash + int hash = GetStableHashCode(text); + + // Gets the 32bit fnv1a hash + // To get it down to 16bit but still reduce hash collisions we cant just cast it to ushort + // Instead we take the highest 16bits of the 32bit hash and fold them with xor into the lower 16bits + // This will create a more uniform 16bit hash, the method is described in: + // http://www.isthe.com/chongo/tech/comp/fnv/ in section "Changing the FNV hash size - xor-folding" + return (ushort)((hash >> 16) ^ hash); + } + + // previously in DotnetCompatibility.cs + // leftover from the UNET days. supposedly for windows store? + internal static string GetMethodName(this Delegate func) + { +#if NETFX_CORE + return func.GetMethodInfo().Name; +#else + return func.Method.Name; +#endif + } + + // helper function to copy to List + // C# only provides CopyTo(T[]) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CopyTo(this IEnumerable source, List destination) + { + // foreach allocates. use AddRange. + destination.AddRange(source); + } + +#if !UNITY_2021_OR_NEWER + // Unity 2020 and earlier don't have Queue.TryDequeue which we need for batching. + public static bool TryDequeue(this Queue source, out T element) + { + if (source.Count > 0) + { + element = source.Dequeue(); + return true; + } + + element = default; + return false; + } +#endif + +#if !UNITY_2021_OR_NEWER + // Unity 2020 and earlier don't have ConcurrentQueue.Clear which we need for ThreadedTransport. + public static void Clear(this ConcurrentQueue source) + { + // while count > 0 risks deadlock if other thread write at the same time. + // our safest solution is a best-effort approach to clear 'Count' once. + int count = source.Count; // get it only once + for (int i = 0; i < count; ++i) + { + source.TryDequeue(out _); + } + } +#endif + +#if !UNITY_2022_0_OR_NEWER + // Some patch versions of Unity 2021.3 and earlier don't have transform.GetPositionAndRotation which we use for performance in some places + public static void GetPositionAndRotation(this Transform transform, out Vector3 position, out Quaternion rotation) + { + position = transform.position; + rotation = transform.rotation; + } +#endif + + // IPEndPoint address only to pretty string. + // useful for to get a connection's address for IP bans etc. + public static string PrettyAddress(this IPEndPoint endPoint) + { + if (endPoint == null) return ""; + + // Map to IPv4 if "IsIPv4MappedToIPv6" for readability + // "::ffff:127.0.0.1" -> "127.0.0.1" + return + endPoint.Address.IsIPv4MappedToIPv6 + ? endPoint.Address.MapToIPv4().ToString() + : endPoint.Address.ToString(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Extensions.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/Extensions.cs.meta new file mode 100644 index 0000000000..54b7e81e26 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Extensions.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: decf32fd053744d18f35712b7a6f5116 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/Extensions.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Mathd.cs b/Assets/ImportedAssets/Mirror/Core/Tools/Mathd.cs new file mode 100644 index 0000000000..374471a9d5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Mathd.cs @@ -0,0 +1,32 @@ +// 'double' precision variants for some of Unity's Mathf functions. +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class Mathd + { + // Unity 2020 doesn't have Math.Clamp yet. + /// Clamps value between 0 and 1 and returns value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double Clamp(double value, double min, double max) + { + if (value < min) return min; + if (value > max) return max; + return value; + } + + /// Clamps value between 0 and 1 and returns value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double Clamp01(double value) => Clamp(value, 0, 1); + + /// Calculates the linear parameter t that produces the interpolant value within the range [a, b]. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double InverseLerp(double a, double b, double value) => + a != b ? Clamp01((value - a) / (b - a)) : 0; + + /// Linearly interpolates between a and b by t with no limit to t. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double LerpUnclamped(double a, double b, double t) => + a + (b - a) * t; + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Mathd.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/Mathd.cs.meta new file mode 100644 index 0000000000..a163a57e46 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Mathd.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 5f74084b91c74df2839b426c4a381373 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/Mathd.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Pool.cs b/Assets/ImportedAssets/Mirror/Core/Tools/Pool.cs new file mode 100644 index 0000000000..f26d49b11c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Pool.cs @@ -0,0 +1,48 @@ +// Pool to avoid allocations (from libuv2k) +// API consistent with Microsoft's ObjectPool. +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public class Pool + { + // Mirror is single threaded, no need for concurrent collections. + // stack increases the chance that a reused writer remains in cache. + readonly Stack objects = new Stack(); + + // some types might need additional parameters in their constructor, so + // we use a Func generator + readonly Func objectGenerator; + + public Pool(Func objectGenerator, int initialCapacity) + { + this.objectGenerator = objectGenerator; + + // allocate an initial pool so we have fewer (if any) + // allocations in the first few frames (or seconds). + for (int i = 0; i < initialCapacity; ++i) + objects.Push(objectGenerator()); + } + + // take an element from the pool, or create a new one if empty + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T Get() => objects.Count > 0 ? objects.Pop() : objectGenerator(); + + // return an element to the pool + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Return(T item) + { + // make sure we can't accidentally insert null values into the pool. + // debugging this would be hard since it would only show on get(). + if (item == null) + throw new ArgumentNullException(nameof(item)); + + objects.Push(item); + } + + // count to see how many objects are in the pool. useful for tests. + public int Count => objects.Count; + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Pool.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/Pool.cs.meta new file mode 100644 index 0000000000..950c888446 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Pool.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 845bb05fa349344c3811022f4f15dfbc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/Pool.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Readme.txt b/Assets/ImportedAssets/Mirror/Core/Tools/Readme.txt new file mode 100644 index 0000000000..09bd920f37 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Readme.txt @@ -0,0 +1 @@ +Standalone algorithms & structs to help build Mirror. \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Readme.txt.meta b/Assets/ImportedAssets/Mirror/Core/Tools/Readme.txt.meta new file mode 100644 index 0000000000..2a2493fe31 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Readme.txt.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: da033671de7d49e0838223a997c56bf1 +timeCreated: 1667486850 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/Readme.txt + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/TimeSample.cs b/Assets/ImportedAssets/Mirror/Core/Tools/TimeSample.cs new file mode 100644 index 0000000000..111e9719f2 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/TimeSample.cs @@ -0,0 +1,61 @@ +// TimeSample from Mirror II. +// simple profiling sample, averaged for display in statistics. +// usable in builds without unitiy profiler overhead etc. +// +// .average may safely be called from main thread while Begin/End is in another. +// i.e. worker threads, transport, etc. +using System.Diagnostics; +using System.Threading; + +namespace Mirror +{ + public struct TimeSample + { + // UnityEngine.Time isn't thread safe. use stopwatch instead. + readonly Stopwatch watch; + + // remember when Begin was called + double beginTime; + + // keep accumulating times over the given interval. + // (not readonly. we modify its contents.) + ExponentialMovingAverage ema; + + // average in seconds. + // code often runs in sub-millisecond time. float is more precise. + // + // set with Interlocked for thread safety. + // can be read from main thread while sampling happens in other thread. + public double average; // THREAD SAFE + + // average over N begin/end captures + public TimeSample(int n) + { + watch = new Stopwatch(); + watch.Start(); + ema = new ExponentialMovingAverage(n); + beginTime = 0; + average = 0; + } + + // begin is called before the code to be sampled + public void Begin() + { + // remember when Begin was called. + // keep StopWatch running so we can average over the given interval. + beginTime = watch.Elapsed.TotalSeconds; + // Debug.Log($"Begin @ {beginTime:F4}"); + } + + // end is called after the code to be sampled + public void End() + { + // add duration in seconds to accumulated durations + double elapsed = watch.Elapsed.TotalSeconds - beginTime; + ema.Add(elapsed); + + // expose new average thread safely + Interlocked.Exchange(ref average, ema.Value); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/TimeSample.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/TimeSample.cs.meta new file mode 100644 index 0000000000..0542d3dd41 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/TimeSample.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 26c32f6429554546a88d800c846c74ed +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/TimeSample.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Utils.cs b/Assets/ImportedAssets/Mirror/Core/Tools/Utils.cs new file mode 100644 index 0000000000..406484f34e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Utils.cs @@ -0,0 +1,222 @@ +using System; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.SceneManagement; + +namespace Mirror +{ + // Handles network messages on client and server + public delegate void NetworkMessageDelegate(NetworkConnection conn, NetworkReader reader, int channelId); + + // Handles requests to spawn objects on the client + public delegate GameObject SpawnDelegate(Vector3 position, uint assetId); + + public delegate GameObject SpawnHandlerDelegate(SpawnMessage msg); + + // Handles requests to unspawn objects on the client + public delegate void UnSpawnDelegate(GameObject spawned); + + // channels are const ints instead of an enum so people can add their own + // channels (can't extend an enum otherwise). + // + // note that Mirror is slowly moving towards quake style networking which + // will only require reliable for handshake, and unreliable for the rest. + // so eventually we can change this to an Enum and transports shouldn't + // add custom channels anymore. + public static class Channels + { + public const int Reliable = 0; // ordered + public const int Unreliable = 1; // unordered + } + + public static class Utils + { + // detect headless / dedicated server mode + // SystemInfo.graphicsDeviceType is never null in the editor. + // UNITY_SERVER works in builds for all Unity versions 2019 LTS and later. + // For Unity 2019 / 2020, there is no way to detect Server Build checkbox + // state in Build Settings, so they never auto-start headless server / client. + // UNITY_SERVER works in the editor in Unity 2021 LTS and later + // because that's when Dedicated Server platform was added. + // It is intentional for editor play mode to auto-start headless server / client + // when Dedicated Server platform is selected in the editor so that editor + // acts like a headless build to every extent possible for testing / debugging. + public static bool IsHeadless() => +#if UNITY_SERVER + true; +#else + SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null; +#endif + + // detect WebGL mode + public const bool IsWebGL = +#if UNITY_WEBGL + true; +#else + false; +#endif + + // detect Debug mode + public const bool IsDebug = +#if DEBUG + true; +#else + false; +#endif + + public static uint GetTrueRandomUInt() + { + // use Crypto RNG to avoid having time based duplicates + using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) + { + byte[] bytes = new byte[4]; + rng.GetBytes(bytes); + return BitConverter.ToUInt32(bytes, 0); + } + } + + public static bool IsPrefab(GameObject obj) + { +#if UNITY_EDITOR + return UnityEditor.PrefabUtility.IsPartOfPrefabAsset(obj); +#else + return false; +#endif + } + + // simplified IsSceneObject check from Mirror II + public static bool IsSceneObject(NetworkIdentity identity) + { + // original UNET / Mirror still had the IsPersistent check. + // it never fires though. even for Prefabs dragged to the Scene. + // (see Scene Objects example scene.) + // #if UNITY_EDITOR + // if (UnityEditor.EditorUtility.IsPersistent(identity.gameObject)) + // return false; + // #endif + + return identity.gameObject.hideFlags != HideFlags.NotEditable && + identity.gameObject.hideFlags != HideFlags.HideAndDontSave && + identity.sceneId != 0; + } + + public static bool IsSceneObjectWithPrefabParent(GameObject gameObject, out GameObject prefab) + { + prefab = null; + +#if UNITY_EDITOR + if (!UnityEditor.PrefabUtility.IsPartOfPrefabInstance(gameObject)) + { + return false; + } + prefab = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject); +#endif + + if (prefab == null) + { + Debug.LogError($"Failed to find prefab parent for scene object [name:{gameObject.name}]"); + return false; + } + return true; + } + + // is a 2D point in screen? (from ummorpg) + // (if width = 1024, then indices from 0..1023 are valid (=1024 indices) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsPointInScreen(Vector2 point) => + 0 <= point.x && point.x < Screen.width && + 0 <= point.y && point.y < Screen.height; + + // pretty print bytes as KB/MB/GB/etc. from DOTSNET + // long to support > 2GB + // divides by floats to return "2.5MB" etc. + public static string PrettyBytes(long bytes) + { + // bytes + if (bytes < 1024) + return $"{bytes} B"; + // kilobytes + else if (bytes < 1024L * 1024L) + return $"{(bytes / 1024f):F2} KB"; + // megabytes + else if (bytes < 1024 * 1024L * 1024L) + return $"{(bytes / (1024f * 1024f)):F2} MB"; + // gigabytes + return $"{(bytes / (1024f * 1024f * 1024f)):F2} GB"; + } + + // pretty print seconds as hours:minutes:seconds(.milliseconds/100)s. + // double for long running servers. + public static string PrettySeconds(double seconds) + { + TimeSpan t = TimeSpan.FromSeconds(seconds); + string res = ""; + if (t.Days > 0) res += $"{t.Days}d"; + if (t.Hours > 0) res += $"{(res.Length > 0 ? " " : "")}{t.Hours}h"; + if (t.Minutes > 0) res += $"{(res.Length > 0 ? " " : "")}{t.Minutes}m"; + // 0.5s, 1.5s etc. if any milliseconds. 1s, 2s etc. if any seconds + if (t.Milliseconds > 0) res += $"{(res.Length > 0 ? " " : "")}{t.Seconds}.{(t.Milliseconds / 100)}s"; + else if (t.Seconds > 0) res += $"{(res.Length > 0 ? " " : "")}{t.Seconds}s"; + // if the string is still empty because the value was '0', then at least + // return the seconds instead of returning an empty string + return res != "" ? res : "0s"; + } + + // universal .spawned function + public static NetworkIdentity GetSpawnedInServerOrClient(uint netId) + { + // server / host mode: use the one from server. + // host mode has access to all spawned. + if (NetworkServer.active) + { + NetworkServer.spawned.TryGetValue(netId, out NetworkIdentity entry); + return entry; + } + + // client + if (NetworkClient.active) + { + NetworkClient.spawned.TryGetValue(netId, out NetworkIdentity entry); + return entry; + } + + return null; + } + + // keep a GUI window in screen. + // for example. if it's at x=1000 and screen is resized to w=500, + // it won't get lost in the invisible area etc. + public static Rect KeepInScreen(Rect rect) + { + // ensure min + rect.x = Math.Max(rect.x, 0); + rect.y = Math.Max(rect.y, 0); + + // ensure max + rect.x = Math.Min(rect.x, Screen.width - rect.width); + rect.y = Math.Min(rect.y, Screen.width - rect.height); + + return rect; + } + + // create local connections pair and connect them + public static void CreateLocalConnections( + out LocalConnectionToClient connectionToClient, + out LocalConnectionToServer connectionToServer) + { + connectionToServer = new LocalConnectionToServer(); + connectionToClient = new LocalConnectionToClient(); + connectionToServer.connectionToClient = connectionToClient; + connectionToClient.connectionToServer = connectionToServer; + } + + public static bool IsSceneActive(string scene) + { + Scene activeScene = SceneManager.GetActiveScene(); + return activeScene.path == scene || + activeScene.name == scene; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Utils.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/Utils.cs.meta new file mode 100644 index 0000000000..52cc9d9a91 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Utils.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: b530ce39098b54374a29ad308c8e4554 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/Utils.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Vector3Long.cs b/Assets/ImportedAssets/Mirror/Core/Tools/Vector3Long.cs new file mode 100644 index 0000000000..d54a46c2cf --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Vector3Long.cs @@ -0,0 +1,125 @@ +#pragma warning disable CS0659 // 'Vector3Long' overrides Object.Equals(object o) but does not override Object.GetHashCode() +#pragma warning disable CS0661 // 'Vector3Long' defines operator == or operator != but does not override Object.GetHashCode() + +// Vector3Long by mischa (based on game engine project) +using System; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public struct Vector3Long + { + public long x; + public long y; + public long z; + + public static readonly Vector3Long zero = new Vector3Long(0, 0, 0); + public static readonly Vector3Long one = new Vector3Long(1, 1, 1); + public static readonly Vector3Long forward = new Vector3Long(0, 0, 1); + public static readonly Vector3Long back = new Vector3Long(0, 0, -1); + public static readonly Vector3Long left = new Vector3Long(-1, 0, 0); + public static readonly Vector3Long right = new Vector3Long(1, 0, 0); + public static readonly Vector3Long up = new Vector3Long(0, 1, 0); + public static readonly Vector3Long down = new Vector3Long(0, -1, 0); + + // constructor ///////////////////////////////////////////////////////// + public Vector3Long(long x, long y, long z) + { + this.x = x; + this.y = y; + this.z = z; + } + + // operators /////////////////////////////////////////////////////////// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator +(Vector3Long a, Vector3Long b) => + new Vector3Long(a.x + b.x, a.y + b.y, a.z + b.z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator -(Vector3Long a, Vector3Long b) => + new Vector3Long(a.x - b.x, a.y - b.y, a.z - b.z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator -(Vector3Long v) => + new Vector3Long(-v.x, -v.y, -v.z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator *(Vector3Long a, long n) => + new Vector3Long(a.x * n, a.y * n, a.z * n); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator *(long n, Vector3Long a) => + new Vector3Long(a.x * n, a.y * n, a.z * n); + + // == returns true if approximately equal (with epsilon). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Vector3Long a, Vector3Long b) => + a.x == b.x && + a.y == b.y && + a.z == b.z; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Vector3Long a, Vector3Long b) => !(a == b); + + // NO IMPLICIT System.Numerics.Vector3Long conversion because double<->float + // would silently lose precision in large worlds. + + // [i] component index. useful for iterating all components etc. + public long this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + switch (index) + { + case 0: return x; + case 1: return y; + case 2: return z; + default: throw new IndexOutOfRangeException($"Vector3Long[{index}] out of range."); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + switch (index) + { + case 0: + x = value; + break; + case 1: + y = value; + break; + case 2: + z = value; + break; + default: throw new IndexOutOfRangeException($"Vector3Long[{index}] out of range."); + } + } + } + + // instance functions ////////////////////////////////////////////////// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string ToString() => $"({x} {y} {z})"; + + // equality //////////////////////////////////////////////////////////// + // implement Equals & HashCode explicitly for performance. + // calling .Equals (instead of "==") checks for exact equality. + // (API compatibility) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(Vector3Long other) => + x == other.x && y == other.y && z == other.z; + + // Equals(object) can reuse Equals(Vector4) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool Equals(object other) => + other is Vector3Long vector4 && Equals(vector4); + +#if UNITY_2021_3_OR_NEWER + // Unity 2019/2020 don't have HashCode.Combine yet. + // this is only to avoid reflection. without defining, it works too. + // default generated by rider + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int GetHashCode() => HashCode.Combine(x, y, z); +#endif + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Tools/Vector3Long.cs.meta b/Assets/ImportedAssets/Mirror/Core/Tools/Vector3Long.cs.meta new file mode 100644 index 0000000000..4e6f4bc586 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Tools/Vector3Long.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 18efa4e349254185ad257401dd24628b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Tools/Vector3Long.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/Transport.cs b/Assets/ImportedAssets/Mirror/Core/Transport.cs new file mode 100644 index 0000000000..a20d84f788 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Transport.cs @@ -0,0 +1,204 @@ +// For future reference, here is what Transports need to do in Mirror: +// +// Connecting: +// * Transports are responsible to call either OnConnected || OnDisconnected +// in a certain time after a Connect was called. It can not end in limbo. +// +// Disconnecting: +// * Connections might disconnect voluntarily by the other end. +// * Connections might be disconnect involuntarily by the server. +// * Either way, Transports need to detect it and call OnDisconnected. +// +// Timeouts: +// * Transports should expose a configurable timeout +// * Transports are responsible for calling OnDisconnected after a timeout +// +// Channels: +// * Default channel is Reliable, as in reliable ordered (OR DISCONNECT) +// * Where possible, Unreliable should be supported (unordered, no guarantee) +// +// Other: +// * Transports functions are all bound to the main thread. +// (Transports can use other threads in the background if they manage them) +// * Transports should only process messages while the component is enabled. +// +using System; +using UnityEngine; + +namespace Mirror +{ + /// Abstract transport layer component + public abstract class Transport : MonoBehaviour + { + /// The current transport used by Mirror. + public static Transport active; + + /// Is this transport available in the current platform? + public abstract bool Available(); + + /// Is this transported encrypted for secure communication? + public virtual bool IsEncrypted => false; + + /// If encrypted, which cipher is used? + public virtual string EncryptionCipher => ""; + + // client ////////////////////////////////////////////////////////////// + /// Called by Transport when the client connected to the server. + public Action OnClientConnected; + + /// Called by Transport when the client received a message from the server. + public Action, int> OnClientDataReceived; + + /// Called by Transport when the client sent a message to the server. + // Transports are responsible for calling it because: + // - groups it together with OnReceived responsibility + // - allows transports to decide if anything was sent or not + // - allows transports to decide the actual used channel (i.e. tcp always sending reliable) + public Action, int> OnClientDataSent; + + /// Called by Transport when the client encountered an error. + public Action OnClientError; + + /// Called by Transport when the client encountered an error. + public Action OnClientTransportException; + + /// Called by Transport when the client disconnected from the server. + public Action OnClientDisconnected; + + // server ////////////////////////////////////////////////////////////// + /// Called by Transport when a new client connected to the server. + public Action OnServerConnected; + + /// Called by Transport when the server received a message from a client. + public Action, int> OnServerDataReceived; + + /// Called by Transport when the server sent a message to a client. + // Transports are responsible for calling it because: + // - groups it together with OnReceived responsibility + // - allows transports to decide if anything was sent or not + // - allows transports to decide the actual used channel (i.e. tcp always sending reliable) + public Action, int> OnServerDataSent; + + /// Called by Transport when a server's connection encountered a problem. + /// If a Disconnect will also be raised, raise the Error first. + public Action OnServerError; + + /// Called by Transport when a server's connection encountered a problem. + /// If a Disconnect will also be raised, raise the Error first. + public Action OnServerTransportException; + + /// Called by Transport when a client disconnected from the server. + public Action OnServerDisconnected; + + // client functions //////////////////////////////////////////////////// + /// True if the client is currently connected to the server. + public abstract bool ClientConnected(); + + /// Connects the client to the server at the address. + public abstract void ClientConnect(string address); + + /// Connects the client to the server at the Uri. + public virtual void ClientConnect(Uri uri) + { + // By default, to keep backwards compatibility, just connect to the host + // in the uri + ClientConnect(uri.Host); + } + + /// Sends a message to the server over the given channel. + // The ArraySegment is only valid until returning. Copy if needed. + public abstract void ClientSend(ArraySegment segment, int channelId = Channels.Reliable); + + /// Disconnects the client from the server + public abstract void ClientDisconnect(); + + // server functions //////////////////////////////////////////////////// + /// Returns server address as Uri. + // Useful for NetworkDiscovery. + public abstract Uri ServerUri(); + + /// True if the server is currently listening for connections. + public abstract bool ServerActive(); + + /// Start listening for connections. + public abstract void ServerStart(); + + /// Send a message to a client over the given channel. + public abstract void ServerSend(int connectionId, ArraySegment segment, int channelId = Channels.Reliable); + + /// Disconnect a client from the server. + public abstract void ServerDisconnect(int connectionId); + + /// Get a client's address on the server. + // Can be useful for Game Master IP bans etc. + public abstract string ServerGetClientAddress(int connectionId); + + /// Stop listening and disconnect all connections. + public abstract void ServerStop(); + + /// Maximum message size for the given channel. + // Different channels often have different sizes, ranging from MTU to + // several megabytes. + // + // Needs to return a value at all times, even if the Transport isn't + // running or available because it's needed for initializations. + public abstract int GetMaxPacketSize(int channelId = Channels.Reliable); + + /// Recommended Batching threshold for this transport. + // Uses GetMaxPacketSize by default. + // Some transports like kcp support large max packet sizes which should + // not be used for batching all the time because they end up being too + // slow (head of line blocking etc.). + public virtual int GetBatchThreshold(int channelId = Channels.Reliable) + { + return GetMaxPacketSize(channelId); + } + + // block Update & LateUpdate to show warnings if Transports still use + // them instead of using + // Client/ServerEarlyUpdate: to process incoming messages + // Client/ServerLateUpdate: to process outgoing messages + // those are called by NetworkClient/Server at the right time. + // + // allows transports to implement the proper network update order of: + // process_incoming() + // update_world() + // process_outgoing() + // + // => see NetworkLoop.cs for detailed explanations! +#pragma warning disable UNT0001 // Empty Unity message + public void Update() {} + public void LateUpdate() {} +#pragma warning restore UNT0001 // Empty Unity message + + /// + /// NetworkLoop NetworkEarly/LateUpdate were added for a proper network + /// update order. the goal is to: + /// process_incoming() + /// update_world() + /// process_outgoing() + /// in order to avoid unnecessary latency and data races. + /// + // => split into client and server parts so that we can cleanly call + // them from NetworkClient/Server + // => VIRTUAL for now so we can take our time to convert transports + // without breaking anything. + public virtual void ClientEarlyUpdate() {} + public virtual void ServerEarlyUpdate() {} + public virtual void ClientLateUpdate() {} + public virtual void ServerLateUpdate() {} + + /// Shut down the transport, both as client and server + public abstract void Shutdown(); + + /// Called by Unity when quitting. Inheriting Transports should call base for proper Shutdown. + public virtual void OnApplicationQuit() + { + // stop transport (e.g. to shut down threads) + // (when pressing Stop in the Editor, Unity keeps threads alive + // until we press Start again. so if Transports use threads, we + // really want them to end now and not after next start) + Shutdown(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/Transport.cs.meta b/Assets/ImportedAssets/Mirror/Core/Transport.cs.meta new file mode 100644 index 0000000000..0fdc14216d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/Transport.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: cfffcac25d6d64ced9de620159e221b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/Transport.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/TransportError.cs b/Assets/ImportedAssets/Mirror/Core/TransportError.cs new file mode 100644 index 0000000000..b45201529f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/TransportError.cs @@ -0,0 +1,17 @@ +// Mirror transport error code enum. +// most transport implementations should use a subset of this, +// and then translate the transport error codes to mirror error codes. +namespace Mirror +{ + public enum TransportError : byte + { + DnsResolve, // failed to resolve a host name + Refused, // connection refused by other end. server full etc. + Timeout, // ping timeout or dead link + Congestion, // more messages than transport / network can process + InvalidReceive, // recv invalid packet (possibly intentional attack) + InvalidSend, // user tried to send invalid data + ConnectionClosed, // connection closed voluntarily or lost involuntarily + Unexpected // unexpected error / exception, requires fix. + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/TransportError.cs.meta b/Assets/ImportedAssets/Mirror/Core/TransportError.cs.meta new file mode 100644 index 0000000000..899b4295c4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/TransportError.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: ce162bdedd704db9b8c35d163f0c1d54 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/TransportError.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Core/WeaverFuse.cs b/Assets/ImportedAssets/Mirror/Core/WeaverFuse.cs new file mode 100644 index 0000000000..f850323f99 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/WeaverFuse.cs @@ -0,0 +1,22 @@ +// safety fuse for weaver to flip. +// runtime can check this to ensure weaving succeded. +// otherwise running server/client would give lots of random 'writer not found' etc. errors. +// this is much cleaner. +// +// note that ILPostProcessor errors already block entering playmode. +// however, issues could still stop the weaving from running at all. +// WeaverFuse can check if it actually ran. +namespace Mirror +{ + public static class WeaverFuse + { + // this trick only works for ILPostProcessor. + // CompilationFinishedHook can't weaver Mirror.dll. + public static bool Weaved() => +#if UNITY_2020_3_OR_NEWER + false; +#else + true; +#endif + } +} diff --git a/Assets/ImportedAssets/Mirror/Core/WeaverFuse.cs.meta b/Assets/ImportedAssets/Mirror/Core/WeaverFuse.cs.meta new file mode 100644 index 0000000000..6671489e67 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Core/WeaverFuse.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 4de3dfbcbd2e41fcac947c04bcac52c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Core/WeaverFuse.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/AndroidManifestHelper.cs b/Assets/ImportedAssets/Mirror/Editor/AndroidManifestHelper.cs new file mode 100644 index 0000000000..c76359a8a9 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/AndroidManifestHelper.cs @@ -0,0 +1,113 @@ +// Android NetworkDiscovery Multicast fix +// https://github.com/vis2k/Mirror/pull/2887 +using UnityEditor; +using UnityEngine; +using UnityEditor.Build; +using UnityEditor.Build.Reporting; +using System.Xml; +using System.IO; +#if UNITY_ANDROID +using UnityEditor.Android; +#endif + + +[InitializeOnLoad] +public class AndroidManifestHelper : IPreprocessBuildWithReport, IPostprocessBuildWithReport +#if UNITY_ANDROID + , IPostGenerateGradleAndroidProject +#endif +{ + public int callbackOrder { get { return 99999; } } + +#if UNITY_ANDROID + public void OnPostGenerateGradleAndroidProject(string path) + { + string manifestFolder = Path.Combine(path, "src/main"); + string sourceFile = manifestFolder + "/AndroidManifest.xml"; + // Load android manifest file + XmlDocument doc = new XmlDocument(); + doc.Load(sourceFile); + + string androidNamepsaceURI; + XmlElement element = (XmlElement)doc.SelectSingleNode("/manifest"); + if (element == null) + { + UnityEngine.Debug.LogError("Could not find manifest tag in android manifest."); + return; + } + + // Get android namespace URI from the manifest + androidNamepsaceURI = element.GetAttribute("xmlns:android"); + if (string.IsNullOrEmpty(androidNamepsaceURI)) + { + UnityEngine.Debug.LogError("Could not find Android Namespace in manifest."); + return; + } + AddOrRemoveTag(doc, + androidNamepsaceURI, + "/manifest", + "uses-permission", + "android.permission.CHANGE_WIFI_MULTICAST_STATE", + true, + false); + AddOrRemoveTag(doc, + androidNamepsaceURI, + "/manifest", + "uses-permission", + "android.permission.INTERNET", + true, + false); + doc.Save(sourceFile); + } +#endif + + static void AddOrRemoveTag(XmlDocument doc, string @namespace, string path, string elementName, string name, bool required, bool modifyIfFound, params string[] attrs) // name, value pairs + { + var nodes = doc.SelectNodes(path + "/" + elementName); + XmlElement element = null; + foreach (XmlElement e in nodes) + { + if (name == null || name == e.GetAttribute("name", @namespace)) + { + element = e; + break; + } + } + + if (required) + { + if (element == null) + { + var parent = doc.SelectSingleNode(path); + element = doc.CreateElement(elementName); + element.SetAttribute("name", @namespace, name); + parent.AppendChild(element); + } + + for (int i = 0; i < attrs.Length; i += 2) + { + if (modifyIfFound || string.IsNullOrEmpty(element.GetAttribute(attrs[i], @namespace))) + { + if (attrs[i + 1] != null) + { + element.SetAttribute(attrs[i], @namespace, attrs[i + 1]); + } + else + { + element.RemoveAttribute(attrs[i], @namespace); + } + } + } + } + else + { + if (element != null && modifyIfFound) + { + element.ParentNode.RemoveChild(element); + } + } + } + + public void OnPostprocessBuild(BuildReport report) {} + public void OnPreprocessBuild(BuildReport report) {} +} diff --git a/Assets/ImportedAssets/Mirror/Editor/AndroidManifestHelper.cs.meta b/Assets/ImportedAssets/Mirror/Editor/AndroidManifestHelper.cs.meta new file mode 100644 index 0000000000..40970fe239 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/AndroidManifestHelper.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 80cc70189403d7444bbffd185ca28462 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/AndroidManifestHelper.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/EditorHelper.cs b/Assets/ImportedAssets/Mirror/Editor/EditorHelper.cs new file mode 100644 index 0000000000..c3551ab1e2 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/EditorHelper.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + public static class EditorHelper + { + public static string FindPath() + { + string typeName = typeof(T).Name; + + string[] guidsFound = AssetDatabase.FindAssets($"t:Script {typeName}"); + if (guidsFound.Length >= 1 && !string.IsNullOrWhiteSpace(guidsFound[0])) + { + if (guidsFound.Length > 1) + { + Debug.LogWarning($"Found more than one{typeName}"); + } + + string path = AssetDatabase.GUIDToAssetPath(guidsFound[0]); + return Path.GetDirectoryName(path); + } + else + { + Debug.LogError($"Could not find path of {typeName}"); + return string.Empty; + } + } + + + public static IEnumerable IterateOverProject(string filter) + { + foreach (string guid in AssetDatabase.FindAssets(filter)) + { + yield return AssetDatabase.GUIDToAssetPath(guid); + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/EditorHelper.cs.meta b/Assets/ImportedAssets/Mirror/Editor/EditorHelper.cs.meta new file mode 100644 index 0000000000..0ec87249ff --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/EditorHelper.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: dba787f167ff29c4288532af1ec3584c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/EditorHelper.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Empty.meta b/Assets/ImportedAssets/Mirror/Editor/Empty.meta new file mode 100644 index 0000000000..ee87976437 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Empty.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 62c8dc5bb12bbc6428bb66ccbac57000 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs b/Assets/ImportedAssets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs new file mode 100644 index 0000000000..18ab111517 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs @@ -0,0 +1 @@ +// removed 2021-12-12 diff --git a/Assets/ImportedAssets/Mirror/Editor/EnterPlayModeSettingsCheck.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/EnterPlayModeSettingsCheck.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/LogLevelWindow.cs b/Assets/ImportedAssets/Mirror/Editor/Empty/LogLevelWindow.cs similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/LogLevelWindow.cs rename to Assets/ImportedAssets/Mirror/Editor/Empty/LogLevelWindow.cs diff --git a/Assets/ImportedAssets/Mirror/Editor/LogLevelWindow.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Empty/LogLevelWindow.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/LogLevelWindow.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Empty/LogLevelWindow.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Logging.meta b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Logging.meta rename to Assets/ImportedAssets/Mirror/Editor/Empty/Logging.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelWindow.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelWindow.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelsGUI.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelsGUI.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Editor/Logging/LogSettingsEditor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Logging/LogSettingsEditor.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Editor/Logging/NetworkLogSettingsEditor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Logging/NetworkLogSettingsEditor.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Empty/ScriptableObjectUtility.cs b/Assets/ImportedAssets/Mirror/Editor/Empty/ScriptableObjectUtility.cs new file mode 100644 index 0000000000..39b95f7d8e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Empty/ScriptableObjectUtility.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/ImportedAssets/Mirror/Editor/ScriptableObjectUtility.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Empty/ScriptableObjectUtility.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/ScriptableObjectUtility.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Empty/ScriptableObjectUtility.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Empty/SyncVarDrawer.cs b/Assets/ImportedAssets/Mirror/Editor/Empty/SyncVarDrawer.cs new file mode 100644 index 0000000000..aaa3b9d67a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Empty/SyncVarDrawer.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/ImportedAssets/Mirror/Editor/Empty/SyncVarDrawer.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Empty/SyncVarDrawer.cs.meta new file mode 100644 index 0000000000..0ee91aa4e0 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Empty/SyncVarDrawer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 874812594431423b84f763b987ff9681 +timeCreated: 1632553007 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/EnterPlayModeSettingsCheck.cs b/Assets/ImportedAssets/Mirror/Editor/EnterPlayModeSettingsCheck.cs deleted file mode 100644 index 30b1acd422..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/EnterPlayModeSettingsCheck.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Unity 2019.3 has an experimental 'disable domain reload on play' -// feature. keeping any global state between sessions will break -// Mirror and most of our user's projects. don't allow it for now. -// https://blogs.unity3d.com/2019/11/05/enter-play-mode-faster-in-unity-2019-3/ -using UnityEditor; -using UnityEngine; - -namespace Mirror -{ - public class EnterPlayModeSettingsCheck : MonoBehaviour - { - [InitializeOnLoadMethod] - static void OnInitializeOnLoad() - { -#if UNITY_2019_3_OR_NEWER - // We can't support experimental "Enter Play Mode Options" mode - // Check immediately on load, and before entering play mode, and warn the user - CheckPlayModeOptions(); -#endif - - // Hook this event to see if we have a good weave every time - // user attempts to enter play mode or tries to do a build - EditorApplication.playModeStateChanged += OnPlayModeStateChanged; - } - - static void OnPlayModeStateChanged(PlayModeStateChange state) - { - // Per Unity docs, this fires "when exiting edit mode before the Editor is in play mode". - // This doesn't fire when closing the editor. - if (state == PlayModeStateChange.ExitingEditMode) - { - CheckSuccessfulWeave(); - -#if UNITY_2019_3_OR_NEWER - // We can't support experimental "Enter Play Mode Options" mode - // Check and prevent entering play mode if enabled - CheckPlayModeOptions(); -#endif - } - } - - static void CheckSuccessfulWeave() - { - // Check if last weave result was successful - if (!SessionState.GetBool("MIRROR_WEAVE_SUCCESS", false)) - { - // Last weave result was a failure...try to weave again - // Faults will show in the console that may have been cleared by "Clear on Play" - SessionState.SetBool("MIRROR_WEAVE_SUCCESS", true); - Weaver.CompilationFinishedHook.WeaveExistingAssemblies(); - - // Did that clear things up for us? - if (!SessionState.GetBool("MIRROR_WEAVE_SUCCESS", false)) - { - // Nope, still failed, and console has the issues logged - Debug.LogError("Can't enter play mode until weaver issues are resolved."); - EditorApplication.isPlaying = false; - } - } - } - -#if UNITY_2019_3_OR_NEWER - static void CheckPlayModeOptions() - { - // enabling the checkbox is enough. it controls all the other settings. - if (EditorSettings.enterPlayModeOptionsEnabled) - { - Debug.LogError("Enter Play Mode Options are not supported by Mirror. Please disable 'ProjectSettings -> Editor -> Enter Play Mode Settings (Experimental)'."); - EditorApplication.isPlaying = false; - } - } -#endif - } -} diff --git a/Assets/ImportedAssets/Mirror/Icon.meta b/Assets/ImportedAssets/Mirror/Editor/Icon.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Icon.meta rename to Assets/ImportedAssets/Mirror/Editor/Icon.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Icon/MirrorIcon.png b/Assets/ImportedAssets/Mirror/Editor/Icon/MirrorIcon.png new file mode 100644 index 0000000000..1be896157a Binary files /dev/null and b/Assets/ImportedAssets/Mirror/Editor/Icon/MirrorIcon.png differ diff --git a/Assets/ImportedAssets/Mirror/Icon/MirrorIcon.png.meta b/Assets/ImportedAssets/Mirror/Editor/Icon/MirrorIcon.png.meta similarity index 92% rename from Assets/ImportedAssets/Mirror/Icon/MirrorIcon.png.meta rename to Assets/ImportedAssets/Mirror/Editor/Icon/MirrorIcon.png.meta index 8049382f36..d6884f26c4 100644 --- a/Assets/ImportedAssets/Mirror/Icon/MirrorIcon.png.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Icon/MirrorIcon.png.meta @@ -108,3 +108,10 @@ TextureImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Icon/MirrorIcon.png + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/InspectorHelper.cs b/Assets/ImportedAssets/Mirror/Editor/InspectorHelper.cs index 40d2f1ef48..80b3a063ff 100644 --- a/Assets/ImportedAssets/Mirror/Editor/InspectorHelper.cs +++ b/Assets/ImportedAssets/Mirror/Editor/InspectorHelper.cs @@ -7,12 +7,8 @@ namespace Mirror { public static class InspectorHelper { - /// - /// Gets all public and private fields for a type - /// - /// - /// Stops at this base type (exclusive) - /// + /// Gets all public and private fields for a type + // deepestBaseType: Stops at this base type (exclusive) public static IEnumerable GetAllFields(Type type, Type deepestBaseType) { const BindingFlags publicFields = BindingFlags.Public | BindingFlags.Instance; @@ -49,25 +45,30 @@ public static bool IsSyncVar(this FieldInfo field) object[] fieldMarkers = field.GetCustomAttributes(typeof(SyncVarAttribute), true); return fieldMarkers.Length > 0; } + public static bool IsSerializeField(this FieldInfo field) { object[] fieldMarkers = field.GetCustomAttributes(typeof(SerializeField), true); return fieldMarkers.Length > 0; } + public static bool IsVisibleField(this FieldInfo field) { return field.IsPublic || IsSerializeField(field); } - public static bool IsSyncObject(this FieldInfo field) + public static bool ImplementsInterface(this FieldInfo field) { - return typeof(SyncObject).IsAssignableFrom(field.FieldType); + return typeof(T).IsAssignableFrom(field.FieldType); } + public static bool HasShowInInspector(this FieldInfo field) { object[] fieldMarkers = field.GetCustomAttributes(typeof(ShowInInspectorAttribute), true); return fieldMarkers.Length > 0; } + + // checks if SyncObject is public or has our custom [ShowInInspector] field public static bool IsVisibleSyncObject(this FieldInfo field) { return field.IsPublic || HasShowInInspector(field); diff --git a/Assets/ImportedAssets/Mirror/Editor/InspectorHelper.cs.meta b/Assets/ImportedAssets/Mirror/Editor/InspectorHelper.cs.meta index 852ff71218..dcfc64b557 100644 --- a/Assets/ImportedAssets/Mirror/Editor/InspectorHelper.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/InspectorHelper.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/InspectorHelper.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/LagCompensatorInspector.cs b/Assets/ImportedAssets/Mirror/Editor/LagCompensatorInspector.cs new file mode 100644 index 0000000000..f706384a8a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/LagCompensatorInspector.cs @@ -0,0 +1,14 @@ +using UnityEditor; + +namespace Mirror +{ + [CustomEditor(typeof(LagCompensator))] + public class LagCompensatorInspector : Editor + { + public override void OnInspectorGUI() + { + EditorGUILayout.HelpBox("Preview Component - Feedback appreciated on GitHub or Discord!", MessageType.Warning); + DrawDefaultInspector(); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/LagCompensatorInspector.cs.meta b/Assets/ImportedAssets/Mirror/Editor/LagCompensatorInspector.cs.meta new file mode 100644 index 0000000000..e92cdba8c1 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/LagCompensatorInspector.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 703e39b5385ae2e479987ff4ec0707a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/LagCompensatorInspector.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelWindow.cs b/Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelWindow.cs deleted file mode 100644 index 1d80f52ca8..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelWindow.cs +++ /dev/null @@ -1,70 +0,0 @@ -using Mirror.Logging; -using UnityEditor; -using UnityEngine; - -namespace Mirror.EditorScripts.Logging -{ - public class LogLevelWindow : EditorWindow - { - [Header("Log Settings Asset")] - [SerializeField] LogSettings settings = null; - - SerializedObject serializedObject; - SerializedProperty settingsProp; - Vector2 dictionaryScrollPosition; - - void OnEnable() - { - serializedObject = new SerializedObject(this); - settingsProp = serializedObject.FindProperty(nameof(settings)); - - LogSettings existingSettings = EditorLogSettingsLoader.FindLogSettings(); - if (existingSettings != null) - { - settingsProp.objectReferenceValue = existingSettings; - serializedObject.ApplyModifiedProperties(); - } - } - - void OnGUI() - { - using (EditorGUILayout.ScrollViewScope scrollScope = new EditorGUILayout.ScrollViewScope(dictionaryScrollPosition, GUIStyle.none, GUI.skin.verticalScrollbar)) - { - dictionaryScrollPosition = scrollScope.scrollPosition; - - using (new EditorGUILayout.VerticalScope()) - { - using (new EditorGUILayout.VerticalScope()) - { - serializedObject.Update(); - EditorGUILayout.PropertyField(settingsProp); - serializedObject.ApplyModifiedProperties(); - - if (settings == null) - { - LogSettings newSettings = LogLevelsGUI.DrawCreateNewButton(); - if (newSettings != null) - { - settingsProp.objectReferenceValue = newSettings; - serializedObject.ApplyModifiedProperties(); - } - } - else - { - LogLevelsGUI.DrawLogFactoryDictionary(settings); - } - } - } - } - } - - [MenuItem("Window/Analysis/Mirror Log Levels", priority = 20002)] - public static void ShowWindow() - { - LogLevelWindow window = GetWindow(); - window.minSize = new Vector2(200, 100); - window.titleContent = new GUIContent("Mirror Log Levels"); - window.Show(); - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelsGUI.cs b/Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelsGUI.cs deleted file mode 100644 index 2aaa855fe8..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Logging/LogLevelsGUI.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Collections.Generic; -using Mirror.Logging; -using UnityEditor; -using UnityEngine; - -namespace Mirror.EditorScripts.Logging -{ - public static class LogLevelsGUI - { - public static LogSettings DrawCreateNewButton() - { - if (GUILayout.Button("Create New")) - { - return ScriptableObjectUtility.CreateAsset(nameof(LogSettings)); - } - - return null; - } - - public static void DrawLogFactoryDictionary(LogSettings settings) - { - using (EditorGUI.ChangeCheckScope scope = new EditorGUI.ChangeCheckScope()) - { - if (LogFactory.loggers.Count == 0) - { - EditorGUILayout.LabelField("No Keys found in LogFactory.loggers\nPlay the game for default log values to be added to LogFactory", EditorStyles.wordWrappedLabel); - } - else - { - EditorGUILayout.Space(); - EditorGUILayout.LabelField("Logging Components", EditorStyles.boldLabel); - - foreach (KeyValuePair item in LogFactory.loggers) - { - DrawLoggerField(item); - } - - if (scope.changed) - { - settings.SaveFromDictionary(LogFactory.loggers); - } - } - } - } - - static void DrawLoggerField(KeyValuePair item) - { - ILogger logger = item.Value; - string name = item.Key; - - const float fieldWidth = 100f; - const float inspectorMargin = 25f; - - using (new EditorGUILayout.HorizontalScope()) - { - EditorGUILayout.LabelField(new GUIContent(ObjectNames.NicifyVariableName(name)), GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth - fieldWidth - inspectorMargin)); - logger.filterLogType = (LogType)EditorGUILayout.EnumPopup(logger.filterLogType, GUILayout.Width(fieldWidth)); - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Logging/LogSettingsEditor.cs b/Assets/ImportedAssets/Mirror/Editor/Logging/LogSettingsEditor.cs deleted file mode 100644 index 2579ae43e1..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Logging/LogSettingsEditor.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Mirror.Logging; -using UnityEditor; -using UnityEngine; - -namespace Mirror.EditorScripts.Logging -{ - [CustomEditor(typeof(LogSettings))] - public class LogSettingsEditor : Editor - { - public override void OnInspectorGUI() - { - CurrentScriptField(); - - LogLevelsGUI.DrawLogFactoryDictionary(target as LogSettings); - } - - public void CurrentScriptField() - { - GUI.enabled = false; - EditorGUILayout.PropertyField(serializedObject.FindProperty("m_Script")); - GUI.enabled = true; - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Logging/NetworkLogSettingsEditor.cs b/Assets/ImportedAssets/Mirror/Editor/Logging/NetworkLogSettingsEditor.cs deleted file mode 100644 index 56e172fa72..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Logging/NetworkLogSettingsEditor.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Mirror.Logging; -using UnityEditor; - -namespace Mirror.EditorScripts.Logging -{ - [CustomEditor(typeof(NetworkLogSettings))] - public class NetworkLogSettingsEditor : Editor - { - public override void OnInspectorGUI() - { - DrawDefaultInspector(); - - NetworkLogSettings target = this.target as NetworkLogSettings; - - if (target.settings == null) - { - LogSettings newSettings = LogLevelsGUI.DrawCreateNewButton(); - if (newSettings != null) - { - SerializedProperty settingsProp = serializedObject.FindProperty("settings"); - settingsProp.objectReferenceValue = newSettings; - serializedObject.ApplyModifiedProperties(); - } - } - else - { - LogLevelsGUI.DrawLogFactoryDictionary(target.settings); - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Mirror.Editor.asmdef b/Assets/ImportedAssets/Mirror/Editor/Mirror.Editor.asmdef index 3ed7e2f881..800e67b046 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Mirror.Editor.asmdef +++ b/Assets/ImportedAssets/Mirror/Editor/Mirror.Editor.asmdef @@ -1,10 +1,11 @@ { "name": "Mirror.Editor", + "rootNamespace": "", "references": [ - "Mirror", - "Mirror.Weaver" + "GUID:30817c1a0e6d646d99c048fc403f5979", + "GUID:72872094b21c16e48b631b2224833d49", + "GUID:1d0b9d21c3ff546a4aa32399dfd33474" ], - "optionalUnityReferences": [], "includePlatforms": [ "Editor" ], @@ -13,5 +14,7 @@ "overrideReferences": false, "precompiledReferences": [], "autoReferenced": true, - "defineConstraints": [] + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/Mirror.Editor.asmdef.meta b/Assets/ImportedAssets/Mirror/Editor/Mirror.Editor.asmdef.meta index e2e6f2aa7f..8e50d5755f 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Mirror.Editor.asmdef.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Mirror.Editor.asmdef.meta @@ -5,3 +5,10 @@ AssemblyDefinitionImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Mirror.Editor.asmdef + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/NetworkBehaviourInspector.cs b/Assets/ImportedAssets/Mirror/Editor/NetworkBehaviourInspector.cs index 45740a0f3e..52c56d6b69 100644 --- a/Assets/ImportedAssets/Mirror/Editor/NetworkBehaviourInspector.cs +++ b/Assets/ImportedAssets/Mirror/Editor/NetworkBehaviourInspector.cs @@ -1,6 +1,4 @@ using System; -using System.Collections; -using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; @@ -11,12 +9,8 @@ namespace Mirror [CanEditMultipleObjects] public class NetworkBehaviourInspector : Editor { - /// - /// List of all visible syncVars in target class - /// - protected List syncVarNames = new List(); bool syncsAnything; - SyncListDrawer syncListDrawer; + SyncObjectCollectionsDrawer syncObjectCollectionsDrawer; // does this type sync anything? otherwise we don't need to show syncInterval bool SyncsAnything(Type scriptClass) @@ -43,16 +37,14 @@ bool SyncsAnything(Type scriptClass) // is always there even if we don't use SyncObjects. so we need to // search for SyncObjects manually. // Any SyncObject should be added to syncObjects when unity creates an - // object so we can cheeck length of list so see if sync objects exists - FieldInfo syncObjectsField = scriptClass.GetField("syncObjects", BindingFlags.NonPublic | BindingFlags.Instance); - List syncObjects = (List)syncObjectsField.GetValue(serializedObject.targetObject); - - return syncObjects.Count > 0; + // object so we can check length of list so see if sync objects exists + return ((NetworkBehaviour)serializedObject.targetObject).HasSyncObjects(); } void OnEnable() { - if (target == null) { Debug.LogWarning("NetworkBehaviourInspector had no target object"); return; } + // sometimes target is null. just return early. + if (target == null) return; // If target's base class is changed from NetworkBehaviour to MonoBehaviour // then Unity temporarily keep using this Inspector causing things to break @@ -60,16 +52,7 @@ void OnEnable() Type scriptClass = target.GetType(); - syncVarNames = new List(); - foreach (FieldInfo field in InspectorHelper.GetAllFields(scriptClass, typeof(NetworkBehaviour))) - { - if (field.IsSyncVar() && field.IsVisibleField()) - { - syncVarNames.Add(field.Name); - } - } - - syncListDrawer = new SyncListDrawer(serializedObject.targetObject); + syncObjectCollectionsDrawer = new SyncObjectCollectionsDrawer(serializedObject.targetObject); syncsAnything = SyncsAnything(scriptClass); } @@ -77,24 +60,20 @@ void OnEnable() public override void OnInspectorGUI() { DrawDefaultInspector(); - DrawDefaultSyncLists(); + DrawSyncObjectCollections(); DrawDefaultSyncSettings(); } - /// - /// Draws Sync Objects that are IEnumerable - /// - protected void DrawDefaultSyncLists() + // Draws Sync Objects that are IEnumerable + protected void DrawSyncObjectCollections() { - // Need this check incase OnEnable returns early - if (syncListDrawer == null) { return; } + // Need this check in case OnEnable returns early + if (syncObjectCollectionsDrawer == null) return; - syncListDrawer.Draw(); + syncObjectCollectionsDrawer.Draw(); } - /// - /// Draws SyncSettings if the NetworkBehaviour has anything to sync - /// + // Draws SyncSettings if the NetworkBehaviour has anything to sync protected void DrawDefaultSyncSettings() { // does it sync anything? then show extra properties @@ -107,80 +86,19 @@ protected void DrawDefaultSyncSettings() EditorGUILayout.Space(); EditorGUILayout.LabelField("Sync Settings", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(serializedObject.FindProperty("syncMode")); + // sync direction + SerializedProperty syncDirection = serializedObject.FindProperty("syncDirection"); + EditorGUILayout.PropertyField(syncDirection); + + // sync mdoe: only show for ServerToClient components + if (syncDirection.enumValueIndex == (int)SyncDirection.ServerToClient) + EditorGUILayout.PropertyField(serializedObject.FindProperty("syncMode")); + + // sync interval EditorGUILayout.PropertyField(serializedObject.FindProperty("syncInterval")); // apply serializedObject.ApplyModifiedProperties(); } } - public class SyncListDrawer - { - readonly UnityEngine.Object targetObject; - readonly List syncListFields; - - public SyncListDrawer(UnityEngine.Object targetObject) - { - this.targetObject = targetObject; - syncListFields = new List(); - foreach (FieldInfo field in InspectorHelper.GetAllFields(targetObject.GetType(), typeof(NetworkBehaviour))) - { - if (field.IsSyncObject() && field.IsVisibleSyncObject()) - { - syncListFields.Add(new SyncListField(field)); - } - } - } - - public void Draw() - { - if (syncListFields.Count == 0) { return; } - - EditorGUILayout.Space(); - EditorGUILayout.LabelField("Sync Lists", EditorStyles.boldLabel); - - for (int i = 0; i < syncListFields.Count; i++) - { - DrawSyncList(syncListFields[i]); - } - } - - void DrawSyncList(SyncListField syncListField) - { - syncListField.visible = EditorGUILayout.Foldout(syncListField.visible, syncListField.label); - if (syncListField.visible) - { - using (new EditorGUI.IndentLevelScope()) - { - object fieldValue = syncListField.field.GetValue(targetObject); - if (fieldValue is IEnumerable synclist) - { - int index = 0; - foreach (object item in synclist) - { - string itemValue = item != null ? item.ToString() : "NULL"; - string itemLabel = "Element " + index; - EditorGUILayout.LabelField(itemLabel, itemValue); - - index++; - } - } - } - } - } - - class SyncListField - { - public bool visible; - public readonly FieldInfo field; - public readonly string label; - - public SyncListField(FieldInfo field) - { - this.field = field; - visible = false; - label = field.Name + " [" + field.FieldType.Name + "]"; - } - } - } -} //namespace +} diff --git a/Assets/ImportedAssets/Mirror/Editor/NetworkBehaviourInspector.cs.meta b/Assets/ImportedAssets/Mirror/Editor/NetworkBehaviourInspector.cs.meta index 78d9fa8f6b..bbd2c1c00a 100644 --- a/Assets/ImportedAssets/Mirror/Editor/NetworkBehaviourInspector.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/NetworkBehaviourInspector.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/NetworkBehaviourInspector.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/NetworkInformationPreview.cs b/Assets/ImportedAssets/Mirror/Editor/NetworkInformationPreview.cs index 0c302989ed..b4dbe5ea93 100644 --- a/Assets/ImportedAssets/Mirror/Editor/NetworkInformationPreview.cs +++ b/Assets/ImportedAssets/Mirror/Editor/NetworkInformationPreview.cs @@ -73,7 +73,7 @@ public override GUIContent GetPreviewTitle() public override bool HasPreviewGUI() { - // need to check if target is null to stop MissingReferenceException + // need to check if target is null to stop MissingReferenceException return target != null && target is GameObject gameObject && gameObject.GetComponent() != null; } @@ -126,7 +126,9 @@ float DrawNetworkIdentityInfo(NetworkIdentity identity, float initialX, float Y) Vector2 maxValueLabelSize = GetMaxNameLabelSize(infos); Rect labelRect = new Rect(initialX, Y, maxNameLabelSize.x, maxNameLabelSize.y); - Rect idLabelRect = new Rect(maxNameLabelSize.x, Y, maxValueLabelSize.x, maxValueLabelSize.y); + + // height needs a +1 to line up nicely + Rect idLabelRect = new Rect(maxNameLabelSize.x, Y, maxValueLabelSize.x, maxValueLabelSize.y + 1); foreach (NetworkIdentityInfo info in infos) { @@ -171,7 +173,7 @@ float DrawNetworkBehaviors(NetworkIdentity identity, float initialX, float Y) float DrawObservers(NetworkIdentity identity, float initialX, float Y) { - if (identity.observers != null && identity.observers.Count > 0) + if (identity.observers.Count > 0) { Rect observerRect = new Rect(initialX, Y + 10, 200, 20); @@ -180,9 +182,9 @@ float DrawObservers(NetworkIdentity identity, float initialX, float Y) observerRect.x += 20; observerRect.y += observerRect.height; - foreach (KeyValuePair kvp in identity.observers) + foreach (KeyValuePair kvp in identity.observers) { - GUI.Label(observerRect, kvp.Value.address + ":" + kvp.Value, styles.componentName); + GUI.Label(observerRect, $"{kvp.Value.address}:{kvp.Value}", styles.componentName); observerRect.y += observerRect.height; Y = observerRect.y; } @@ -196,7 +198,7 @@ float DrawOwner(NetworkIdentity identity, float initialX, float Y) if (identity.connectionToClient != null) { Rect ownerRect = new Rect(initialX, Y + 10, 400, 20); - GUI.Label(ownerRect, new GUIContent("Client Authority: " + identity.connectionToClient), styles.labelStyle); + GUI.Label(ownerRect, new GUIContent($"Client Authority: {identity.connectionToClient}"), styles.labelStyle); Y += ownerRect.height; } return Y; @@ -252,7 +254,7 @@ IEnumerable GetNetworkIdentityInfo(NetworkIdentity identity infos.Add(GetString("Network ID", identity.netId.ToString())); infos.Add(GetBoolean("Is Client", identity.isClient)); infos.Add(GetBoolean("Is Server", identity.isServer)); - infos.Add(GetBoolean("Has Authority", identity.hasAuthority)); + infos.Add(GetBoolean("Is Owned", identity.isOwned)); infos.Add(GetBoolean("Is Local Player", identity.isLocalPlayer)); } return infos; @@ -277,7 +279,7 @@ IEnumerable GetNetworkBehaviorInfo(NetworkIdentity identit NetworkIdentityInfo GetAssetId(NetworkIdentity identity) { string assetId = identity.assetId.ToString(); - if (string.IsNullOrEmpty(assetId)) + if (string.IsNullOrWhiteSpace(assetId)) { assetId = ""; } diff --git a/Assets/ImportedAssets/Mirror/Editor/NetworkInformationPreview.cs.meta b/Assets/ImportedAssets/Mirror/Editor/NetworkInformationPreview.cs.meta index 9bf2de4d1b..c00939a14f 100644 --- a/Assets/ImportedAssets/Mirror/Editor/NetworkInformationPreview.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/NetworkInformationPreview.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/NetworkInformationPreview.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/NetworkManagerEditor.cs b/Assets/ImportedAssets/Mirror/Editor/NetworkManagerEditor.cs index 315db469ec..82b2b1b9f6 100644 --- a/Assets/ImportedAssets/Mirror/Editor/NetworkManagerEditor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/NetworkManagerEditor.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; +using System.Linq; using UnityEditor; using UnityEditorInternal; using UnityEngine; @@ -9,20 +12,15 @@ namespace Mirror public class NetworkManagerEditor : Editor { SerializedProperty spawnListProperty; - ReorderableList spawnList; - protected NetworkManager networkManager; protected void Init() { if (spawnList == null) { - networkManager = target as NetworkManager; - spawnListProperty = serializedObject.FindProperty("spawnPrefabs"); - spawnList = new ReorderableList(serializedObject, spawnListProperty) { drawHeaderCallback = DrawHeader, @@ -47,6 +45,76 @@ public override void OnInspectorGUI() { serializedObject.ApplyModifiedProperties(); } + + if (GUILayout.Button("Populate Spawnable Prefabs")) + { + ScanForNetworkIdentities(); + } + } + + void ScanForNetworkIdentities() + { + List identities = new List(); + bool cancelled = false; + try + { + string[] paths = EditorHelper.IterateOverProject("t:prefab").ToArray(); + int count = 0; + foreach (string path in paths) + { + // ignore test & example prefabs. + // users sometimes keep the folders in their projects. + if (path.Contains("Mirror/Tests/") || + path.Contains("Mirror/Examples/")) + { + continue; + } + + if (EditorUtility.DisplayCancelableProgressBar("Searching for NetworkIdentities..", + $"Scanned {count}/{paths.Length} prefabs. Found {identities.Count} new ones", + count / (float)paths.Length)) + { + cancelled = true; + break; + } + + count++; + + NetworkIdentity ni = AssetDatabase.LoadAssetAtPath(path); + if (!ni) + { + continue; + } + + if (!networkManager.spawnPrefabs.Contains(ni.gameObject)) + { + identities.Add(ni.gameObject); + } + + } + } + finally + { + + EditorUtility.ClearProgressBar(); + if (!cancelled) + { + // RecordObject is needed for "*" to show up in Scene. + // however, this only saves List.Count without the entries. + Undo.RecordObject(networkManager, "NetworkManager: populated prefabs"); + + // add the entries + networkManager.spawnPrefabs.AddRange(identities); + + // sort alphabetically for better UX + networkManager.spawnPrefabs = networkManager.spawnPrefabs.OrderBy(go => go.name).ToList(); + + // SetDirty is required to save the individual entries properly. + EditorUtility.SetDirty(target); + } + // Loading assets might use a lot of memory, so try to unload them after + Resources.UnloadUnusedAssets(); + } } static void DrawHeader(Rect headerRect) @@ -67,7 +135,7 @@ internal void DrawChild(Rect r, int index, bool isActive, bool isFocused) else { NetworkIdentity identity = go.GetComponent(); - label = new GUIContent(go.name, identity != null ? "AssetId: [" + identity.assetId + "]" : "No Network Identity"); + label = new GUIContent(go.name, identity != null ? $"AssetId: [{identity.assetId}]" : "No Network Identity"); } GameObject newGameObject = (GameObject)EditorGUI.ObjectField(r, label, go, typeof(GameObject), false); @@ -76,7 +144,7 @@ internal void DrawChild(Rect r, int index, bool isActive, bool isFocused) { if (newGameObject != null && !newGameObject.GetComponent()) { - Debug.LogError("Prefab " + newGameObject + " cannot be added as spawnable as it doesn't have a NetworkIdentity."); + Debug.LogError($"Prefab {newGameObject} cannot be added as spawnable as it doesn't have a NetworkIdentity."); return; } prefab.objectReferenceValue = newGameObject; diff --git a/Assets/ImportedAssets/Mirror/Editor/NetworkManagerEditor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/NetworkManagerEditor.cs.meta index 7fe8dbc8b5..ffeabf4628 100644 --- a/Assets/ImportedAssets/Mirror/Editor/NetworkManagerEditor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/NetworkManagerEditor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/NetworkManagerEditor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/NetworkScenePostProcess.cs b/Assets/ImportedAssets/Mirror/Editor/NetworkScenePostProcess.cs index cb663285e8..2fa07d65b7 100644 --- a/Assets/ImportedAssets/Mirror/Editor/NetworkScenePostProcess.cs +++ b/Assets/ImportedAssets/Mirror/Editor/NetworkScenePostProcess.cs @@ -26,16 +26,14 @@ public static void OnPostProcessScene() .Where(identity => identity.gameObject.hideFlags != HideFlags.NotEditable && identity.gameObject.hideFlags != HideFlags.HideAndDontSave && identity.gameObject.scene.name != "DontDestroyOnLoad" && - !PrefabUtility.IsPartOfPrefabAsset(identity.gameObject)); + !Utils.IsPrefab(identity.gameObject)); foreach (NetworkIdentity identity in identities) { // if we had a [ConflictComponent] attribute that would be better than this check. // also there is no context about which scene this is in. if (identity.GetComponent() != null) - { Debug.LogError("NetworkManager has a NetworkIdentity component. This will cause the NetworkManager object to be disabled, so it is not recommended."); - } // not spawned before? // OnPostProcessScene is called after additive scene loads too, @@ -54,7 +52,23 @@ public static void OnPostProcessScene() } // throwing an exception would only show it for one object // because this function would return afterwards. - else Debug.LogError("Scene " + identity.gameObject.scene.path + " needs to be opened and resaved, because the scene object " + identity.name + " has no valid sceneId yet."); + else + { + // there are two cases where sceneId == 0: + // * if we have a prefab open in the prefab scene + // * if an unopened scene needs resaving + // show a proper error message in both cases so the user + // knows what to do. + string path = identity.gameObject.scene.path; + if (string.IsNullOrWhiteSpace(path)) + Debug.LogError($"{identity.name} is currently open in Prefab Edit Mode. Please open the actual scene before launching Mirror."); + else + Debug.LogError($"Scene {path} needs to be opened and resaved, because the scene object {identity.name} has no valid sceneId yet."); + + // either way we shouldn't continue. nothing good will + // happen when trying to launch with invalid sceneIds. + EditorApplication.isPlaying = false; + } } } } @@ -64,28 +78,20 @@ static void PrepareSceneObject(NetworkIdentity identity) // set scene hash identity.SetSceneIdSceneHashPartInternal(); - // disable it + // spawnable scene objects are force disabled on scene load to + // ensure Start/Update/etc. aren't called until actually spawned. + // // note: NetworkIdentity.OnDisable adds itself to the // spawnableObjects dictionary (only if sceneId != 0) identity.gameObject.SetActive(false); // safety check for prefabs with more than one NetworkIdentity -#if UNITY_2018_2_OR_NEWER GameObject prefabGO = PrefabUtility.GetCorrespondingObjectFromSource(identity.gameObject); -#else - GameObject prefabGO = PrefabUtility.GetPrefabParent(identity.gameObject); -#endif if (prefabGO) { -#if UNITY_2018_3_OR_NEWER GameObject prefabRootGO = prefabGO.transform.root.gameObject; -#else - GameObject prefabRootGO = PrefabUtility.FindPrefabRoot(prefabGO); -#endif if (prefabRootGO != null && prefabRootGO.GetComponentsInChildren().Length > 1) - { - Debug.LogWarningFormat("Prefab '{0}' has several NetworkIdentity components attached to itself or its children, this is not supported.", prefabRootGO.name); - } + Debug.LogWarning($"Prefab {prefabRootGO.name} has several NetworkIdentity components attached to itself or its children, this is not supported."); } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/NetworkScenePostProcess.cs.meta b/Assets/ImportedAssets/Mirror/Editor/NetworkScenePostProcess.cs.meta index b567cc9547..2999a9b59e 100644 --- a/Assets/ImportedAssets/Mirror/Editor/NetworkScenePostProcess.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/NetworkScenePostProcess.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/NetworkScenePostProcess.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/ReadOnlyDrawer.cs b/Assets/ImportedAssets/Mirror/Editor/ReadOnlyDrawer.cs new file mode 100644 index 0000000000..4a09707900 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/ReadOnlyDrawer.cs @@ -0,0 +1,19 @@ +using UnityEngine; +using UnityEditor; + +namespace Mirror +{ + [CustomPropertyDrawer(typeof(ReadOnlyAttribute))] + public class ReadOnlyDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + // Cache the current GUI enabled state + bool prevGuiEnabledState = GUI.enabled; + + GUI.enabled = false; + EditorGUI.PropertyField(position, property, label, true); + GUI.enabled = prevGuiEnabledState; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/ReadOnlyDrawer.cs.meta b/Assets/ImportedAssets/Mirror/Editor/ReadOnlyDrawer.cs.meta new file mode 100644 index 0000000000..7fc1b55095 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/ReadOnlyDrawer.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 22f17bdd21f104c41bc175937fefbdec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/ReadOnlyDrawer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/SceneDrawer.cs b/Assets/ImportedAssets/Mirror/Editor/SceneDrawer.cs index a234c3f553..f391684e54 100644 --- a/Assets/ImportedAssets/Mirror/Editor/SceneDrawer.cs +++ b/Assets/ImportedAssets/Mirror/Editor/SceneDrawer.cs @@ -12,12 +12,12 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten { SceneAsset sceneObject = AssetDatabase.LoadAssetAtPath(property.stringValue); - if (sceneObject == null && !string.IsNullOrEmpty(property.stringValue)) + if (sceneObject == null && !string.IsNullOrWhiteSpace(property.stringValue)) { // try to load it from the build settings for legacy compatibility sceneObject = GetBuildSettingsSceneObject(property.stringValue); } - if (sceneObject == null && !string.IsNullOrEmpty(property.stringValue)) + if (sceneObject == null && !string.IsNullOrWhiteSpace(property.stringValue)) { Debug.LogError($"Could not find scene {property.stringValue} in {property.propertyPath}, assign the proper scenes in your NetworkManager"); } @@ -36,7 +36,7 @@ protected SceneAsset GetBuildSettingsSceneObject(string sceneName) foreach (EditorBuildSettingsScene buildScene in EditorBuildSettings.scenes) { SceneAsset sceneAsset = AssetDatabase.LoadAssetAtPath(buildScene.path); - if (sceneAsset.name == sceneName) + if (sceneAsset!= null && sceneAsset.name == sceneName) { return sceneAsset; } diff --git a/Assets/ImportedAssets/Mirror/Editor/SceneDrawer.cs.meta b/Assets/ImportedAssets/Mirror/Editor/SceneDrawer.cs.meta index 6a996dcd92..c8d313dfcc 100644 --- a/Assets/ImportedAssets/Mirror/Editor/SceneDrawer.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/SceneDrawer.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/SceneDrawer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/ScriptableObjectUtility.cs b/Assets/ImportedAssets/Mirror/Editor/ScriptableObjectUtility.cs deleted file mode 100644 index e6a36bd2fa..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/ScriptableObjectUtility.cs +++ /dev/null @@ -1,54 +0,0 @@ -using UnityEditor; -using UnityEngine; - -namespace Mirror.EditorScripts -{ - public static class ScriptableObjectUtility - { - /// - // This makes it easy to create, name and place unique new ScriptableObject asset files. - /// - public static T CreateAsset(string defaultName) where T : ScriptableObject - { - string path = SavePanel(defaultName); - // user click cancel - if (string.IsNullOrEmpty(path)) { return null; } - - T asset = ScriptableObject.CreateInstance(); - - SaveAsset(path, asset); - - return asset; - } - - static string SavePanel(string name) - { - string path = EditorUtility.SaveFilePanel( - "Save ScriptableObject", - "Assets/Mirror/", - name + ".asset", - "asset"); - - // user click cancel, return early - if (string.IsNullOrEmpty(path)) { return path; } - - // Unity only wants path from Assets - if (path.StartsWith(Application.dataPath)) - { - path = "Assets" + path.Substring(Application.dataPath.Length); - } - - return path; - } - - static void SaveAsset(string path, ScriptableObject asset) - { - string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path); - - AssetDatabase.CreateAsset(asset, assetPathAndName); - - AssetDatabase.SaveAssets(); - AssetDatabase.Refresh(); - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/SyncObjectCollectionsDrawer.cs b/Assets/ImportedAssets/Mirror/Editor/SyncObjectCollectionsDrawer.cs new file mode 100644 index 0000000000..735b018da2 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/SyncObjectCollectionsDrawer.cs @@ -0,0 +1,89 @@ +// helper class for NetworkBehaviourInspector to draw all enumerable SyncObjects +// (SyncList/Set/Dictionary) +// 'SyncObjectCollectionsDrawer' is a nicer name than 'IEnumerableSyncObjectsDrawer' +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Text.RegularExpressions; +using UnityEditor; + +namespace Mirror +{ + class SyncObjectCollectionField + { + public bool visible; + public readonly FieldInfo field; + public readonly string label; + + public SyncObjectCollectionField(FieldInfo field) + { + this.field = field; + visible = false; + + // field.FieldType.Name has a backtick and number at the end, e.g. SyncList`1 + // so we split it and only take the first part so it looks nicer. + // e.g. SyncList`1 -> SyncList + // Better to do it one time here than in hot path in OnInspectorGUI + label = $"{field.Name} [{Regex.Replace(field.FieldType.Name, @"`\d+", "")}]"; + } + } + + public class SyncObjectCollectionsDrawer + { + readonly UnityEngine.Object targetObject; + readonly List syncObjectCollectionFields; + + public SyncObjectCollectionsDrawer(UnityEngine.Object targetObject) + { + this.targetObject = targetObject; + syncObjectCollectionFields = new List(); + foreach (FieldInfo field in InspectorHelper.GetAllFields(targetObject.GetType(), typeof(NetworkBehaviour))) + { + // only draw SyncObjects that are IEnumerable (SyncList/Set/Dictionary) + if (field.IsVisibleSyncObject() && + field.ImplementsInterface() && + field.ImplementsInterface()) + { + syncObjectCollectionFields.Add(new SyncObjectCollectionField(field)); + } + } + } + + public void Draw() + { + if (syncObjectCollectionFields.Count == 0) { return; } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Sync Collections", EditorStyles.boldLabel); + + for (int i = 0; i < syncObjectCollectionFields.Count; i++) + { + DrawSyncObjectCollection(syncObjectCollectionFields[i]); + } + } + + void DrawSyncObjectCollection(SyncObjectCollectionField syncObjectCollectionField) + { + syncObjectCollectionField.visible = EditorGUILayout.Foldout(syncObjectCollectionField.visible, syncObjectCollectionField.label); + if (syncObjectCollectionField.visible) + { + using (new EditorGUI.IndentLevelScope()) + { + object fieldValue = syncObjectCollectionField.field.GetValue(targetObject); + if (fieldValue is IEnumerable syncObject) + { + int index = 0; + foreach (object item in syncObject) + { + string itemValue = item != null ? item.ToString() : "NULL"; + string itemLabel = $"Element {index}"; + EditorGUILayout.LabelField(itemLabel, itemValue); + + index++; + } + } + } + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/SyncObjectCollectionsDrawer.cs.meta b/Assets/ImportedAssets/Mirror/Editor/SyncObjectCollectionsDrawer.cs.meta new file mode 100644 index 0000000000..88478215d9 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/SyncObjectCollectionsDrawer.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6f90afab12e04f0e945d83e9d38308a3 +timeCreated: 1632556645 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/SyncObjectCollectionsDrawer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/SyncVarAttributeDrawer.cs b/Assets/ImportedAssets/Mirror/Editor/SyncVarAttributeDrawer.cs index f7b018a0d7..2356a5e234 100644 --- a/Assets/ImportedAssets/Mirror/Editor/SyncVarAttributeDrawer.cs +++ b/Assets/ImportedAssets/Mirror/Editor/SyncVarAttributeDrawer.cs @@ -16,7 +16,7 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten Rect valueRect = new Rect(position.x, position.y, valueWidth, position.height); Rect labelRect = new Rect(position.x + valueWidth, position.y, syncVarIndicatorRect.x, position.height); - EditorGUI.PropertyField(valueRect, property, true); + EditorGUI.PropertyField(valueRect, property, label, true); GUI.Label(labelRect, syncVarIndicatorContent, EditorStyles.miniLabel); } @@ -25,4 +25,4 @@ public override float GetPropertyHeight(SerializedProperty property, GUIContent return EditorGUI.GetPropertyHeight(property); } } -} //namespace +} diff --git a/Assets/ImportedAssets/Mirror/Editor/SyncVarAttributeDrawer.cs.meta b/Assets/ImportedAssets/Mirror/Editor/SyncVarAttributeDrawer.cs.meta index 6311f1d3a6..886868c278 100644 --- a/Assets/ImportedAssets/Mirror/Editor/SyncVarAttributeDrawer.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/SyncVarAttributeDrawer.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/SyncVarAttributeDrawer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/AssemblyInfo.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/AssemblyInfo.cs.meta index d356af818f..c7bec235aa 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/AssemblyInfo.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/AssemblyInfo.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/AssemblyInfo.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/CompilationFinishedHook.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/CompilationFinishedHook.cs deleted file mode 100644 index 991c964841..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/CompilationFinishedHook.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEditor; -using UnityEditor.Compilation; -using UnityEngine; -using UnityAssembly = UnityEditor.Compilation.Assembly; - -namespace Mirror.Weaver -{ - public static class CompilationFinishedHook - { - const string MirrorRuntimeAssemblyName = "Mirror"; - const string MirrorWeaverAssemblyName = "Mirror.Weaver"; - - // delegate for subscription to Weaver debug messages - public static Action OnWeaverMessage; - // delegate for subscription to Weaver warning messages - public static Action OnWeaverWarning; - // delete for subscription to Weaver error messages - public static Action OnWeaverError; - - // controls whether we weave any assemblies when CompilationPipeline delegates are invoked - public static bool WeaverEnabled { get; set; } - // controls weather Weaver errors are reported direct to the Unity console (tests enable this) - public static bool UnityLogEnabled = true; - - // holds the result status of our latest Weave operation - // NOTE: WeaveFailed is critical to unit tests, but isn't used for anything else. - public static bool WeaveFailed { get; private set; } - - // warning message handler that also calls OnWarningMethod delegate - static void HandleWarning(string msg) - { - if (UnityLogEnabled) Debug.LogWarning(msg); - if (OnWeaverWarning != null) OnWeaverWarning.Invoke(msg); - } - - // error message handler that also calls OnErrorMethod delegate - static void HandleError(string msg) - { - if (UnityLogEnabled) Debug.LogError(msg); - if (OnWeaverError != null) OnWeaverError.Invoke(msg); - } - - [InitializeOnLoadMethod] - public static void OnInitializeOnLoad() - { - CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished; - - // We only need to run this once per session - // after that, all assemblies will be weaved by the event - if (!SessionState.GetBool("MIRROR_WEAVED", false)) - { - // reset session flag - SessionState.SetBool("MIRROR_WEAVED", true); - SessionState.SetBool("MIRROR_WEAVE_SUCCESS", true); - - WeaveExistingAssemblies(); - } - } - - public static void WeaveExistingAssemblies() - { - foreach (UnityAssembly assembly in CompilationPipeline.GetAssemblies()) - { - if (File.Exists(assembly.outputPath)) - { - OnCompilationFinished(assembly.outputPath, new CompilerMessage[0]); - } - } - -#if UNITY_2019_3_OR_NEWER - EditorUtility.RequestScriptReload(); -#else - UnityEditorInternal.InternalEditorUtility.RequestScriptReload(); -#endif - } - - static string FindMirrorRuntime() - { - foreach (UnityAssembly assembly in CompilationPipeline.GetAssemblies()) - { - if (assembly.name == MirrorRuntimeAssemblyName) - { - return assembly.outputPath; - } - } - return ""; - } - - static bool CompilerMessagesContainError(CompilerMessage[] messages) - { - return messages.Any(msg => msg.type == CompilerMessageType.Error); - } - - static void OnCompilationFinished(string assemblyPath, CompilerMessage[] messages) - { - // Do nothing if there were compile errors on the target - if (CompilerMessagesContainError(messages)) - { - Debug.Log("Weaver: stop because compile errors on target"); - return; - } - - // Should not run on the editor only assemblies - if (assemblyPath.Contains("-Editor") || assemblyPath.Contains(".Editor")) - { - return; - } - - // don't weave mirror files - string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath); - if (assemblyName == MirrorRuntimeAssemblyName || assemblyName == MirrorWeaverAssemblyName) - { - return; - } - - // find Mirror.dll - string mirrorRuntimeDll = FindMirrorRuntime(); - if (string.IsNullOrEmpty(mirrorRuntimeDll)) - { - Debug.LogError("Failed to find Mirror runtime assembly"); - return; - } - if (!File.Exists(mirrorRuntimeDll)) - { - // this is normal, it happens with any assembly that is built before mirror - // such as unity packages or your own assemblies - // those don't need to be weaved - // if any assembly depends on mirror, then it will be built after - return; - } - - // find UnityEngine.CoreModule.dll - string unityEngineCoreModuleDLL = UnityEditorInternal.InternalEditorUtility.GetEngineCoreModuleAssemblyPath(); - if (string.IsNullOrEmpty(unityEngineCoreModuleDLL)) - { - Debug.LogError("Failed to find UnityEngine assembly"); - return; - } - - HashSet dependencyPaths = GetDependecyPaths(assemblyPath); - - // passing null in the outputDirectory param will do an in-place update of the assembly - if (Weaver.Process(unityEngineCoreModuleDLL, mirrorRuntimeDll, null, new[] { assemblyPath }, dependencyPaths.ToArray(), HandleWarning, HandleError)) - { - // NOTE: WeaveFailed is critical for unit tests but isn't used elsewhere - WeaveFailed = false; - } - else - { - // Set false...will be checked in \Editor\EnterPlayModeSettingsCheck.CheckSuccessfulWeave() - SessionState.SetBool("MIRROR_WEAVE_SUCCESS", false); - - WeaveFailed = true; - if (UnityLogEnabled) Debug.LogError("Weaving failed for: " + assemblyPath); - } - } - - static HashSet GetDependecyPaths(string assemblyPath) - { - // build directory list for later asm/symbol resolving using CompilationPipeline refs - HashSet dependencyPaths = new HashSet(); - dependencyPaths.Add(Path.GetDirectoryName(assemblyPath)); - foreach (UnityAssembly unityAsm in CompilationPipeline.GetAssemblies()) - { - if (unityAsm.outputPath != assemblyPath) - continue; - - foreach (string unityAsmRef in unityAsm.compiledAssemblyReferences) - { - dependencyPaths.Add(Path.GetDirectoryName(unityAsmRef)); - } - } - - return dependencyPaths; - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/CompilationFinishedHook.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/CompilationFinishedHook.cs.meta deleted file mode 100644 index ed537ab5ce..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/CompilationFinishedHook.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: de2aeb2e8068f421a9a1febe408f7051 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty.meta new file mode 100644 index 0000000000..6e29ee7a95 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 30fc290f2ff9c29498f54f63de12ca6f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs new file mode 100644 index 0000000000..a88144a8f9 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs @@ -0,0 +1 @@ +// Removed Oct 1 2020 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/GenericArgumentResolver.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/GenericArgumentResolver.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs new file mode 100644 index 0000000000..b38f1712e1 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs @@ -0,0 +1 @@ +// removed Oct 5 2020 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs.meta similarity index 83% rename from Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs.meta index 875cf9adc7..cbea4d617c 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 3544c9f00f6e5443ea3c30873c5a06ef +guid: e25c00c88fc134f6ea7ab00ae4db8083 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Program.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/Program.cs similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Weaver/Program.cs rename to Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/Program.cs diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Program.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/Program.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Weaver/Program.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/Program.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs new file mode 100644 index 0000000000..a88144a8f9 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs @@ -0,0 +1 @@ +// Removed Oct 1 2020 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs new file mode 100644 index 0000000000..2fdbc52eef --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs @@ -0,0 +1 @@ +// removed 2020-09 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs new file mode 100644 index 0000000000..a88144a8f9 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs @@ -0,0 +1 @@ +// Removed Oct 1 2020 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs.meta similarity index 100% rename from Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs.meta rename to Assets/ImportedAssets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs.meta diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint.meta new file mode 100644 index 0000000000..81827c5c83 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 251338e67afb4cefa38da924f8c50a6e +timeCreated: 1628851818 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs new file mode 100644 index 0000000000..b5db851fc1 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs @@ -0,0 +1,188 @@ +// for Unity 2020+ we use ILPostProcessor. +// only automatically invoke it for older versions. +#if !UNITY_2020_3_OR_NEWER +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Mono.CecilX; +using UnityEditor; +using UnityEditor.Compilation; +using UnityEngine; +using UnityAssembly = UnityEditor.Compilation.Assembly; + +namespace Mirror.Weaver +{ + public static class CompilationFinishedHook + { + // needs to be the same as Weaver.MirrorAssemblyName! + const string MirrorRuntimeAssemblyName = "Mirror"; + const string MirrorWeaverAssemblyName = "Mirror.Weaver"; + + // global weaver define so that tests can use it + internal static Weaver weaver; + + // delegate for subscription to Weaver warning messages + public static Action OnWeaverWarning; + // delete for subscription to Weaver error messages + public static Action OnWeaverError; + + // controls whether Weaver errors are reported direct to the Unity console (tests enable this) + public static bool UnityLogEnabled = true; + + [InitializeOnLoadMethod] + public static void OnInitializeOnLoad() + { + CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished; + + // We only need to run this once per session + // after that, all assemblies will be weaved by the event + if (!SessionState.GetBool("MIRROR_WEAVED", false)) + { + // reset session flag + SessionState.SetBool("MIRROR_WEAVED", true); + SessionState.SetBool("MIRROR_WEAVE_SUCCESS", true); + + WeaveExistingAssemblies(); + } + } + + public static void WeaveExistingAssemblies() + { + foreach (UnityAssembly assembly in CompilationPipeline.GetAssemblies()) + { + if (File.Exists(assembly.outputPath)) + { + OnCompilationFinished(assembly.outputPath, new CompilerMessage[0]); + } + } + + EditorUtility.RequestScriptReload(); + } + + static Assembly FindCompilationPipelineAssembly(string assemblyName) => + CompilationPipeline.GetAssemblies().First(assembly => assembly.name == assemblyName); + + static bool CompilerMessagesContainError(CompilerMessage[] messages) => + messages.Any(msg => msg.type == CompilerMessageType.Error); + + public static void OnCompilationFinished(string assemblyPath, CompilerMessage[] messages) + { + // Do nothing if there were compile errors on the target + if (CompilerMessagesContainError(messages)) + { + Debug.Log("Weaver: stop because compile errors on target"); + return; + } + + // Should not run on the editor only assemblies (test ones still need to be weaved) + if (assemblyPath.Contains("-Editor") || + (assemblyPath.Contains(".Editor") && !assemblyPath.Contains(".Tests"))) + { + return; + } + + // skip Mirror.dll because CompilationFinishedHook can't weave itself. + // this would cause a sharing violation. + // skip Mirror.Weaver.dll too. + string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath); + if (assemblyName == MirrorRuntimeAssemblyName || assemblyName == MirrorWeaverAssemblyName) + { + return; + } + + // find Mirror.dll + Assembly mirrorAssembly = FindCompilationPipelineAssembly(MirrorRuntimeAssemblyName); + if (mirrorAssembly == null) + { + Debug.LogError("Failed to find Mirror runtime assembly"); + return; + } + + string mirrorRuntimeDll = mirrorAssembly.outputPath; + if (!File.Exists(mirrorRuntimeDll)) + { + // this is normal, it happens with any assembly that is built before mirror + // such as unity packages or your own assemblies + // those don't need to be weaved + // if any assembly depends on mirror, then it will be built after + return; + } + + // find UnityEngine.CoreModule.dll + string unityEngineCoreModuleDLL = UnityEditorInternal.InternalEditorUtility.GetEngineCoreModuleAssemblyPath(); + if (string.IsNullOrEmpty(unityEngineCoreModuleDLL)) + { + Debug.LogError("Failed to find UnityEngine assembly"); + return; + } + + HashSet dependencyPaths = GetDependencyPaths(assemblyPath); + dependencyPaths.Add(Path.GetDirectoryName(mirrorRuntimeDll)); + dependencyPaths.Add(Path.GetDirectoryName(unityEngineCoreModuleDLL)); + + if (!WeaveFromFile(assemblyPath, dependencyPaths.ToArray())) + { + // Set false...will be checked in \Editor\EnterPlayModeSettingsCheck.CheckSuccessfulWeave() + SessionState.SetBool("MIRROR_WEAVE_SUCCESS", false); + if (UnityLogEnabled) Debug.LogError($"Weaving failed for {assemblyPath}"); + } + } + + static HashSet GetDependencyPaths(string assemblyPath) + { + // build directory list for later asm/symbol resolving using CompilationPipeline refs + HashSet dependencyPaths = new HashSet + { + Path.GetDirectoryName(assemblyPath) + }; + foreach (Assembly assembly in CompilationPipeline.GetAssemblies()) + { + if (assembly.outputPath == assemblyPath) + { + foreach (string reference in assembly.compiledAssemblyReferences) + { + dependencyPaths.Add(Path.GetDirectoryName(reference)); + } + } + } + + return dependencyPaths; + } + // helper function to invoke Weaver with an AssemblyDefinition from a + // file path, with dependencies added. + static bool WeaveFromFile(string assemblyPath, string[] dependencies) + { + // resolve assembly from stream + using (DefaultAssemblyResolver asmResolver = new DefaultAssemblyResolver()) + using (AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters{ ReadWrite = true, ReadSymbols = true, AssemblyResolver = asmResolver })) + { + // add this assembly's path and unity's assembly path + asmResolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath)); + asmResolver.AddSearchDirectory(Helpers.UnityEngineDllDirectoryName()); + + // add dependencies + if (dependencies != null) + { + foreach (string path in dependencies) + { + asmResolver.AddSearchDirectory(path); + } + } + + // create weaver with logger + weaver = new Weaver(new CompilationFinishedLogger()); + if (weaver.Weave(assembly, asmResolver, out bool modified)) + { + // write changes to file if modified + if (modified) + assembly.Write(new WriterParameters{WriteSymbols = true}); + + return true; + } + return false; + } + } + } +} +#endif diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs.meta new file mode 100644 index 0000000000..c238f0bbb5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: de2aeb2e8068f421a9a1febe408f7051 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs new file mode 100644 index 0000000000..e05340484d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs @@ -0,0 +1,31 @@ +// logger for compilation finished hook. +// where we need a callback and Debug.Log. +// for Unity 2020+ we use ILPostProcessor. +#if !UNITY_2020_3_OR_NEWER +using Mono.CecilX; +using UnityEngine; + +namespace Mirror.Weaver +{ + public class CompilationFinishedLogger : Logger + { + public void Warning(string message) => Warning(message, null); + public void Warning(string message, MemberReference mr) + { + if (mr != null) message = $"{message} (at {mr})"; + + if (CompilationFinishedHook.UnityLogEnabled) Debug.LogWarning(message); + CompilationFinishedHook.OnWeaverWarning?.Invoke(message); + } + + public void Error(string message) => Error(message, null); + public void Error(string message, MemberReference mr) + { + if (mr != null) message = $"{message} (at {mr})"; + + if (CompilationFinishedHook.UnityLogEnabled) Debug.LogError(message); + CompilationFinishedHook.OnWeaverError?.Invoke(message); + } + } +} +#endif diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs.meta new file mode 100644 index 0000000000..031d8bf6de --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 47026732f0fa475c94bd1dd41f1de559 +timeCreated: 1629379868 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs new file mode 100644 index 0000000000..5dffa975e9 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs @@ -0,0 +1,44 @@ +#if !UNITY_2020_3_OR_NEWER +// make sure we weaved successfully when entering play mode. +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + public class EnterPlayModeSettingsCheck : MonoBehaviour + { + [InitializeOnLoadMethod] + static void OnInitializeOnLoad() + { + // Hook this event to see if we have a good weave every time + // user attempts to enter play mode or tries to do a build + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + } + + static void OnPlayModeStateChanged(PlayModeStateChange state) + { + // Per Unity docs, this fires "when exiting edit mode before the Editor is in play mode". + // This doesn't fire when closing the editor. + if (state == PlayModeStateChange.ExitingEditMode) + { + // Check if last weave result was successful + if (!SessionState.GetBool("MIRROR_WEAVE_SUCCESS", false)) + { + // Last weave result was a failure...try to weave again + // Faults will show in the console that may have been cleared by "Clear on Play" + SessionState.SetBool("MIRROR_WEAVE_SUCCESS", true); + Weaver.CompilationFinishedHook.WeaveExistingAssemblies(); + + // Did that clear things up for us? + if (!SessionState.GetBool("MIRROR_WEAVE_SUCCESS", false)) + { + // Nope, still failed, and console has the issues logged + Debug.LogError("Can't enter play mode until weaver issues are resolved."); + EditorApplication.isPlaying = false; + } + } + } + } + } +} +#endif diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs.meta new file mode 100644 index 0000000000..2e5251dc25 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b73d0f106ba84aa983baa5142b08a0a9 +timeCreated: 1628851346 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor.meta new file mode 100644 index 0000000000..6ef7bf34f2 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 09082db63d1d48d9ab91320165c1b684 +timeCreated: 1628859005 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs new file mode 100644 index 0000000000..e4d9de2b0f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs @@ -0,0 +1,31 @@ +// tests use WeaveAssembler, which uses AssemblyBuilder to Build(). +// afterwards ILPostProcessor weaves the build. +// this works on windows, but build() does not run ILPP on mac atm. +// we need to manually invoke ILPP with an assembly from file. +// +// this is in Weaver folder becuase CompilationPipeline can only be accessed +// from assemblies with the name "Unity.*.CodeGen" +using System.IO; +using Unity.CompilationPipeline.Common.ILPostProcessing; + +namespace Mirror.Weaver +{ + public class CompiledAssemblyFromFile : ICompiledAssembly + { + readonly string assemblyPath; + + public string Name => Path.GetFileNameWithoutExtension(assemblyPath); + public string[] References { get; set; } + public string[] Defines { get; set; } + public InMemoryAssembly InMemoryAssembly { get; } + + public CompiledAssemblyFromFile(string assemblyPath) + { + this.assemblyPath = assemblyPath; + byte[] peData = File.ReadAllBytes(assemblyPath); + string pdbFileName = Path.GetFileNameWithoutExtension(assemblyPath) + ".pdb"; + byte[] pdbData = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(assemblyPath), pdbFileName)); + InMemoryAssembly = new InMemoryAssembly(peData, pdbData); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs.meta new file mode 100644 index 0000000000..05d67e3737 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9009d1db4ed44f6694a92bf8ad7738e9 +timeCreated: 1630129423 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs new file mode 100644 index 0000000000..0823234e7d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs @@ -0,0 +1,205 @@ +// based on paul's resolver from +// https://github.com/MirageNet/Mirage/commit/def64cd1db525398738f057b3d1eb1fe8afc540c?branch=def64cd1db525398738f057b3d1eb1fe8afc540c&diff=split +// +// an assembly resolver's job is to open an assembly in case we want to resolve +// a type from it. +// +// for example, while weaving MyGame.dll: if we want to resolve ArraySegment, +// then we need to open and resolve from another assembly (CoreLib). +// +// using DefaultAssemblyResolver with ILPostProcessor throws Exceptions in +// WeaverTypes.cs when resolving anything, for example: +// ArraySegment in Mirror.Tests.Dll. +// +// we need a custom resolver for ILPostProcessor. +#if UNITY_2020_3_OR_NEWER +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Linq; +using System.Threading; +using Mono.CecilX; +using Unity.CompilationPipeline.Common.ILPostProcessing; + +namespace Mirror.Weaver +{ + class ILPostProcessorAssemblyResolver : IAssemblyResolver + { + readonly string[] assemblyReferences; + + // originally we used Dictionary + lock. + // Resolve() is called thousands of times for large projects. + // ILPostProcessor is multithreaded, so best to use ConcurrentDictionary without the lock here. + readonly ConcurrentDictionary assemblyCache = + new ConcurrentDictionary(); + + // Resolve() calls FindFile() every time. + // thousands of times for String => mscorlib alone in large projects. + // cache the results! ILPostProcessor is multithreaded, so use a ConcurrentDictionary here. + readonly ConcurrentDictionary fileNameCache = + new ConcurrentDictionary(); + + readonly ICompiledAssembly compiledAssembly; + AssemblyDefinition selfAssembly; + + readonly Logger Log; + + public ILPostProcessorAssemblyResolver(ICompiledAssembly compiledAssembly, Logger Log) + { + this.compiledAssembly = compiledAssembly; + assemblyReferences = compiledAssembly.References; + this.Log = Log; + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + // Cleanup + } + + public AssemblyDefinition Resolve(AssemblyNameReference name) => + Resolve(name, new ReaderParameters(ReadingMode.Deferred)); + + // here is an example on when this is called: + // Player : NetworkBehaviour has a [SyncVar] of type String. + // Weaver's SyncObjectInitializer checks if ImplementsSyncObject() + // which needs to resolve the type 'String' from mscorlib. + // Resolve() lives in CecilX.MetadataResolver.Resolve() + // which calls assembly_resolver.Resolve(). + // which uses our ILPostProcessorAssemblyResolver here. + // + // for large projects, this is called thousands of times for mscorlib alone. + // initially ILPostProcessorAssemblyResolver took 30x longer than with CompilationFinishedHook. + // we need to cache and speed up everything we can here! + public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) + { + if (name.Name == compiledAssembly.Name) + return selfAssembly; + + // cache FindFile. + // in large projects, this is called thousands(!) of times for String=>mscorlib alone. + // reduces a single String=>mscorlib resolve from 0.771ms to 0.015ms. + // => 50x improvement in TypeReference.Resolve() speed! + // => 22x improvement in Weaver speed! + if (!fileNameCache.TryGetValue(name.Name, out string fileName)) + { + fileName = FindFile(name.Name); + fileNameCache.TryAdd(name.Name, fileName); + } + + if (fileName == null) + { + // returning null will throw exceptions in our weaver where. + // let's make it obvious why we returned null for easier debugging. + // NOTE: if this fails for "System.Private.CoreLib": + // ILPostProcessorReflectionImporter fixes it! + + // the fix for #2503 started showing this warning for Bee.BeeDriver on mac, + // which is for compilation. we can ignore that one. + if (!name.Name.StartsWith("Bee.BeeDriver")) + { + Log.Warning($"ILPostProcessorAssemblyResolver.Resolve: Failed to find file for {name}"); + } + return null; + } + + // try to get cached assembly by filename + writetime + DateTime lastWriteTime = File.GetLastWriteTime(fileName); + string cacheKey = fileName + lastWriteTime; + if (assemblyCache.TryGetValue(cacheKey, out AssemblyDefinition result)) + return result; + + // otherwise resolve and cache a new assembly + parameters.AssemblyResolver = this; + MemoryStream ms = MemoryStreamFor(fileName); + + string pdb = fileName + ".pdb"; + if (File.Exists(pdb)) + parameters.SymbolStream = MemoryStreamFor(pdb); + + AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(ms, parameters); + assemblyCache.TryAdd(cacheKey, assemblyDefinition); + return assemblyDefinition; + } + + // find assemblyname in assembly's references + string FindFile(string name) + { + // perhaps the type comes from a .dll or .exe + // check both in one call without Linq instead of iterating twice like originally + foreach (string r in assemblyReferences) + { + if (Path.GetFileNameWithoutExtension(r) == name) + return r; + } + + // this is called thousands(!) of times. + // constructing strings only once saves ~0.1ms per call for mscorlib. + string dllName = name + ".dll"; + + // Unfortunately the current ICompiledAssembly API only provides direct references. + // It is very much possible that a postprocessor ends up investigating a type in a directly + // referenced assembly, that contains a field that is not in a directly referenced assembly. + // if we don't do anything special for that situation, it will fail to resolve. We should fix this + // in the ILPostProcessing API. As a workaround, we rely on the fact here that the indirect references + // are always located next to direct references, so we search in all directories of direct references we + // got passed, and if we find the file in there, we resolve to it. + foreach (string parentDir in assemblyReferences.Select(Path.GetDirectoryName).Distinct()) + { + string candidate = Path.Combine(parentDir, dllName); + if (File.Exists(candidate)) + return candidate; + } + + return null; + } + + // open file as MemoryStream. + // ILPostProcessor is multithreaded. + // retry a few times in case another thread is still accessing the file. + static MemoryStream MemoryStreamFor(string fileName) + { + return Retry(10, TimeSpan.FromSeconds(1), () => + { + byte[] byteArray; + using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + byteArray = new byte[fs.Length]; + int readLength = fs.Read(byteArray, 0, (int)fs.Length); + if (readLength != fs.Length) + throw new InvalidOperationException("File read length is not full length of file."); + } + + return new MemoryStream(byteArray); + }); + } + + static MemoryStream Retry(int retryCount, TimeSpan waitTime, Func func) + { + try + { + return func(); + } + catch (IOException) + { + if (retryCount == 0) + throw; + Console.WriteLine($"Caught IO Exception, trying {retryCount} more times"); + Thread.Sleep(waitTime); + return Retry(retryCount - 1, waitTime, func); + } + } + + // if the CompiledAssembly's AssemblyDefinition is known, we can add it + public void SetAssemblyDefinitionForCompiledAssembly(AssemblyDefinition assemblyDefinition) + { + selfAssembly = assemblyDefinition; + } + } +} +#endif diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs.meta new file mode 100644 index 0000000000..b87828b16f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 0b3e94696e22440ead0b3a42411bbe14 +timeCreated: 1629693784 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs new file mode 100644 index 0000000000..6a706411e6 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs @@ -0,0 +1,53 @@ +// helper function to use ILPostProcessor for an assembly from file. +// we keep this in Weaver folder because we can access CompilationPipleine here. +// in tests folder we can't, unless we rename to "Unity.*.CodeGen", +// but then tests wouldn't be weaved anymore. +#if UNITY_2020_3_OR_NEWER +using System; +using System.IO; +using Unity.CompilationPipeline.Common.Diagnostics; +using Unity.CompilationPipeline.Common.ILPostProcessing; + +namespace Mirror.Weaver +{ + public static class ILPostProcessorFromFile + { + // read, weave, write file via ILPostProcessor + public static void ILPostProcessFile(string assemblyPath, string[] references, Action OnWarning, Action OnError) + { + // we COULD Weave() with a test logger manually. + // but for test result consistency on all platforms, + // let's invoke the ILPostProcessor here too. + CompiledAssemblyFromFile assembly = new CompiledAssemblyFromFile(assemblyPath); + assembly.References = references; + + // create ILPP and check WillProcess like Unity would. + ILPostProcessorHook ilpp = new ILPostProcessorHook(); + if (ilpp.WillProcess(assembly)) + { + //Debug.Log($"Will Process: {assembly.Name}"); + + // process it like Unity would + ILPostProcessResult result = ilpp.Process(assembly); + + // handle the error messages like Unity would + foreach (DiagnosticMessage message in result.Diagnostics) + { + if (message.DiagnosticType == DiagnosticType.Warning) + { + OnWarning(message.MessageData); + } + else if (message.DiagnosticType == DiagnosticType.Error) + { + OnError(message.MessageData); + } + } + + // save the weaved assembly to file. + // some tests open it and check for certain IL code. + File.WriteAllBytes(assemblyPath, result.InMemoryAssembly.PeData); + } + } + } +} +#endif diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs.meta new file mode 100644 index 0000000000..2b343c810f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 2a4b115486b74d27a9540f3c39ae2d46 +timeCreated: 1630152191 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs new file mode 100644 index 0000000000..0cfb433878 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs @@ -0,0 +1,143 @@ +// hook via ILPostProcessor from Unity 2020.3+ +// (2020.1 has errors https://github.com/vis2k/Mirror/issues/2912) +#if UNITY_2020_3_OR_NEWER +// Unity.CompilationPipeline reference is only resolved if assembly name is +// Unity.*.CodeGen: +// https://forum.unity.com/threads/how-does-unity-do-codegen-and-why-cant-i-do-it-myself.853867/#post-5646937 +using System.IO; +using System.Linq; +// to use Mono.CecilX here, we need to 'override references' in the +// Unity.Mirror.CodeGen assembly definition file in the Editor, and add CecilX. +// otherwise we get a reflection exception with 'file not found: CecilX'. +using Mono.CecilX; +using Mono.CecilX.Cil; +using Unity.CompilationPipeline.Common.ILPostProcessing; +// IMPORTANT: 'using UnityEngine' does not work in here. +// Unity gives "(0,0): error System.Security.SecurityException: ECall methods must be packaged into a system module." +//using UnityEngine; + +namespace Mirror.Weaver +{ + public class ILPostProcessorHook : ILPostProcessor + { + // from CompilationFinishedHook + const string MirrorRuntimeAssemblyName = "Mirror"; + + // ILPostProcessor is invoked by Unity. + // we can not tell it to ignore certain assemblies before processing. + // add a 'ignore' define for convenience. + // => WeaverTests/WeaverAssembler need it to avoid Unity running it + public const string IgnoreDefine = "ILPP_IGNORE"; + + // we can't use Debug.Log in ILPP, so we need a custom logger + ILPostProcessorLogger Log = new ILPostProcessorLogger(); + + // ??? + public override ILPostProcessor GetInstance() => this; + + // check if assembly has the 'ignore' define + static bool HasDefine(ICompiledAssembly assembly, string define) => + assembly.Defines != null && + assembly.Defines.Contains(define); + + // process Mirror, or anything that references Mirror + public override bool WillProcess(ICompiledAssembly compiledAssembly) + { + // compiledAssembly.References are file paths: + // Library/Bee/artifacts/200b0aE.dag/Mirror.CompilerSymbols.dll + // Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll + // /Applications/Unity/Hub/Editor/2021.2.0b6_apple_silicon/Unity.app/Contents/NetStandard/ref/2.1.0/netstandard.dll + // + // log them to see: + // foreach (string reference in compiledAssembly.References) + // LogDiagnostics($"{compiledAssembly.Name} references {reference}"); + bool relevant = compiledAssembly.Name == MirrorRuntimeAssemblyName || + compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == MirrorRuntimeAssemblyName); + bool ignore = HasDefine(compiledAssembly, IgnoreDefine); + return relevant && !ignore; + } + + public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly) + { + //Log.Warning($"Processing {compiledAssembly.Name}"); + + // load the InMemoryAssembly peData into a MemoryStream + byte[] peData = compiledAssembly.InMemoryAssembly.PeData; + //LogDiagnostics($" peData.Length={peData.Length} bytes"); + using (MemoryStream stream = new MemoryStream(peData)) + using (ILPostProcessorAssemblyResolver asmResolver = new ILPostProcessorAssemblyResolver(compiledAssembly, Log)) + { + // we need to load symbols. otherwise we get: + // "(0,0): error Mono.CecilX.Cil.SymbolsNotFoundException: No symbol found for file: " + using (MemoryStream symbols = new MemoryStream(compiledAssembly.InMemoryAssembly.PdbData)) + { + ReaderParameters readerParameters = new ReaderParameters{ + SymbolStream = symbols, + ReadWrite = true, + ReadSymbols = true, + AssemblyResolver = asmResolver, + // custom reflection importer to fix System.Private.CoreLib + // not being found in custom assembly resolver above. + ReflectionImporterProvider = new ILPostProcessorReflectionImporterProvider() + }; + using (AssemblyDefinition asmDef = AssemblyDefinition.ReadAssembly(stream, readerParameters)) + { + // resolving a Mirror.dll type like NetworkServer while + // weaving Mirror.dll does not work. it throws a + // NullReferenceException in WeaverTypes.ctor + // when Resolve() is called on the first Mirror type. + // need to add the AssemblyDefinition itself to use. + asmResolver.SetAssemblyDefinitionForCompiledAssembly(asmDef); + + // weave this assembly. + Weaver weaver = new Weaver(Log); + if (weaver.Weave(asmDef, asmResolver, out bool modified)) + { + //Log.Warning($"Weaving succeeded for: {compiledAssembly.Name}"); + + // write if modified + if (modified) + { + // when weaving Mirror.dll with ILPostProcessor, + // Weave() -> WeaverTypes -> resolving the first + // type in Mirror.dll adds a reference to + // Mirror.dll even though we are in Mirror.dll. + // -> this would throw an exception: + // "Mirror references itself" and not compile + // -> need to detect and fix manually here + if (asmDef.MainModule.AssemblyReferences.Any(r => r.Name == asmDef.Name.Name)) + { + asmDef.MainModule.AssemblyReferences.Remove(asmDef.MainModule.AssemblyReferences.First(r => r.Name == asmDef.Name.Name)); + //Log.Warning($"fixed self referencing Assembly: {asmDef.Name.Name}"); + } + + MemoryStream peOut = new MemoryStream(); + MemoryStream pdbOut = new MemoryStream(); + WriterParameters writerParameters = new WriterParameters + { + SymbolWriterProvider = new PortablePdbWriterProvider(), + SymbolStream = pdbOut, + WriteSymbols = true + }; + + asmDef.Write(peOut, writerParameters); + + InMemoryAssembly inMemory = new InMemoryAssembly(peOut.ToArray(), pdbOut.ToArray()); + return new ILPostProcessResult(inMemory, Log.Logs); + } + } + // if anything during Weave() fails, we log an error. + // don't need to indicate 'weaving failed' again. + // in fact, this would break tests only expecting certain errors. + //else Log.Error($"Weaving failed for: {compiledAssembly.Name}"); + } + } + } + + // always return an ILPostProcessResult with Logs. + // otherwise we won't see Logs if weaving failed. + return new ILPostProcessResult(compiledAssembly.InMemoryAssembly, Log.Logs); + } + } +} +#endif diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs.meta new file mode 100644 index 0000000000..fef4ee8368 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 5f113eb695b348b5b28cd85358c8959a +timeCreated: 1628859074 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs new file mode 100644 index 0000000000..e8595fd9c6 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs @@ -0,0 +1,68 @@ +using System.Collections.Generic; +using Mono.CecilX; +using Unity.CompilationPipeline.Common.Diagnostics; + +namespace Mirror.Weaver +{ + public class ILPostProcessorLogger : Logger + { + // can't Debug.Log in ILPostProcessor. need to add to this list. + internal List Logs = new List(); + + void Add(string message, DiagnosticType logType) + { + Logs.Add(new DiagnosticMessage + { + // TODO add file etc. for double click opening later? + DiagnosticType = logType, // doesn't have .Log + File = null, + Line = 0, + Column = 0, + MessageData = message + }); + } + + public void LogDiagnostics(string message, DiagnosticType logType = DiagnosticType.Warning) + { + // TODO IN-44868 FIX IS IN 2021.3.32f1, 2022.3.11f1, 2023.2.0b13 and 2023.3.0a8 + // DiagnosticMessage can't display \n for some reason. + // it just cuts it off and we don't see any stack trace. + // so let's replace all line breaks so we get the stack trace. + // (Unity 2021.2.0b6 apple silicon) + //message = message.Replace("\n", "/"); + + // lets break it into several messages instead so it's easier readable + string[] lines = message.Split('\n'); + + // if it's just one line, simply log it + if (lines.Length == 1) + { + // tests assume exact message log. + // don't include 'Weaver: ...' or similar. + Add($"{message}", logType); + } + // for multiple lines, log each line separately with start/end indicators + else + { + // first line with Weaver: ... first + Add("----------------------------------------------", logType); + foreach (string line in lines) Add(line, logType); + Add("----------------------------------------------", logType); + } + } + + public void Warning(string message) => Warning(message, null); + public void Warning(string message, MemberReference mr) + { + if (mr != null) message = $"{message} (at {mr})"; + LogDiagnostics(message, DiagnosticType.Warning); + } + + public void Error(string message) => Error(message, null); + public void Error(string message, MemberReference mr) + { + if (mr != null) message = $"{message} (at {mr})"; + LogDiagnostics(message, DiagnosticType.Error); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs.meta new file mode 100644 index 0000000000..e02f56cd1d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: e7b56e7826664e34a415e4b70d958f2a +timeCreated: 1629533154 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs new file mode 100644 index 0000000000..e15c10307a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs @@ -0,0 +1,36 @@ +// based on paul's resolver from +// https://github.com/MirageNet/Mirage/commit/def64cd1db525398738f057b3d1eb1fe8afc540c?branch=def64cd1db525398738f057b3d1eb1fe8afc540c&diff=split +// +// ILPostProcessorAssemblyRESOLVER does not find the .dll file for: +// "System.Private.CoreLib" +// we need this custom reflection importer to fix that. +using System.Linq; +using System.Reflection; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + internal class ILPostProcessorReflectionImporter : DefaultReflectionImporter + { + const string SystemPrivateCoreLib = "System.Private.CoreLib"; + readonly AssemblyNameReference fixedCoreLib; + + public ILPostProcessorReflectionImporter(ModuleDefinition module) : base(module) + { + // find the correct library for "System.Private.CoreLib". + // either mscorlib or netstandard. + // defaults to System.Private.CoreLib if not found. + fixedCoreLib = module.AssemblyReferences.FirstOrDefault(a => a.Name == "mscorlib" || a.Name == "netstandard" || a.Name == SystemPrivateCoreLib); + } + + public override AssemblyNameReference ImportReference(AssemblyName name) + { + // System.Private.CoreLib? + if (name.Name == SystemPrivateCoreLib && fixedCoreLib != null) + return fixedCoreLib; + + // otherwise import as usual + return base.ImportReference(name); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs.meta new file mode 100644 index 0000000000..022827c70d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6403a7e3b3ae4e009ae282f111d266e0 +timeCreated: 1629709256 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs new file mode 100644 index 0000000000..7358e1baf7 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs @@ -0,0 +1,16 @@ +// based on paul's resolver from +// https://github.com/MirageNet/Mirage/commit/def64cd1db525398738f057b3d1eb1fe8afc540c?branch=def64cd1db525398738f057b3d1eb1fe8afc540c&diff=split +// +// ILPostProcessorAssemblyRESOLVER does not find the .dll file for: +// "System.Private.CoreLib" +// we need this custom reflection importer to fix that. +using Mono.CecilX; + +namespace Mirror.Weaver +{ + internal class ILPostProcessorReflectionImporterProvider : IReflectionImporterProvider + { + public IReflectionImporter GetReflectionImporter(ModuleDefinition module) => + new ILPostProcessorReflectionImporter(module); + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs.meta new file mode 100644 index 0000000000..f7494ad527 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a1003b568bad4e69b961c4c81d5afd96 +timeCreated: 1629709223 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Extensions.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Extensions.cs index b1d0b5dd6c..566a51af4f 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Extensions.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Extensions.cs @@ -7,52 +7,43 @@ namespace Mirror.Weaver { public static class Extensions { - public static bool IsDerivedFrom(this TypeDefinition td, TypeReference baseClass) - { - return IsDerivedFrom(td, baseClass.FullName); - } - - // removes from class names (if any generic parameters) - internal static string StripGenericParametersFromClassName(string className) - { - int index = className.IndexOf('<'); - if (index != -1) - { - return className.Substring(0, index); - } - return className; - } - - public static bool IsDerivedFrom(this TypeDefinition td, string baseClassFullName) + public static bool Is(this TypeReference td, Type type) => + type.IsGenericType + ? td.GetElementType().FullName == type.FullName + : td.FullName == type.FullName; + + // check if 'td' is exactly of type T. + // it does not check if any base type is of , only the specific type. + // for example: + // NetworkConnection Is NetworkConnection: true + // NetworkConnectionToClient Is NetworkConnection: false + public static bool Is(this TypeReference td) => Is(td, typeof(T)); + + // check if 'tr' is derived from T. + // it does not check if 'tr' is exactly T. + // for example: + // NetworkConnection IsDerivedFrom: false + // NetworkConnectionToClient IsDerivedFrom: true + public static bool IsDerivedFrom(this TypeReference tr) => IsDerivedFrom(tr, typeof(T)); + + public static bool IsDerivedFrom(this TypeReference tr, Type baseClass) { + TypeDefinition td = tr.Resolve(); if (!td.IsClass) return false; // are ANY parent classes of baseClass? TypeReference parent = td.BaseType; - while (parent != null) - { - string parentName = parent.FullName; - // strip generic parameters from class name (if any) - parentName = StripGenericParametersFromClassName(parentName); + if (parent == null) + return false; - if (parentName == baseClassFullName) - { - return true; - } + if (parent.Is(baseClass)) + return true; + + if (parent.CanBeResolved()) + return IsDerivedFrom(parent.Resolve(), baseClass); - try - { - parent = parent.Resolve().BaseType; - } - catch (AssemblyResolutionException) - { - // this can happen for plugins. - //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); - break; - } - } return false; } @@ -66,16 +57,14 @@ public static TypeReference GetEnumUnderlyingType(this TypeDefinition td) throw new ArgumentException($"Invalid enum {td.FullName}"); } - public static bool ImplementsInterface(this TypeDefinition td, TypeReference baseInterface) + public static bool ImplementsInterface(this TypeDefinition td) { TypeDefinition typedef = td; + while (typedef != null) { - foreach (InterfaceImplementation iface in typedef.Interfaces) - { - if (iface.InterfaceType.FullName == baseInterface.FullName) - return true; - } + if (typedef.Interfaces.Any(iface => iface.InterfaceType.Is())) + return true; try { @@ -84,7 +73,7 @@ public static bool ImplementsInterface(this TypeDefinition td, TypeReference bas } catch (AssemblyResolutionException) { - // this can happen for pluins. + // this can happen for plugins. //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); break; } @@ -93,25 +82,17 @@ public static bool ImplementsInterface(this TypeDefinition td, TypeReference bas return false; } - public static bool IsArrayType(this TypeReference tr) - { - // jagged array - if ((tr.IsArray && ((ArrayType)tr).ElementType.IsArray) || - // multidimensional array - (tr.IsArray && ((ArrayType)tr).Rank > 1)) - return false; - return true; - } - - public static bool IsArraySegment(this TypeReference td) - { - return td.FullName.StartsWith("System.ArraySegment`1", System.StringComparison.Ordinal); - } + public static bool IsMultidimensionalArray(this TypeReference tr) => + tr is ArrayType arrayType && arrayType.Rank > 1; - public static bool IsList(this TypeReference td) - { - return td.FullName.StartsWith("System.Collections.Generic.List`1", System.StringComparison.Ordinal); - } + // Does type use netId as backing field + public static bool IsNetworkIdentityField(this TypeReference tr) => + tr.Is() || + tr.Is() || + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + tr.IsDerivedFrom() || + tr.Is(); public static bool CanBeResolved(this TypeReference parent) { @@ -140,17 +121,21 @@ public static bool CanBeResolved(this TypeReference parent) return true; } + // Makes T => Variable and imports function + public static MethodReference MakeGeneric(this MethodReference generic, ModuleDefinition module, TypeReference variableReference) + { + GenericInstanceMethod instance = new GenericInstanceMethod(generic); + instance.GenericArguments.Add(variableReference); - /// - /// Given a method of a generic class such as ArraySegment`T.get_Count, - /// and a generic instance such as ArraySegment`int - /// Creates a reference to the specialized method ArraySegment`int`.get_Count - /// Note that calling ArraySegment`T.get_Count directly gives an invalid IL error - /// - /// - /// - /// - public static MethodReference MakeHostInstanceGeneric(this MethodReference self, GenericInstanceType instanceType) + MethodReference readFunc = module.ImportReference(instance); + return readFunc; + } + + // Given a method of a generic class such as ArraySegment`T.get_Count, + // and a generic instance such as ArraySegment`int + // Creates a reference to the specialized method ArraySegment`int`.get_Count + // Note that calling ArraySegment`T.get_Count directly gives an invalid IL error + public static MethodReference MakeHostInstanceGeneric(this MethodReference self, ModuleDefinition module, GenericInstanceType instanceType) { MethodReference reference = new MethodReference(self.Name, self.ReturnType, instanceType) { @@ -165,55 +150,56 @@ public static MethodReference MakeHostInstanceGeneric(this MethodReference self, foreach (GenericParameter generic_parameter in self.GenericParameters) reference.GenericParameters.Add(new GenericParameter(generic_parameter.Name, reference)); - return Weaver.CurrentAssembly.MainModule.ImportReference(reference); + return module.ImportReference(reference); } - public static CustomAttribute GetCustomAttribute(this ICustomAttributeProvider method, string attributeName) + // needed for NetworkBehaviour support + // https://github.com/vis2k/Mirror/pull/3073/ + public static FieldReference MakeHostInstanceGeneric(this FieldReference self) { - foreach (CustomAttribute ca in method.CustomAttributes) + var declaringType = new GenericInstanceType(self.DeclaringType); + foreach (var parameter in self.DeclaringType.GenericParameters) { - if (ca.AttributeType.FullName == attributeName) - return ca; + declaringType.GenericArguments.Add(parameter); } - return null; + return new FieldReference(self.Name, self.FieldType, declaringType); } - public static bool HasCustomAttribute(this ICustomAttributeProvider attributeProvider, TypeReference attribute) + // Given a field of a generic class such as Writer.write, + // and a generic instance such as ArraySegment`int + // Creates a reference to the specialized method ArraySegment`int`.get_Count + // Note that calling ArraySegment`T.get_Count directly gives an invalid IL error + public static FieldReference SpecializeField(this FieldReference self, ModuleDefinition module, GenericInstanceType instanceType) { - // Linq allocations don't matter in weaver - return attributeProvider.CustomAttributes.Any(attr => attr.AttributeType.FullName == attribute.FullName); + FieldReference reference = new FieldReference(self.Name, self.FieldType, instanceType); + return module.ImportReference(reference); + } + + public static CustomAttribute GetCustomAttribute(this ICustomAttributeProvider method) + { + return method.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.Is()); + } + + public static bool HasCustomAttribute(this ICustomAttributeProvider attributeProvider) + { + return attributeProvider.CustomAttributes.Any(attr => attr.AttributeType.Is()); } public static T GetField(this CustomAttribute ca, string field, T defaultValue) { foreach (CustomAttributeNamedArgument customField in ca.Fields) - { if (customField.Name == field) - { return (T)customField.Argument.Value; - } - } - return defaultValue; } public static MethodDefinition GetMethod(this TypeDefinition td, string methodName) { - // Linq allocations don't matter in weaver return td.Methods.FirstOrDefault(method => method.Name == methodName); } - public static MethodDefinition GetMethodWith1Arg(this TypeDefinition tr, string methodName, TypeReference argType) - { - return tr.GetMethods(methodName).Where(m => - m.Parameters.Count == 1 - && m.Parameters[0].ParameterType.FullName == argType.FullName - ).FirstOrDefault(); - } - public static List GetMethods(this TypeDefinition td, string methodName) { - // Linq allocations don't matter in weaver return td.Methods.Where(method => method.Name == methodName).ToList(); } @@ -243,64 +229,29 @@ public static MethodDefinition GetMethodInBaseType(this TypeDefinition td, strin return null; } - /// - /// - /// - /// - /// - /// - /// - public static bool HasMethodInBaseType(this TypeDefinition td, string methodName, TypeReference stopAt) - { - TypeDefinition typedef = td; - while (typedef != null) - { - if (typedef.FullName == stopAt.FullName) - break; - - foreach (MethodDefinition md in typedef.Methods) - { - if (md.Name == methodName) - return true; - } - - try - { - TypeReference parent = typedef.BaseType; - typedef = parent?.Resolve(); - } - catch (AssemblyResolutionException) - { - // this can happen for plugins. - break; - } - } - - return false; - } - - /// - /// Finds public fields in type and base type - /// - /// - /// + // Finds public fields in type and base type public static IEnumerable FindAllPublicFields(this TypeReference variable) { return FindAllPublicFields(variable.Resolve()); } - /// - /// Finds public fields in type and base type - /// - /// - /// + // Finds public fields in type and base type public static IEnumerable FindAllPublicFields(this TypeDefinition typeDefinition) { while (typeDefinition != null) { foreach (FieldDefinition field in typeDefinition.Fields) { - if (field.IsStatic || field.IsPrivate) + // ignore static, private, protected fields + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3485 + // credit: James Frowen + if (field.IsStatic || field.IsPrivate || field.IsFamily) + continue; + + // also ignore internal fields + // we dont want to create different writers for this type if they are in current dll or another dll + // so we have to ignore internal in all cases + if (field.IsAssembly) continue; if (field.IsNotSerialized) @@ -311,13 +262,98 @@ public static IEnumerable FindAllPublicFields(this TypeDefiniti try { - typeDefinition = typeDefinition.BaseType.Resolve(); + typeDefinition = typeDefinition.BaseType?.Resolve(); } - catch + catch (AssemblyResolutionException) { break; } } } + + public static bool ContainsClass(this ModuleDefinition module, string nameSpace, string className) => + module.GetTypes().Any(td => td.Namespace == nameSpace && + td.Name == className); + + + public static AssemblyNameReference FindReference(this ModuleDefinition module, string referenceName) + { + foreach (AssemblyNameReference reference in module.AssemblyReferences) + { + if (reference.Name == referenceName) + return reference; + } + return null; + } + + // Takes generic arguments from child class and applies them to parent reference, if possible + // eg makes `Base` in Child : Base have `int` instead of `T` + // Originally by James-Frowen under MIT + // https://github.com/MirageNet/Mirage/commit/cf91e1d54796866d2cf87f8e919bb5c681977e45 + public static TypeReference ApplyGenericParameters(this TypeReference parentReference, + TypeReference childReference) + { + // If the parent is not generic, we got nothing to apply + if (!parentReference.IsGenericInstance) + return parentReference; + + GenericInstanceType parentGeneric = (GenericInstanceType)parentReference; + // make new type so we can replace the args on it + // resolve it so we have non-generic instance (eg just instance with instead of ) + // if we don't cecil will make it double generic (eg INVALID IL) + GenericInstanceType generic = new GenericInstanceType(parentReference.Resolve()); + foreach (TypeReference arg in parentGeneric.GenericArguments) + generic.GenericArguments.Add(arg); + + for (int i = 0; i < generic.GenericArguments.Count; i++) + { + // if arg is not generic + // eg List would be int so not generic. + // But List would be T so is generic + if (!generic.GenericArguments[i].IsGenericParameter) + continue; + + // get the generic name, eg T + string name = generic.GenericArguments[i].Name; + // find what type T is, eg turn it into `int` if `List` + TypeReference arg = FindMatchingGenericArgument(childReference, name); + + // import just to be safe + TypeReference imported = parentReference.Module.ImportReference(arg); + // set arg on generic, parent ref will be Base instead of just Base + generic.GenericArguments[i] = imported; + } + + return generic; + } + + // Finds the type reference for a generic parameter with the provided name in the child reference + // Originally by James-Frowen under MIT + // https://github.com/MirageNet/Mirage/commit/cf91e1d54796866d2cf87f8e919bb5c681977e45 + static TypeReference FindMatchingGenericArgument(TypeReference childReference, string paramName) + { + TypeDefinition def = childReference.Resolve(); + // child class must be generic if we are in this part of the code + // eg Child : Base <--- child must have generic if Base has T + // vs Child : Base <--- wont be here if Base has int (we check if T exists before calling this) + if (!def.HasGenericParameters) + throw new InvalidOperationException( + "Base class had generic parameters, but could not find them in child class"); + + // go through parameters in child class, and find the generic that matches the name + for (int i = 0; i < def.GenericParameters.Count; i++) + { + GenericParameter param = def.GenericParameters[i]; + if (param.Name == paramName) + { + GenericInstanceType generic = (GenericInstanceType)childReference; + // return generic arg with same index + return generic.GenericArguments[i]; + } + } + + // this should never happen, if it does it means that this code is bugged + throw new InvalidOperationException("Did not find matching generic"); + } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Extensions.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Extensions.cs.meta index 78660f9085..505a8db2d6 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Extensions.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Extensions.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Extensions.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Helpers.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Helpers.cs index 44398fd85a..56b7385100 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Helpers.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Helpers.cs @@ -1,25 +1,26 @@ -using System.Diagnostics; using System.IO; +using System.Linq; using System.Reflection; +using Mono.CecilX; namespace Mirror.Weaver { static class Helpers { // This code is taken from SerializationWeaver - public static string UnityEngineDllDirectoryName() { string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); return directoryName?.Replace(@"file:\", ""); } - public static string DestinationFileFor(string outputDir, string assemblyPath) + public static bool IsEditorAssembly(AssemblyDefinition currentAssembly) { - string fileName = Path.GetFileName(assemblyPath); - Debug.Assert(fileName != null, "fileName != null"); - - return Path.Combine(outputDir, fileName); + // we want to add the [InitializeOnLoad] attribute if it's available + // -> usually either 'UnityEditor' or 'UnityEditor.CoreModule' + return currentAssembly.MainModule.AssemblyReferences.Any(assemblyReference => + assemblyReference.Name.StartsWith(nameof(UnityEditor)) + ); } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Helpers.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Helpers.cs.meta index 231f5396fd..488216786c 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Helpers.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Helpers.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Helpers.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Log.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Log.cs deleted file mode 100644 index 75d09321a4..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Log.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace Mirror.Weaver -{ - public static class Log - { - public static Action WarningMethod; - public static Action ErrorMethod; - - public static void Warning(string msg) - { - WarningMethod(msg); - } - - public static void Error(string msg) - { - ErrorMethod(msg); - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Log.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Log.cs.meta deleted file mode 100644 index 3f62978c19..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Log.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2a21c60c40a4c4d679c2b71a7c40882e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Logger.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Logger.cs new file mode 100644 index 0000000000..8be978f28f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Logger.cs @@ -0,0 +1,13 @@ +using Mono.CecilX; + +namespace Mirror.Weaver +{ + // not static, because ILPostProcessor is multithreaded + public interface Logger + { + void Warning(string message); + void Warning(string message, MemberReference mr); + void Error(string message); + void Error(string message, MemberReference mr); + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Logger.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Logger.cs.meta new file mode 100644 index 0000000000..b14558d778 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Logger.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 2a21c60c40a4c4d679c2b71a7c40882e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Logger.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Mirror.Weaver.asmdef b/Assets/ImportedAssets/Mirror/Editor/Weaver/Mirror.Weaver.asmdef deleted file mode 100644 index 5122428309..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Mirror.Weaver.asmdef +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "Mirror.Weaver", - "references": [], - "optionalUnityReferences": [], - "includePlatforms": [ - "Editor" - ], - "excludePlatforms": [], - "allowUnsafeCode": true, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [] -} \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Mirror.Weaver.asmdef.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Mirror.Weaver.asmdef.meta deleted file mode 100644 index b65a0cd379..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Mirror.Weaver.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 1d0b9d21c3ff546a4aa32399dfd33474 -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs index 6911e8077d..db2d5af74d 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs @@ -3,19 +3,18 @@ namespace Mirror.Weaver { - /// - /// Processes [Command] methods in NetworkBehaviour - /// + // Processes [Command] methods in NetworkBehaviour public static class CommandProcessor { /* // generates code like: public void CmdThrust(float thrusting, int spin) { - NetworkWriter networkWriter = new NetworkWriter(); - networkWriter.Write(thrusting); - networkWriter.WritePackedUInt32((uint)spin); - base.SendCommandInternal(cmdName, networkWriter, cmdName); + NetworkWriterPooled writer = NetworkWriterPool.Get(); + writer.Write(thrusting); + writer.WritePackedUInt32((uint)spin); + base.SendCommandInternal(cmdName, cmdHash, writer, channel); + NetworkWriterPool.Return(writer); } public void CallCmdThrust(float thrusting, int spin) @@ -31,42 +30,44 @@ and replaces the body of the original method with the send message code. This way we do not need to modify the code anywhere else, and this works correctly in dependent assemblies */ - public static MethodDefinition ProcessCommandCall(TypeDefinition td, MethodDefinition md, CustomAttribute commandAttr) + public static MethodDefinition ProcessCommandCall(WeaverTypes weaverTypes, Writers writers, Logger Log, TypeDefinition td, MethodDefinition md, CustomAttribute commandAttr, ref bool WeavingFailed) { - MethodDefinition cmd = MethodProcessor.SubstituteMethod(td, md); + MethodDefinition cmd = MethodProcessor.SubstituteMethod(Log, td, md, ref WeavingFailed); ILProcessor worker = md.Body.GetILProcessor(); - NetworkBehaviourProcessor.WriteSetupLocals(worker); + NetworkBehaviourProcessor.WriteSetupLocals(worker, weaverTypes); // NetworkWriter writer = new NetworkWriter(); - NetworkBehaviourProcessor.WriteCreateWriter(worker); + NetworkBehaviourProcessor.WriteGetWriter(worker, weaverTypes); // write all the arguments that the user passed to the Cmd call - if (!NetworkBehaviourProcessor.WriteArguments(worker, md, RemoteCallType.Command)) + if (!NetworkBehaviourProcessor.WriteArguments(worker, writers, Log, md, RemoteCallType.Command, ref WeavingFailed)) return null; - string cmdName = md.Name; int channel = commandAttr.GetField("channel", 0); - bool ignoreAuthority = commandAttr.GetField("ignoreAuthority", false); + bool requiresAuthority = commandAttr.GetField("requiresAuthority", true); // invoke internal send and return // load 'base.' to call the SendCommand function with - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldtoken, td)); - // invokerClass - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.getTypeFromHandleReference)); - worker.Append(worker.Create(OpCodes.Ldstr, cmdName)); + worker.Emit(OpCodes.Ldarg_0); + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + worker.Emit(OpCodes.Ldstr, md.FullName); + // pass the function hash so we don't have to compute it at runtime + // otherwise each GetStableHash call requires O(N) complexity. + // noticeable for long function names: + // https://github.com/MirrorNetworking/Mirror/issues/3375 + worker.Emit(OpCodes.Ldc_I4, md.FullName.GetStableHashCode()); // writer - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Ldc_I4, channel)); - worker.Append(worker.Create(ignoreAuthority ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.sendCommandInternal)); + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Ldc_I4, channel); + // requiresAuthority ? 1 : 0 + worker.Emit(requiresAuthority ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + worker.Emit(OpCodes.Call, weaverTypes.sendCommandInternal); - NetworkBehaviourProcessor.WriteRecycleWriter(worker); - - worker.Append(worker.Create(OpCodes.Ret)); + NetworkBehaviourProcessor.WriteReturnWriter(worker, weaverTypes); + worker.Emit(OpCodes.Ret); return cmd; } @@ -81,31 +82,33 @@ protected static void InvokeCmdCmdThrust(NetworkBehaviour obj, NetworkReader rea ((ShipControl)obj).CmdThrust(reader.ReadSingle(), (int)reader.ReadPackedUInt32()); } */ - public static MethodDefinition ProcessCommandInvoke(TypeDefinition td, MethodDefinition method, MethodDefinition cmdCallFunc) + public static MethodDefinition ProcessCommandInvoke(WeaverTypes weaverTypes, Readers readers, Logger Log, TypeDefinition td, MethodDefinition method, MethodDefinition cmdCallFunc, ref bool WeavingFailed) { - MethodDefinition cmd = new MethodDefinition(Weaver.InvokeRpcPrefix + method.Name, + string cmdName = Weaver.GenerateMethodName(RemoteCalls.RemoteProcedureCalls.InvokeRpcPrefix, method); + + MethodDefinition cmd = new MethodDefinition(cmdName, MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig, - WeaverTypes.voidType); + weaverTypes.Import(typeof(void))); ILProcessor worker = cmd.Body.GetILProcessor(); Instruction label = worker.Create(OpCodes.Nop); - NetworkBehaviourProcessor.WriteServerActiveCheck(worker, method.Name, label, "Command"); + NetworkBehaviourProcessor.WriteServerActiveCheck(worker, weaverTypes, method.Name, label, "Command"); // setup for reader - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Castclass, td)); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Castclass, td); - if (!NetworkBehaviourProcessor.ReadArguments(method, worker, RemoteCallType.Command)) + if (!NetworkBehaviourProcessor.ReadArguments(method, readers, Log, worker, RemoteCallType.Command, ref WeavingFailed)) return null; AddSenderConnection(method, worker); // invoke actual command function - worker.Append(worker.Create(OpCodes.Callvirt, cmdCallFunc)); - worker.Append(worker.Create(OpCodes.Ret)); + worker.Emit(OpCodes.Callvirt, cmdCallFunc); + worker.Emit(OpCodes.Ret); - NetworkBehaviourProcessor.AddInvokeParameters(cmd.Parameters); + NetworkBehaviourProcessor.AddInvokeParameters(weaverTypes, cmd.Parameters); td.Methods.Add(cmd); return cmd; @@ -118,8 +121,8 @@ static void AddSenderConnection(MethodDefinition method, ILProcessor worker) if (NetworkBehaviourProcessor.IsSenderConnection(param, RemoteCallType.Command)) { // NetworkConnection is 3nd arg (arg0 is "obj" not "this" because method is static) - // exmaple: static void InvokeCmdCmdSendCommand(NetworkBehaviour obj, NetworkReader reader, NetworkConnection connection) - worker.Append(worker.Create(OpCodes.Ldarg_2)); + // example: static void InvokeCmdCmdSendCommand(NetworkBehaviour obj, NetworkReader reader, NetworkConnection connection) + worker.Emit(OpCodes.Ldarg_2); } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta index 20c3e154f8..f61dd4c8d9 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/GenericArgumentResolver.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/GenericArgumentResolver.cs deleted file mode 100644 index 1336f6555b..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/GenericArgumentResolver.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System.Collections.Generic; -using Mono.CecilX; - -namespace Mirror.Weaver -{ - public class GenericArgumentResolver - { - readonly Stack stack = new Stack(); - readonly int maxGenericArgument; - - public GenericArgumentResolver(int maxGenericArgument) - { - this.maxGenericArgument = maxGenericArgument; - } - - public bool GetGenericFromBaseClass(TypeDefinition td, int genericArgument, TypeReference baseType, out TypeReference itemType) - { - itemType = null; - if (GetGenericBaseType(td, baseType, out GenericInstanceType parent)) - { - TypeReference arg = parent.GenericArguments[genericArgument]; - if (arg.IsGenericParameter) - { - itemType = FindParameterInStack(td, genericArgument); - } - else - { - itemType = Weaver.CurrentAssembly.MainModule.ImportReference(arg); - } - } - - return itemType != null; - } - - TypeReference FindParameterInStack(TypeDefinition td, int genericArgument) - { - while (stack.Count > 0) - { - TypeReference next = stack.Pop(); - - if (!(next is GenericInstanceType genericType)) - { - // if type is not GenericInstanceType something has gone wrong - return null; - } - - if (genericType.GenericArguments.Count < genericArgument) - { - // if less than `genericArgument` then we didnt find generic argument - return null; - } - - if (genericType.GenericArguments.Count > maxGenericArgument) - { - // if greater than `genericArgument` it is hard to know which generic arg we want - // See SyncListGenericInheritanceWithMultipleGeneric test - Weaver.Error($"Type {td.Name} has too many generic arguments in base class {next}", td); - return null; - } - - TypeReference genericArg = genericType.GenericArguments[genericArgument]; - if (!genericArg.IsGenericParameter) - { - // if not generic, successfully found type - return Weaver.CurrentAssembly.MainModule.ImportReference(genericArg); - } - } - - // nothing left in stack, something went wrong - return null; - } - - bool GetGenericBaseType(TypeDefinition td, TypeReference baseType, out GenericInstanceType found) - { - stack.Clear(); - TypeReference parent = td.BaseType; - found = null; - - while (parent != null) - { - string parentName = parent.FullName; - - // strip generic parameters from class name (if any) - parentName = Extensions.StripGenericParametersFromClassName(parentName); - - if (parentName == baseType.FullName) - { - found = parent as GenericInstanceType; - break; - } - - try - { - stack.Push(parent); - parent = parent.Resolve().BaseType; - } - catch (AssemblyResolutionException) - { - // this can happen for plugins. - break; - } - } - - return found != null; - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs deleted file mode 100644 index 7e22577e8f..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs +++ /dev/null @@ -1,199 +0,0 @@ -using System.Linq; -using Mono.CecilX; -using Mono.CecilX.Cil; - -namespace Mirror.Weaver -{ - /// - /// generates OnSerialize/OnDeserialize when inheriting from MessageBase - /// - static class MessageClassProcessor - { - - static bool IsEmptyDefault(this MethodBody body) - { - return body.Instructions.All(instruction => instruction.OpCode == OpCodes.Nop || instruction.OpCode == OpCodes.Ret); - } - - public static void Process(TypeDefinition td) - { - Weaver.DLog(td, "MessageClassProcessor Start"); - - GenerateSerialization(td); - if (Weaver.WeavingFailed) - { - return; - } - - GenerateDeSerialization(td); - Weaver.DLog(td, "MessageClassProcessor Done"); - } - - static void GenerateSerialization(TypeDefinition td) - { - Weaver.DLog(td, " GenerateSerialization"); - MethodDefinition existingMethod = td.GetMethodWith1Arg("Serialize", WeaverTypes.NetworkWriterType); - // do nothing if method exists and is abstract or not empty - if (existingMethod != null && (existingMethod.IsAbstract || !existingMethod.Body.IsEmptyDefault())) - { - return; - } - - if (td.Fields.Count == 0) - { - return; - } - - // check for self-referencing types - foreach (FieldDefinition field in td.Fields) - { - if (field.FieldType.FullName == td.FullName) - { - Weaver.Error($"{td.Name} has field {field.Name} that references itself", field); - return; - } - } - - MethodDefinition serializeFunc = existingMethod ?? new MethodDefinition("Serialize", - MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, - WeaverTypes.voidType); - - //only add to new method - if (existingMethod == null) - { - serializeFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkWriterType))); - } - ILProcessor worker = serializeFunc.Body.GetILProcessor(); - if (existingMethod != null) - { - //remove default nop&ret from existing empty interface method - worker.Body.Instructions.Clear(); - } - - // if it is not a struct, call base - if (!td.IsValueType) - { - // call base - CallBase(td, worker, "Serialize"); - } - - foreach (FieldDefinition field in td.Fields) - { - if (field.IsStatic || field.IsPrivate || field.IsSpecialName) - continue; - - CallWriter(worker, field); - } - worker.Append(worker.Create(OpCodes.Ret)); - - //only add if not just replaced body - if (existingMethod == null) - { - td.Methods.Add(serializeFunc); - } - } - - static void CallWriter(ILProcessor worker, FieldDefinition field) - { - MethodReference writeFunc = Writers.GetWriteFunc(field.FieldType); - if (writeFunc != null) - { - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, field)); - worker.Append(worker.Create(OpCodes.Call, writeFunc)); - } - else - { - Weaver.Error($"{field.Name} has unsupported type", field); - } - } - - static void CallBase(TypeDefinition td, ILProcessor worker, string name) - { - MethodReference method = Resolvers.TryResolveMethodInParents(td.BaseType, Weaver.CurrentAssembly, name); - - // dont call method if it is null or abstract - if (method == null || method.Resolve().IsAbstract) - { - return; - } - - // base - worker.Append(worker.Create(OpCodes.Ldarg_0)); - // writer - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Call, method)); - } - - static void GenerateDeSerialization(TypeDefinition td) - { - Weaver.DLog(td, " GenerateDeserialization"); - MethodDefinition existingMethod = td.GetMethodWith1Arg("Deserialize", WeaverTypes.NetworkReaderType); - - // do nothing if method exists and is abstract or not empty - if (existingMethod != null && (existingMethod.IsAbstract || !existingMethod.Body.IsEmptyDefault())) - { - return; - } - - if (td.Fields.Count == 0) - { - return; - } - - MethodDefinition serializeFunc = existingMethod ?? new MethodDefinition("Deserialize", - MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, - WeaverTypes.voidType); - - //only add to new method - if (existingMethod == null) - { - serializeFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkReaderType))); - } - ILProcessor worker = serializeFunc.Body.GetILProcessor(); - if (existingMethod != null) - { - //remove default nop&ret from existing empty interface method - worker.Body.Instructions.Clear(); - } - - // if not value type, call base - if (!td.IsValueType) - { - CallBase(td, worker, "Deserialize"); - } - - foreach (FieldDefinition field in td.Fields) - { - if (field.IsStatic || field.IsPrivate || field.IsSpecialName) - continue; - - CallReader(worker, field); - } - worker.Append(worker.Create(OpCodes.Ret)); - - //only add if not just replaced body - if (existingMethod == null) - { - td.Methods.Add(serializeFunc); - } - } - - static void CallReader(ILProcessor worker, FieldDefinition field) - { - MethodReference readerFunc = Readers.GetReadFunc(field.FieldType); - if (readerFunc != null) - { - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Call, readerFunc)); - worker.Append(worker.Create(OpCodes.Stfld, field)); - } - else - { - Weaver.Error($"{field.Name} has unsupported type", field); - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs index 6ea5663d9d..8a4c581ecb 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs @@ -5,36 +5,31 @@ namespace Mirror.Weaver { public static class MethodProcessor { - private const string RpcPrefix = "UserCode_"; - - // creates a method substitute - // For example, if we have this: - // public void CmdThrust(float thrusting, int spin) - // { - // xxxxx - // } - // - // it will substitute the method and move the code to a new method with a provided name - // for example: - // - // public void CmdTrust(float thrusting, int spin) - // { - // } - // - // public void (float thrusting, int spin) - // { - // xxxxx - // } - // - // Note that all the calls to the method remain untouched + const string RpcPrefix = "UserCode_"; + + // For a function like + // [ClientRpc] void RpcTest(int value), + // Weaver substitutes the method and moves the code to a new method: + // UserCode_RpcTest(int value) <- contains original code + // RpcTest(int value) <- serializes parameters, sends the message // - // the original method definition loses all code - // this returns the newly created method with all the user provided code - public static MethodDefinition SubstituteMethod(TypeDefinition td, MethodDefinition md) + // Note that all the calls to the method remain untouched. + // FixRemoteCallToBaseMethod replaces them afterwards. + public static MethodDefinition SubstituteMethod(Logger Log, TypeDefinition td, MethodDefinition md, ref bool WeavingFailed) { - string newName = RpcPrefix + md.Name; + string newName = Weaver.GenerateMethodName(RpcPrefix, md); + MethodDefinition cmd = new MethodDefinition(newName, md.Attributes, md.ReturnType); + // force the substitute method to be protected. + // -> public would show in the Inspector for UnityEvents as + // User_CmdUsePotion() etc. but the user shouldn't use those. + // -> private would not allow inheriting classes to call it, see + // OverrideVirtualWithBaseCallsBothVirtualAndBase test. + // -> IL has no concept of 'protected', it's called IsFamily there. + cmd.IsPublic = false; + cmd.IsFamily = true; + // add parameters foreach (ParameterDefinition pd in md.Parameters) { @@ -57,52 +52,71 @@ public static MethodDefinition SubstituteMethod(TypeDefinition td, MethodDefinit td.Methods.Add(cmd); - FixRemoteCallToBaseMethod(td, cmd); + FixRemoteCallToBaseMethod(Log, td, cmd, ref WeavingFailed); return cmd; } - /// - /// Finds and fixes call to base methods within remote calls - /// For example, changes `base.CmdDoSomething` to `base.CallCmdDoSomething` within `this.CallCmdDoSomething` - /// - /// - /// - public static void FixRemoteCallToBaseMethod(TypeDefinition type, MethodDefinition method) + // For a function like + // [ClientRpc] void RpcTest(int value), + // Weaver substitutes the method and moves the code to a new method: + // UserCode_RpcTest(int value) <- contains original code + // RpcTest(int value) <- serializes parameters, sends the message + // + // FixRemoteCallToBaseMethod replaces all calls to + // RpcTest(value) + // with + // UserCode_RpcTest(value) + public static void FixRemoteCallToBaseMethod(Logger Log, TypeDefinition type, MethodDefinition method, ref bool WeavingFailed) { string callName = method.Name; // Cmd/rpc start with Weaver.RpcPrefix - // eg CallCmdDoSomething + // e.g. CallCmdDoSomething if (!callName.StartsWith(RpcPrefix)) return; - // eg CmdDoSomething + // e.g. CmdDoSomething string baseRemoteCallName = method.Name.Substring(RpcPrefix.Length); foreach (Instruction instruction in method.Body.Instructions) { - // if call to base.CmdDoSomething within this.CallCmdDoSomething - if (IsCallToMethod(instruction, out MethodDefinition calledMethod) && - calledMethod.Name == baseRemoteCallName) + // is this instruction a Call to a method? + // if yes, output the method so we can check it. + if (IsCallToMethod(instruction, out MethodDefinition calledMethod)) { - TypeDefinition baseType = type.BaseType.Resolve(); - MethodDefinition baseMethod = baseType.GetMethodInBaseType(callName); - - if (baseMethod == null) + // when considering if 'calledMethod' is a call to 'method', + // we originally compared .Name. + // + // to fix IL2CPP build bugs with overloaded Rpcs, we need to + // generated rpc names like + // RpcTest(string value) => RpcTestString(strig value) + // RpcTest(int value) => RpcTestInt(int value) + // to make them unique. + // + // calledMethod.Name is still "RpcTest", so we need to + // convert this to the generated name as well before comparing. + string calledMethodName_Generated = Weaver.GenerateMethodName("", calledMethod); + if (calledMethodName_Generated == baseRemoteCallName) { - Weaver.Error($"Could not find base method for {callName}", method); - return; + TypeDefinition baseType = type.BaseType.Resolve(); + MethodDefinition baseMethod = baseType.GetMethodInBaseType(callName); + + if (baseMethod == null) + { + Log.Error($"Could not find base method for {callName}", method); + WeavingFailed = true; + return; + } + + if (!baseMethod.IsVirtual) + { + Log.Error($"Could not find base method that was virtual {callName}", method); + WeavingFailed = true; + return; + } + + instruction.Operand = baseMethod; } - - if (!baseMethod.IsVirtual) - { - Weaver.Error($"Could not find base method that was virutal {callName}", method); - return; - } - - instruction.Operand = baseMethod; - - Weaver.DLog(type, "Replacing call to '{0}' with '{1}' inside '{2}'", calledMethod.FullName, baseMethod.FullName, method.FullName); } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs.meta index 3c8189403e..9e9ae0ad62 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs index 09d39e4a5a..e88c5d6d0e 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs @@ -2,53 +2,53 @@ namespace Mirror.Weaver { - /// - /// only shows warnings in case we use SyncVars etc. for MonoBehaviour. - /// + // only shows warnings in case we use SyncVars etc. for MonoBehaviour. static class MonoBehaviourProcessor { - public static void Process(TypeDefinition td) + public static void Process(Logger Log, TypeDefinition td, ref bool WeavingFailed) { - ProcessSyncVars(td); - ProcessMethods(td); + ProcessSyncVars(Log, td, ref WeavingFailed); + ProcessMethods(Log, td, ref WeavingFailed); } - static void ProcessSyncVars(TypeDefinition td) + static void ProcessSyncVars(Logger Log, TypeDefinition td, ref bool WeavingFailed) { // find syncvars foreach (FieldDefinition fd in td.Fields) { - if (fd.HasCustomAttribute(WeaverTypes.SyncVarType)) - Weaver.Error($"SyncVar {fd.Name} must be inside a NetworkBehaviour. {td.Name} is not a NetworkBehaviour", fd); + if (fd.HasCustomAttribute()) + { + Log.Error($"SyncVar {fd.Name} must be inside a NetworkBehaviour. {td.Name} is not a NetworkBehaviour", fd); + WeavingFailed = true; + } if (SyncObjectInitializer.ImplementsSyncObject(fd.FieldType)) { - Weaver.Error($"{fd.Name} is a SyncObject and must be inside a NetworkBehaviour. {td.Name} is not a NetworkBehaviour", fd); + Log.Error($"{fd.Name} is a SyncObject and must be inside a NetworkBehaviour. {td.Name} is not a NetworkBehaviour", fd); + WeavingFailed = true; } } } - static void ProcessMethods(TypeDefinition td) + static void ProcessMethods(Logger Log, TypeDefinition td, ref bool WeavingFailed) { // find command and RPC functions foreach (MethodDefinition md in td.Methods) { - foreach (CustomAttribute ca in md.CustomAttributes) + if (md.HasCustomAttribute()) { - if (ca.AttributeType.FullName == WeaverTypes.CommandType.FullName) - { - Weaver.Error($"Command {md.Name} must be declared inside a NetworkBehaviour", md); - } - - if (ca.AttributeType.FullName == WeaverTypes.ClientRpcType.FullName) - { - Weaver.Error($"ClientRpc {md.Name} must be declared inside a NetworkBehaviour", md); - } - - if (ca.AttributeType.FullName == WeaverTypes.TargetRpcType.FullName) - { - Weaver.Error($"TargetRpc {md.Name} must be declared inside a NetworkBehaviour", md); - } + Log.Error($"Command {md.Name} must be declared inside a NetworkBehaviour", md); + WeavingFailed = true; + } + if (md.HasCustomAttribute()) + { + Log.Error($"ClientRpc {md.Name} must be declared inside a NetworkBehaviour", md); + WeavingFailed = true; + } + if (md.HasCustomAttribute()) + { + Log.Error($"TargetRpc {md.Name} must be declared inside a NetworkBehaviour", md); + WeavingFailed = true; } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta index ef3f5f445d..c4cf109e6d 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs index a02dbc7507..47f1b94048 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs @@ -8,95 +8,97 @@ public enum RemoteCallType { Command, ClientRpc, - TargetRpc, - SyncEvent + TargetRpc } - - /// - /// processes SyncVars, Cmds, Rpcs, etc. of NetworkBehaviours - /// + // processes SyncVars, Cmds, Rpcs, etc. of NetworkBehaviours class NetworkBehaviourProcessor { + AssemblyDefinition assembly; + WeaverTypes weaverTypes; + SyncVarAccessLists syncVarAccessLists; + SyncVarAttributeProcessor syncVarAttributeProcessor; + Writers writers; + Readers readers; + Logger Log; + List syncVars = new List(); List syncObjects = new List(); // Dictionary syncVarNetIds = new Dictionary(); + // - Every syncvar with a hook has a new field created to store the Action delegate so we don't allocate on every hook invocation + // This dictionary maps each syncvar field to the field that will store the hook method delegate instance, and the method from which the delegate instance is constructed from + Dictionary syncVarHookDelegates = new Dictionary(); readonly List commands = new List(); readonly List clientRpcs = new List(); readonly List targetRpcs = new List(); - readonly List eventRpcs = new List(); readonly List commandInvocationFuncs = new List(); readonly List clientRpcInvocationFuncs = new List(); readonly List targetRpcInvocationFuncs = new List(); - readonly List eventRpcInvocationFuncs = new List(); readonly TypeDefinition netBehaviourSubclass; public struct CmdResult { public MethodDefinition method; - public bool ignoreAuthority; + public bool requiresAuthority; } public struct ClientRpcResult { public MethodDefinition method; - public bool excludeOwner; + public bool includeOwner; } - public NetworkBehaviourProcessor(TypeDefinition td) + public NetworkBehaviourProcessor(AssemblyDefinition assembly, WeaverTypes weaverTypes, SyncVarAccessLists syncVarAccessLists, Writers writers, Readers readers, Logger Log, TypeDefinition td) { - Weaver.DLog(td, "NetworkBehaviourProcessor"); + this.assembly = assembly; + this.weaverTypes = weaverTypes; + this.syncVarAccessLists = syncVarAccessLists; + this.writers = writers; + this.readers = readers; + this.Log = Log; + syncVarAttributeProcessor = new SyncVarAttributeProcessor(assembly, weaverTypes, syncVarAccessLists, Log); netBehaviourSubclass = td; } // return true if modified - public bool Process() + public bool Process(ref bool WeavingFailed) { // only process once if (WasProcessed(netBehaviourSubclass)) { return false; } - Weaver.DLog(netBehaviourSubclass, "Found NetworkBehaviour " + netBehaviourSubclass.FullName); - if (netBehaviourSubclass.HasGenericParameters) - { - Weaver.Error($"{netBehaviourSubclass.Name} cannot have generic parameters", netBehaviourSubclass); - // originally Process returned true in every case, except if already processed. - // maybe return false here in the future. - return true; - } - Weaver.DLog(netBehaviourSubclass, "Process Start"); MarkAsProcessed(netBehaviourSubclass); // deconstruct tuple and set fields - (syncVars, syncVarNetIds) = SyncVarProcessor.ProcessSyncVars(netBehaviourSubclass); + (syncVars, syncVarNetIds, syncVarHookDelegates) = syncVarAttributeProcessor.ProcessSyncVars(netBehaviourSubclass, ref WeavingFailed); - syncObjects = SyncObjectProcessor.FindSyncObjectsFields(netBehaviourSubclass); + syncObjects = SyncObjectProcessor.FindSyncObjectsFields(writers, readers, Log, netBehaviourSubclass, ref WeavingFailed); - ProcessMethods(); - - SyncEventProcessor.ProcessEvents(netBehaviourSubclass, eventRpcs, eventRpcInvocationFuncs); - if (Weaver.WeavingFailed) + ProcessMethods(ref WeavingFailed); + if (WeavingFailed) { // originally Process returned true in every case, except if already processed. // maybe return false here in the future. return true; } - GenerateConstants(); - GenerateSerialization(); - if (Weaver.WeavingFailed) + // inject initializations into static & instance constructor + InjectIntoStaticConstructor(ref WeavingFailed); + InjectIntoInstanceConstructor(ref WeavingFailed); + + GenerateSerialization(ref WeavingFailed); + if (WeavingFailed) { // originally Process returned true in every case, except if already processed. // maybe return false here in the future. return true; } - GenerateDeSerialization(); - Weaver.DLog(netBehaviourSubclass, "Process Done"); + GenerateDeSerialization(ref WeavingFailed); return true; } @@ -107,15 +109,15 @@ public bool Process() which is used in InvokeCmd, InvokeRpc, etc. */ - public static void WriteClientActiveCheck(ILProcessor worker, string mdName, Instruction label, string errString) + public static void WriteClientActiveCheck(ILProcessor worker, WeaverTypes weaverTypes, string mdName, Instruction label, string errString) { // client active check - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.NetworkClientGetActive)); - worker.Append(worker.Create(OpCodes.Brtrue, label)); + worker.Emit(OpCodes.Call, weaverTypes.NetworkClientGetActive); + worker.Emit(OpCodes.Brtrue, label); - worker.Append(worker.Create(OpCodes.Ldstr, errString + " " + mdName + " called on server.")); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.logErrorReference)); - worker.Append(worker.Create(OpCodes.Ret)); + worker.Emit(OpCodes.Ldstr, $"{errString} {mdName} called on server."); + worker.Emit(OpCodes.Call, weaverTypes.logErrorReference); + worker.Emit(OpCodes.Ret); worker.Append(label); } /* @@ -123,39 +125,39 @@ public static void WriteClientActiveCheck(ILProcessor worker, string mdName, Ins if (!NetworkServer.active) Debug.LogError((object) "Command CmdMsgWhisper called on client."); */ - public static void WriteServerActiveCheck(ILProcessor worker, string mdName, Instruction label, string errString) + public static void WriteServerActiveCheck(ILProcessor worker, WeaverTypes weaverTypes, string mdName, Instruction label, string errString) { // server active check - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.NetworkServerGetActive)); - worker.Append(worker.Create(OpCodes.Brtrue, label)); + worker.Emit(OpCodes.Call, weaverTypes.NetworkServerGetActive); + worker.Emit(OpCodes.Brtrue, label); - worker.Append(worker.Create(OpCodes.Ldstr, errString + " " + mdName + " called on client.")); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.logErrorReference)); - worker.Append(worker.Create(OpCodes.Ret)); + worker.Emit(OpCodes.Ldstr, $"{errString} {mdName} called on client."); + worker.Emit(OpCodes.Call, weaverTypes.logErrorReference); + worker.Emit(OpCodes.Ret); worker.Append(label); } - public static void WriteSetupLocals(ILProcessor worker) + public static void WriteSetupLocals(ILProcessor worker, WeaverTypes weaverTypes) { worker.Body.InitLocals = true; - worker.Body.Variables.Add(new VariableDefinition(WeaverTypes.PooledNetworkWriterType)); + worker.Body.Variables.Add(new VariableDefinition(weaverTypes.Import())); } - public static void WriteCreateWriter(ILProcessor worker) + public static void WriteGetWriter(ILProcessor worker, WeaverTypes weaverTypes) { // create writer - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.GetPooledWriterReference)); - worker.Append(worker.Create(OpCodes.Stloc_0)); + worker.Emit(OpCodes.Call, weaverTypes.GetWriterReference); + worker.Emit(OpCodes.Stloc_0); } - public static void WriteRecycleWriter(ILProcessor worker) + public static void WriteReturnWriter(ILProcessor worker, WeaverTypes weaverTypes) { // NetworkWriterPool.Recycle(writer); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.RecycleWriterReference)); + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Call, weaverTypes.ReturnWriterReference); } - public static bool WriteArguments(ILProcessor worker, MethodDefinition method, RemoteCallType callType) + public static bool WriteArguments(ILProcessor worker, Writers writers, Logger Log, MethodDefinition method, RemoteCallType callType, ref bool WeavingFailed) { // write each argument // example result @@ -164,8 +166,8 @@ public static bool WriteArguments(ILProcessor worker, MethodDefinition method, R writer.WriteNetworkIdentity(someTarget); */ - bool skipFirst = (callType == RemoteCallType.TargetRpc - && TargetRpcProcessor.HasNetworkConnectionParameter(method)); + bool skipFirst = callType == RemoteCallType.TargetRpc + && TargetRpcProcessor.HasNetworkConnectionParameter(method); // arg of calling function, arg 0 is "this" so start counting at 1 int argNum = 1; @@ -185,52 +187,82 @@ public static bool WriteArguments(ILProcessor worker, MethodDefinition method, R continue; } - MethodReference writeFunc = Writers.GetWriteFunc(param.ParameterType); + MethodReference writeFunc = writers.GetWriteFunc(param.ParameterType, ref WeavingFailed); if (writeFunc == null) { - Weaver.Error($"{method.Name} has invalid parameter {param}", method); + Log.Error($"{method.Name} has invalid parameter {param}", method); + WeavingFailed = true; return false; } // use built-in writer func on writer object // NetworkWriter object - worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Emit(OpCodes.Ldloc_0); // add argument to call - worker.Append(worker.Create(OpCodes.Ldarg, argNum)); + worker.Emit(OpCodes.Ldarg, argNum); // call writer extension method - worker.Append(worker.Create(OpCodes.Call, writeFunc)); + worker.Emit(OpCodes.Call, writeFunc); argNum += 1; } return true; } #region mark / check type as processed - public const string ProcessedFunctionName = "MirrorProcessed"; + public const string ProcessedFunctionName = "Weaved"; - // by adding an empty MirrorProcessed() function + // check if the type has a "Weaved" function already public static bool WasProcessed(TypeDefinition td) { return td.GetMethod(ProcessedFunctionName) != null; } - public static void MarkAsProcessed(TypeDefinition td) + // add the Weaved() function which returns true. + // can be called at runtime and from tests to check if weaving succeeded. + public void MarkAsProcessed(TypeDefinition td) { if (!WasProcessed(td)) { - MethodDefinition versionMethod = new MethodDefinition(ProcessedFunctionName, MethodAttributes.Private, WeaverTypes.voidType); + // add a function: + // public override bool MirrorProcessed() { return true; } + // ReuseSlot means 'override'. + MethodDefinition versionMethod = new MethodDefinition( + ProcessedFunctionName, + MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.ReuseSlot, + weaverTypes.Import(typeof(bool))); ILProcessor worker = versionMethod.Body.GetILProcessor(); - worker.Append(worker.Create(OpCodes.Ret)); + worker.Emit(OpCodes.Ldc_I4_1); + worker.Emit(OpCodes.Ret); td.Methods.Add(versionMethod); } } #endregion - void GenerateConstants() + // helper function to remove 'Ret' from the end of the method if 'Ret' + // is the last instruction. + // returns false if there was an issue + static bool RemoveFinalRetInstruction(MethodDefinition method) { - if (commands.Count == 0 && clientRpcs.Count == 0 && targetRpcs.Count == 0 && eventRpcs.Count == 0 && syncObjects.Count == 0) - return; + // remove the return opcode from end of function. will add our own later. + if (method.Body.Instructions.Count != 0) + { + Instruction retInstr = method.Body.Instructions[method.Body.Instructions.Count - 1]; + if (retInstr.OpCode == OpCodes.Ret) + { + method.Body.Instructions.RemoveAt(method.Body.Instructions.Count - 1); + return true; + } + return false; + } - Weaver.DLog(netBehaviourSubclass, " GenerateConstants "); + // we did nothing, but there was no error. + return true; + } + + // we need to inject several initializations into NetworkBehaviour cctor + void InjectIntoStaticConstructor(ref bool WeavingFailed) + { + if (commands.Count == 0 && clientRpcs.Count == 0 && targetRpcs.Count == 0) + return; // find static constructor MethodDefinition cctor = netBehaviourSubclass.GetMethod(".cctor"); @@ -238,18 +270,11 @@ void GenerateConstants() if (cctor != null) { // remove the return opcode from end of function. will add our own later. - if (cctor.Body.Instructions.Count != 0) + if (!RemoveFinalRetInstruction(cctor)) { - Instruction retInstr = cctor.Body.Instructions[cctor.Body.Instructions.Count - 1]; - if (retInstr.OpCode == OpCodes.Ret) - { - cctor.Body.Instructions.RemoveAt(cctor.Body.Instructions.Count - 1); - } - else - { - Weaver.Error($"{netBehaviourSubclass.Name} has invalid class constructor", cctor); - return; - } + Log.Error($"{netBehaviourSubclass.Name} has invalid class constructor", cctor); + WeavingFailed = true; + return; } } else @@ -260,112 +285,126 @@ void GenerateConstants() MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.Static, - WeaverTypes.voidType); - } - - // find instance constructor - MethodDefinition ctor = netBehaviourSubclass.GetMethod(".ctor"); - - if (ctor == null) - { - Weaver.Error($"{netBehaviourSubclass.Name} has invalid constructor", netBehaviourSubclass); - return; - } - - Instruction ret = ctor.Body.Instructions[ctor.Body.Instructions.Count - 1]; - if (ret.OpCode == OpCodes.Ret) - { - ctor.Body.Instructions.RemoveAt(ctor.Body.Instructions.Count - 1); - } - else - { - Weaver.Error($"{netBehaviourSubclass.Name} has invalid constructor", ctor); - return; + weaverTypes.Import(typeof(void))); } - // TODO: find out if the order below matters. If it doesn't split code below into 2 functions - ILProcessor ctorWorker = ctor.Body.GetILProcessor(); ILProcessor cctorWorker = cctor.Body.GetILProcessor(); + // register all commands in cctor for (int i = 0; i < commands.Count; ++i) { CmdResult cmdResult = commands[i]; - GenerateRegisterCommandDelegate(cctorWorker, WeaverTypes.registerCommandDelegateReference, commandInvocationFuncs[i], cmdResult); + GenerateRegisterCommandDelegate(cctorWorker, weaverTypes.registerCommandReference, commandInvocationFuncs[i], cmdResult); } + // register all client rpcs in cctor for (int i = 0; i < clientRpcs.Count; ++i) { ClientRpcResult clientRpcResult = clientRpcs[i]; - GenerateRegisterRemoteDelegate(cctorWorker, WeaverTypes.registerRpcDelegateReference, clientRpcInvocationFuncs[i], clientRpcResult.method.Name); + GenerateRegisterRemoteDelegate(cctorWorker, weaverTypes.registerRpcReference, clientRpcInvocationFuncs[i], clientRpcResult.method.FullName); } + // register all target rpcs in cctor for (int i = 0; i < targetRpcs.Count; ++i) { - GenerateRegisterRemoteDelegate(cctorWorker, WeaverTypes.registerRpcDelegateReference, targetRpcInvocationFuncs[i], targetRpcs[i].Name); + GenerateRegisterRemoteDelegate(cctorWorker, weaverTypes.registerRpcReference, targetRpcInvocationFuncs[i], targetRpcs[i].FullName); + } + + // add final 'Ret' instruction to cctor + cctorWorker.Append(cctorWorker.Create(OpCodes.Ret)); + if (!cctorFound) + { + netBehaviourSubclass.Methods.Add(cctor); + } + + // in case class had no cctor, it might have BeforeFieldInit, so injected cctor would be called too late + netBehaviourSubclass.Attributes &= ~TypeAttributes.BeforeFieldInit; + } + + // we need to inject several initializations into NetworkBehaviour ctor + void InjectIntoInstanceConstructor(ref bool WeavingFailed) + { + if ((syncObjects.Count == 0) && (syncVarHookDelegates.Count == 0)) + return; + + // find instance constructor + MethodDefinition ctor = netBehaviourSubclass.GetMethod(".ctor"); + if (ctor == null) + { + Log.Error($"{netBehaviourSubclass.Name} has invalid constructor", netBehaviourSubclass); + WeavingFailed = true; + return; } - for (int i = 0; i < eventRpcs.Count; ++i) + // remove the return opcode from end of function. will add our own later. + if (!RemoveFinalRetInstruction(ctor)) { - GenerateRegisterRemoteDelegate(cctorWorker, WeaverTypes.registerEventDelegateReference, eventRpcInvocationFuncs[i], eventRpcs[i].Name); + Log.Error($"{netBehaviourSubclass.Name} has invalid constructor", ctor); + WeavingFailed = true; + return; } + ILProcessor ctorWorker = ctor.Body.GetILProcessor(); + + // initialize all sync objects in ctor foreach (FieldDefinition fd in syncObjects) { - SyncObjectInitializer.GenerateSyncObjectInitializer(ctorWorker, fd); + SyncObjectInitializer.GenerateSyncObjectInitializer(ctorWorker, weaverTypes, fd); } - cctorWorker.Append(cctorWorker.Create(OpCodes.Ret)); - if (!cctorFound) + // initialize all delegate fields in ctor + foreach(KeyValuePair entry in syncVarHookDelegates) { - netBehaviourSubclass.Methods.Add(cctor); + FieldDefinition syncVarField = entry.Key; + (FieldDefinition hookDelegate, MethodDefinition hookMethod) = entry.Value; + syncVarAttributeProcessor.GenerateSyncVarHookDelegateInitializer(ctorWorker, syncVarField, hookDelegate, hookMethod); } - // finish ctor + // add final 'Ret' instruction to ctor ctorWorker.Append(ctorWorker.Create(OpCodes.Ret)); - - // in case class had no cctor, it might have BeforeFieldInit, so injected cctor would be called too late - netBehaviourSubclass.Attributes &= ~TypeAttributes.BeforeFieldInit; } /* // This generates code like: NetworkBehaviour.RegisterCommandDelegate(base.GetType(), "CmdThrust", new NetworkBehaviour.CmdDelegate(ShipControl.InvokeCmdCmdThrust)); */ - void GenerateRegisterRemoteDelegate(ILProcessor worker, MethodReference registerMethod, MethodDefinition func, string cmdName) + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + void GenerateRegisterRemoteDelegate(ILProcessor worker, MethodReference registerMethod, MethodDefinition func, string functionFullName) { - worker.Append(worker.Create(OpCodes.Ldtoken, netBehaviourSubclass)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.getTypeFromHandleReference)); - worker.Append(worker.Create(OpCodes.Ldstr, cmdName)); - worker.Append(worker.Create(OpCodes.Ldnull)); - worker.Append(worker.Create(OpCodes.Ldftn, func)); + worker.Emit(OpCodes.Ldtoken, netBehaviourSubclass); + worker.Emit(OpCodes.Call, weaverTypes.getTypeFromHandleReference); + worker.Emit(OpCodes.Ldstr, functionFullName); + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ldftn, func); - worker.Append(worker.Create(OpCodes.Newobj, WeaverTypes.CmdDelegateConstructor)); + worker.Emit(OpCodes.Newobj, weaverTypes.RemoteCallDelegateConstructor); // - worker.Append(worker.Create(OpCodes.Call, registerMethod)); + worker.Emit(OpCodes.Call, registerMethod); } void GenerateRegisterCommandDelegate(ILProcessor worker, MethodReference registerMethod, MethodDefinition func, CmdResult cmdResult) { - string cmdName = cmdResult.method.Name; - bool ignoreAuthority = cmdResult.ignoreAuthority; + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + string cmdName = cmdResult.method.FullName; + bool requiresAuthority = cmdResult.requiresAuthority; - worker.Append(worker.Create(OpCodes.Ldtoken, netBehaviourSubclass)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.getTypeFromHandleReference)); - worker.Append(worker.Create(OpCodes.Ldstr, cmdName)); - worker.Append(worker.Create(OpCodes.Ldnull)); - worker.Append(worker.Create(OpCodes.Ldftn, func)); + worker.Emit(OpCodes.Ldtoken, netBehaviourSubclass); + worker.Emit(OpCodes.Call, weaverTypes.getTypeFromHandleReference); + worker.Emit(OpCodes.Ldstr, cmdName); + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ldftn, func); - worker.Append(worker.Create(OpCodes.Newobj, WeaverTypes.CmdDelegateConstructor)); + worker.Emit(OpCodes.Newobj, weaverTypes.RemoteCallDelegateConstructor); - worker.Append(worker.Create(ignoreAuthority ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0)); + // requiresAuthority ? 1 : 0 + worker.Emit(requiresAuthority ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); - worker.Append(worker.Create(OpCodes.Call, registerMethod)); + worker.Emit(OpCodes.Call, registerMethod); } - void GenerateSerialization() + void GenerateSerialization(ref bool WeavingFailed) { - Weaver.DLog(netBehaviourSubclass, " GenerateSerialization"); - const string SerializeMethodName = "SerializeSyncVars"; if (netBehaviourSubclass.GetMethod(SerializeMethodName) != null) return; @@ -378,356 +417,264 @@ void GenerateSerialization() MethodDefinition serialize = new MethodDefinition(SerializeMethodName, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, - WeaverTypes.boolType); + weaverTypes.Import(typeof(void))); - serialize.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkWriterType))); - serialize.Parameters.Add(new ParameterDefinition("forceAll", ParameterAttributes.None, WeaverTypes.boolType)); + serialize.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, weaverTypes.Import())); + serialize.Parameters.Add(new ParameterDefinition("forceAll", ParameterAttributes.None, weaverTypes.Import())); ILProcessor worker = serialize.Body.GetILProcessor(); serialize.Body.InitLocals = true; - // loc_0, this local variable is to determine if any variable was dirty - VariableDefinition dirtyLocal = new VariableDefinition(WeaverTypes.boolType); - serialize.Body.Variables.Add(dirtyLocal); - - MethodReference baseSerialize = Resolvers.TryResolveMethodInParents(netBehaviourSubclass.BaseType, Weaver.CurrentAssembly, SerializeMethodName); + // base.SerializeSyncVars(writer, forceAll); + MethodReference baseSerialize = Resolvers.TryResolveMethodInParents(netBehaviourSubclass.BaseType, assembly, SerializeMethodName); if (baseSerialize != null) { // base - worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Emit(OpCodes.Ldarg_0); // writer - worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Emit(OpCodes.Ldarg_1); // forceAll - worker.Append(worker.Create(OpCodes.Ldarg_2)); - worker.Append(worker.Create(OpCodes.Call, baseSerialize)); - // set dirtyLocal to result of base.OnSerialize() - worker.Append(worker.Create(OpCodes.Stloc_0)); + worker.Emit(OpCodes.Ldarg_2); + worker.Emit(OpCodes.Call, baseSerialize); } - // Generates: if (forceAll); + // Generates: + // if (forceAll) + // { + // writer.WriteInt(health); + // ... + // } Instruction initialStateLabel = worker.Create(OpCodes.Nop); // forceAll - worker.Append(worker.Create(OpCodes.Ldarg_2)); - worker.Append(worker.Create(OpCodes.Brfalse, initialStateLabel)); + worker.Emit(OpCodes.Ldarg_2); // load 'forceAll' flag + worker.Emit(OpCodes.Brfalse, initialStateLabel); // start the 'if forceAll' branch - foreach (FieldDefinition syncVar in syncVars) + // generates write.Write(syncVar) for each SyncVar in forceAll case + foreach (FieldDefinition syncVarDef in syncVars) { + FieldReference syncVar = syncVarDef; + if (netBehaviourSubclass.HasGenericParameters) + { + syncVar = syncVarDef.MakeHostInstanceGeneric(); + } // Generates a writer call for each sync variable // writer - worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Emit(OpCodes.Ldarg_1); // this - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, syncVar)); - MethodReference writeFunc = Writers.GetWriteFunc(syncVar.FieldType); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, syncVar); + MethodReference writeFunc; + // For NBs we always need to use the default NetworkBehaviour write func + // since the reader counter part uses that exact layout which is not easy to change + // without introducing more edge cases + // effectively this disallows custom NB-type writers/readers on SyncVars + // see: https://github.com/MirrorNetworking/Mirror/issues/2680 + if (syncVar.FieldType.IsDerivedFrom()) + { + writeFunc = writers.GetWriteFunc(weaverTypes.Import(), ref WeavingFailed); + } + else + { + writeFunc = writers.GetWriteFunc(syncVar.FieldType, ref WeavingFailed); + } + if (writeFunc != null) { - worker.Append(worker.Create(OpCodes.Call, writeFunc)); + worker.Emit(OpCodes.Call, writeFunc); } else { - Weaver.Error($"{syncVar.Name} has unsupported type. Use a supported Mirror type instead", syncVar); + Log.Error($"{syncVar.Name} has unsupported type. Use a supported Mirror type instead", syncVar); + WeavingFailed = true; return; } } - // always return true if forceAll + // if (forceAll) then always return at the end of the 'if' case + worker.Emit(OpCodes.Ret); - // Generates: return true - worker.Append(worker.Create(OpCodes.Ldc_I4_1)); - worker.Append(worker.Create(OpCodes.Ret)); - - // Generates: end if (forceAll); + // end the 'if' case for "if (forceAll)" worker.Append(initialStateLabel); + //////////////////////////////////////////////////////////////////// + // write dirty bits before the data fields // Generates: writer.WritePackedUInt64 (base.get_syncVarDirtyBits ()); // writer - worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Emit(OpCodes.Ldarg_1); // base - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.NetworkBehaviourDirtyBitsReference)); - MethodReference writeUint64Func = Writers.GetWriteFunc(WeaverTypes.uint64Type); - worker.Append(worker.Create(OpCodes.Call, writeUint64Func)); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, weaverTypes.NetworkBehaviourDirtyBitsReference); + MethodReference writeUint64Func = writers.GetWriteFunc(weaverTypes.Import(), ref WeavingFailed); + worker.Emit(OpCodes.Call, writeUint64Func); // generate a writer call for any dirty variable in this class // start at number of syncvars in parent - int dirtyBit = Weaver.GetSyncVarStart(netBehaviourSubclass.BaseType.FullName); - foreach (FieldDefinition syncVar in syncVars) + int dirtyBit = syncVarAccessLists.GetSyncVarStart(netBehaviourSubclass.BaseType.FullName); + foreach (FieldDefinition syncVarDef in syncVars) { + FieldReference syncVar = syncVarDef; + if (netBehaviourSubclass.HasGenericParameters) + { + syncVar = syncVarDef.MakeHostInstanceGeneric(); + } Instruction varLabel = worker.Create(OpCodes.Nop); // Generates: if ((base.get_syncVarDirtyBits() & 1uL) != 0uL) // base - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.NetworkBehaviourDirtyBitsReference)); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, weaverTypes.NetworkBehaviourDirtyBitsReference); // 8 bytes = long - worker.Append(worker.Create(OpCodes.Ldc_I8, 1L << dirtyBit)); - worker.Append(worker.Create(OpCodes.And)); - worker.Append(worker.Create(OpCodes.Brfalse, varLabel)); + worker.Emit(OpCodes.Ldc_I8, 1L << dirtyBit); + worker.Emit(OpCodes.And); + worker.Emit(OpCodes.Brfalse, varLabel); // Generates a call to the writer for that field // writer - worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Emit(OpCodes.Ldarg_1); // base - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, syncVar)); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, syncVar); + + MethodReference writeFunc; + // For NBs we always need to use the default NetworkBehaviour write func + // since the reader counter part uses that exact layout which is not easy to change + // without introducing more edge cases + // effectively this disallows custom NB-type writers/readers on SyncVars + // see: https://github.com/MirrorNetworking/Mirror/issues/2680 + if (syncVar.FieldType.IsDerivedFrom()) + { + writeFunc = writers.GetWriteFunc(weaverTypes.Import(), ref WeavingFailed); + } + else + { + writeFunc = writers.GetWriteFunc(syncVar.FieldType, ref WeavingFailed); + } - MethodReference writeFunc = Writers.GetWriteFunc(syncVar.FieldType); if (writeFunc != null) { - worker.Append(worker.Create(OpCodes.Call, writeFunc)); + worker.Emit(OpCodes.Call, writeFunc); } else { - Weaver.Error($"{syncVar.Name} has unsupported type. Use a supported Mirror type instead", syncVar); + Log.Error($"{syncVar.Name} has unsupported type. Use a supported Mirror type instead", syncVar); + WeavingFailed = true; return; } - // something was dirty - worker.Append(worker.Create(OpCodes.Ldc_I4_1)); - // set dirtyLocal to true - worker.Append(worker.Create(OpCodes.Stloc_0)); - worker.Append(varLabel); dirtyBit += 1; } - if (Weaver.GenerateLogErrors) - { - worker.Append(worker.Create(OpCodes.Ldstr, "Injected Serialize " + netBehaviourSubclass.Name)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.logErrorReference)); - } + // add a log message if needed for debugging + //worker.Emit(OpCodes.Ldstr, $"Injected Serialize {netBehaviourSubclass.Name}"); + //worker.Emit(OpCodes.Call, WeaverTypes.logErrorReference); - // generate: return dirtyLocal - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Ret)); + // generate: return + worker.Emit(OpCodes.Ret); netBehaviourSubclass.Methods.Add(serialize); } - void DeserializeField(FieldDefinition syncVar, ILProcessor worker, MethodDefinition deserialize) + void DeserializeField(FieldDefinition syncVar, ILProcessor worker, ref bool WeavingFailed) { - // check for Hook function - MethodDefinition hookMethod = SyncVarProcessor.GetHookMethod(netBehaviourSubclass, syncVar); + // put 'this.' onto stack for 'this.syncvar' below + worker.Append(worker.Create(OpCodes.Ldarg_0)); - if (IsNetworkIdentityField(syncVar)) + // push 'ref T this.field' + worker.Emit(OpCodes.Ldarg_0); + // if the netbehaviour class is generic, we need to make the field reference generic as well for correct IL + if (netBehaviourSubclass.HasGenericParameters) { - DeserializeNetworkIdentityField(syncVar, worker, deserialize, hookMethod); + worker.Emit(OpCodes.Ldflda, syncVar.MakeHostInstanceGeneric()); } else { - DeserializeNormalField(syncVar, worker, deserialize, hookMethod); + worker.Emit(OpCodes.Ldflda, syncVar); } - } - - /// - /// Is the field a NetworkIdentity or GameObject - /// - /// - /// - static bool IsNetworkIdentityField(FieldDefinition syncVar) - { - return syncVar.FieldType.FullName == WeaverTypes.gameObjectType.FullName || - syncVar.FieldType.FullName == WeaverTypes.NetworkIdentityType.FullName; - } - - /// - /// [SyncVar] GameObject/NetworkIdentity? - /// - /// - /// - /// - /// - /// - void DeserializeNetworkIdentityField(FieldDefinition syncVar, ILProcessor worker, MethodDefinition deserialize, MethodDefinition hookMethod) - { - /* - Generates code like: - uint oldNetId = ___qNetId; - // returns GetSyncVarGameObject(___qNetId) - GameObject oldSyncVar = syncvar.getter; - ___qNetId = reader.ReadPackedUInt32(); - if (!SyncVarEqual(oldNetId, ref ___goNetId)) - { - // getter returns GetSyncVarGameObject(___qNetId) - OnSetQ(oldSyncVar, syncvar.getter); - } - */ - - // GameObject/NetworkIdentity SyncVar: - // OnSerialize sends writer.Write(go); - // OnDeserialize reads to __netId manually so we can use - // lookups in the getter (so it still works if objects - // move in and out of range repeatedly) - FieldDefinition netIdField = syncVarNetIds[syncVar]; - - // uint oldNetId = ___qNetId; - VariableDefinition oldNetId = new VariableDefinition(WeaverTypes.uint32Type); - deserialize.Body.Variables.Add(oldNetId); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, netIdField)); - worker.Append(worker.Create(OpCodes.Stloc, oldNetId)); - // GameObject/NetworkIdentity oldSyncVar = syncvar.getter; - VariableDefinition oldSyncVar = new VariableDefinition(syncVar.FieldType); - deserialize.Body.Variables.Add(oldSyncVar); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, syncVar)); - worker.Append(worker.Create(OpCodes.Stloc, oldSyncVar)); - - // read id and store in netId field BEFORE calling the hook - // -> this makes way more sense. by definition, the hook is - // supposed to be called after it was changed. not before. - // -> setting it BEFORE calling the hook fixes the following bug: - // https://github.com/vis2k/Mirror/issues/1151 in host mode - // where the value during the Hook call would call Cmds on - // the host server, and they would all happen and compare - // values BEFORE the hook even returned and hence BEFORE the - // actual value was even set. - // put 'this.' onto stack for 'this.netId' below - worker.Append(worker.Create(OpCodes.Ldarg_0)); - // reader. for 'reader.Read()' below - worker.Append(worker.Create(OpCodes.Ldarg_1)); - // Read() - worker.Append(worker.Create(OpCodes.Call, Readers.GetReadFunc(WeaverTypes.uint32Type))); - // netId - worker.Append(worker.Create(OpCodes.Stfld, netIdField)); - - if (hookMethod != null) + // If a hook exists, then we need to load the hook delegate on the stack + // The hook delegate is created once in the constructor and stored in an instance field + // We load the delegate from this instance field to avoid instantiating a new delegate instance every time (drastically reduces allocations) + if(syncVarHookDelegates.TryGetValue(syncVar, out (FieldDefinition hookDelegateField, MethodDefinition) value)) { - // call Hook(this.GetSyncVarGameObject/NetworkIdentity(reader.ReadPackedUInt32())) - // because we send/receive the netID, not the GameObject/NetworkIdentity - // but only if SyncVar changed. otherwise a client would - // get hook calls for all initial values, even if they - // didn't change from the default values on the client. - // see also: https://github.com/vis2k/Mirror/issues/1278 - - // IMPORTANT: for GameObjects/NetworkIdentities we usually - // use SyncVarGameObjectEqual to compare equality. - // in this case however, we can just use - // SyncVarEqual with the two uint netIds. - // => this is easier weaver code because we don't - // have to get the GameObject/NetworkIdentity - // from the uint netId - // => this is faster because we void one - // GetComponent call for GameObjects to get - // their NetworkIdentity when comparing. - - // Generates: if (!SyncVarEqual); - Instruction syncVarEqualLabel = worker.Create(OpCodes.Nop); - - // 'this.' for 'this.SyncVarEqual' - worker.Append(worker.Create(OpCodes.Ldarg_0)); - // 'oldNetId' - worker.Append(worker.Create(OpCodes.Ldloc, oldNetId)); - // 'ref this.__netId' - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldflda, netIdField)); - // call the function - GenericInstanceMethod syncVarEqualGm = new GenericInstanceMethod(WeaverTypes.syncVarEqualReference); - syncVarEqualGm.GenericArguments.Add(netIdField.FieldType); - worker.Append(worker.Create(OpCodes.Call, syncVarEqualGm)); - worker.Append(worker.Create(OpCodes.Brtrue, syncVarEqualLabel)); - - // call the hook - // Generates: OnValueChanged(oldValue, this.syncVar); - SyncVarProcessor.WriteCallHookMethodUsingField(worker, hookMethod, oldSyncVar, syncVar); - - // Generates: end if (!SyncVarEqual); - worker.Append(syncVarEqualLabel); + // A hook exists. Push this.hookDelegateField onto the stack + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, value.hookDelegateField); } - } - - /// - /// [SyncVar] int/float/struct/etc.? - /// - /// - /// - /// - /// - /// - void DeserializeNormalField(FieldDefinition syncVar, ILProcessor serWorker, MethodDefinition deserialize, MethodDefinition hookMethod) - { - /* - Generates code like: - // for hook - int oldValue = a; - Networka = reader.ReadPackedInt32(); - if (!SyncVarEqual(oldValue, ref a)) - { - OnSetA(oldValue, Networka); - } - */ - - MethodReference readFunc = Readers.GetReadFunc(syncVar.FieldType); - if (readFunc == null) + else { - Weaver.Error($"{syncVar.Name} has unsupported type. Use a supported Mirror type instead", syncVar); - return; + // No hook exists. Push 'null' as hook + worker.Emit(OpCodes.Ldnull); } - // T oldValue = value; - VariableDefinition oldValue = new VariableDefinition(syncVar.FieldType); - deserialize.Body.Variables.Add(oldValue); - serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); - serWorker.Append(serWorker.Create(OpCodes.Ldfld, syncVar)); - serWorker.Append(serWorker.Create(OpCodes.Stloc, oldValue)); - - // read value and store in syncvar BEFORE calling the hook - // -> this makes way more sense. by definition, the hook is - // supposed to be called after it was changed. not before. - // -> setting it BEFORE calling the hook fixes the following bug: - // https://github.com/vis2k/Mirror/issues/1151 in host mode - // where the value during the Hook call would call Cmds on - // the host server, and they would all happen and compare - // values BEFORE the hook even returned and hence BEFORE the - // actual value was even set. - // put 'this.' onto stack for 'this.syncvar' below - serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); - // reader. for 'reader.Read()' below - serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); - // reader.Read() - serWorker.Append(serWorker.Create(OpCodes.Call, readFunc)); - // syncvar - serWorker.Append(serWorker.Create(OpCodes.Stfld, syncVar)); - - if (hookMethod != null) + // call GeneratedSyncVarDeserialize. + // special cases for GameObject/NetworkIdentity/NetworkBehaviour + // passing netId too for persistence. + if (syncVar.FieldType.Is()) { - // call hook - // but only if SyncVar changed. otherwise a client would - // get hook calls for all initial values, even if they - // didn't change from the default values on the client. - // see also: https://github.com/vis2k/Mirror/issues/1278 + // reader + worker.Emit(OpCodes.Ldarg_1); - // Generates: if (!SyncVarEqual); - Instruction syncVarEqualLabel = serWorker.Create(OpCodes.Nop); + // GameObject setter needs one more parameter: netId field ref + FieldDefinition netIdField = syncVarNetIds[syncVar]; + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdField); + worker.Emit(OpCodes.Call, weaverTypes.generatedSyncVarDeserialize_GameObject); + } + else if (syncVar.FieldType.Is()) + { + // reader + worker.Emit(OpCodes.Ldarg_1); - // 'this.' for 'this.SyncVarEqual' - serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); - // 'oldValue' - serWorker.Append(serWorker.Create(OpCodes.Ldloc, oldValue)); - // 'ref this.syncVar' - serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); - serWorker.Append(serWorker.Create(OpCodes.Ldflda, syncVar)); - // call the function - GenericInstanceMethod syncVarEqualGm = new GenericInstanceMethod(WeaverTypes.syncVarEqualReference); - syncVarEqualGm.GenericArguments.Add(syncVar.FieldType); - serWorker.Append(serWorker.Create(OpCodes.Call, syncVarEqualGm)); - serWorker.Append(serWorker.Create(OpCodes.Brtrue, syncVarEqualLabel)); - - // call the hook - // Generates: OnValueChanged(oldValue, this.syncVar); - SyncVarProcessor.WriteCallHookMethodUsingField(serWorker, hookMethod, oldValue, syncVar); - - // Generates: end if (!SyncVarEqual); - serWorker.Append(syncVarEqualLabel); + // NetworkIdentity deserialize needs one more parameter: netId field ref + FieldDefinition netIdField = syncVarNetIds[syncVar]; + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdField); + worker.Emit(OpCodes.Call, weaverTypes.generatedSyncVarDeserialize_NetworkIdentity); + } + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + else if (syncVar.FieldType.IsDerivedFrom() || syncVar.FieldType.Is()) + { + // reader + worker.Emit(OpCodes.Ldarg_1); + + // NetworkIdentity deserialize needs one more parameter: netId field ref + // (actually its a NetworkBehaviourSyncVar type) + FieldDefinition netIdField = syncVarNetIds[syncVar]; + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdField); + // make generic version of GeneratedSyncVarSetter_NetworkBehaviour + MethodReference getFunc = weaverTypes.generatedSyncVarDeserialize_NetworkBehaviour_T.MakeGeneric(assembly.MainModule, syncVar.FieldType); + worker.Emit(OpCodes.Call, getFunc); + } + else + { + // T value = reader.ReadT(); + // this is still in IL because otherwise weaver generated + // readers/writers don't seem to work in tests. + // besides, this also avoids reader.Read overhead. + MethodReference readFunc = readers.GetReadFunc(syncVar.FieldType, ref WeavingFailed); + if (readFunc == null) + { + Log.Error($"{syncVar.Name} has unsupported type. Use a supported Mirror type instead", syncVar); + WeavingFailed = true; + return; + } + // reader. for 'reader.Read()' below + worker.Emit(OpCodes.Ldarg_1); + // reader.Read() + worker.Emit(OpCodes.Call, readFunc); + + // make generic version of GeneratedSyncVarDeserialize + MethodReference generic = weaverTypes.generatedSyncVarDeserialize.MakeGeneric(assembly.MainModule, syncVar.FieldType); + worker.Emit(OpCodes.Call, generic); } } - void GenerateDeSerialization() + void GenerateDeSerialization(ref bool WeavingFailed) { - Weaver.DLog(netBehaviourSubclass, " GenerateDeSerialization"); - const string DeserializeMethodName = "DeserializeSyncVars"; if (netBehaviourSubclass.GetMethod(DeserializeMethodName) != null) return; @@ -740,17 +687,17 @@ void GenerateDeSerialization() MethodDefinition serialize = new MethodDefinition(DeserializeMethodName, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, - WeaverTypes.voidType); + weaverTypes.Import(typeof(void))); - serialize.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkReaderType))); - serialize.Parameters.Add(new ParameterDefinition("initialState", ParameterAttributes.None, WeaverTypes.boolType)); + serialize.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, weaverTypes.Import())); + serialize.Parameters.Add(new ParameterDefinition("initialState", ParameterAttributes.None, weaverTypes.Import())); ILProcessor serWorker = serialize.Body.GetILProcessor(); // setup local for dirty bits serialize.Body.InitLocals = true; - VariableDefinition dirtyBitsLocal = new VariableDefinition(WeaverTypes.int64Type); + VariableDefinition dirtyBitsLocal = new VariableDefinition(weaverTypes.Import()); serialize.Body.Variables.Add(dirtyBitsLocal); - MethodReference baseDeserialize = Resolvers.TryResolveMethodInParents(netBehaviourSubclass.BaseType, Weaver.CurrentAssembly, DeserializeMethodName); + MethodReference baseDeserialize = Resolvers.TryResolveMethodInParents(netBehaviourSubclass.BaseType, assembly, DeserializeMethodName); if (baseDeserialize != null) { // base @@ -770,7 +717,7 @@ void GenerateDeSerialization() foreach (FieldDefinition syncVar in syncVars) { - DeserializeField(syncVar, serWorker, serialize); + DeserializeField(syncVar, serWorker, ref WeavingFailed); } serWorker.Append(serWorker.Create(OpCodes.Ret)); @@ -780,12 +727,12 @@ void GenerateDeSerialization() // get dirty bits serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); - serWorker.Append(serWorker.Create(OpCodes.Call, Readers.GetReadFunc(WeaverTypes.uint64Type))); + serWorker.Append(serWorker.Create(OpCodes.Call, readers.GetReadFunc(weaverTypes.Import(), ref WeavingFailed))); serWorker.Append(serWorker.Create(OpCodes.Stloc_0)); // conditionally read each syncvar // start at number of syncvars in parent - int dirtyBit = Weaver.GetSyncVarStart(netBehaviourSubclass.BaseType.FullName); + int dirtyBit = syncVarAccessLists.GetSyncVarStart(netBehaviourSubclass.BaseType.FullName); foreach (FieldDefinition syncVar in syncVars) { Instruction varLabel = serWorker.Create(OpCodes.Nop); @@ -796,23 +743,21 @@ void GenerateDeSerialization() serWorker.Append(serWorker.Create(OpCodes.And)); serWorker.Append(serWorker.Create(OpCodes.Brfalse, varLabel)); - DeserializeField(syncVar, serWorker, serialize); + DeserializeField(syncVar, serWorker, ref WeavingFailed); serWorker.Append(varLabel); dirtyBit += 1; } - if (Weaver.GenerateLogErrors) - { - serWorker.Append(serWorker.Create(OpCodes.Ldstr, "Injected Deserialize " + netBehaviourSubclass.Name)); - serWorker.Append(serWorker.Create(OpCodes.Call, WeaverTypes.logErrorReference)); - } + // add a log message if needed for debugging + //serWorker.Append(serWorker.Create(OpCodes.Ldstr, $"Injected Deserialize {netBehaviourSubclass.Name}")); + //serWorker.Append(serWorker.Create(OpCodes.Call, WeaverTypes.logErrorReference)); serWorker.Append(serWorker.Create(OpCodes.Ret)); netBehaviourSubclass.Methods.Add(serialize); } - public static bool ReadArguments(MethodDefinition method, ILProcessor worker, RemoteCallType callType) + public static bool ReadArguments(MethodDefinition method, Readers readers, Logger Log, ILProcessor worker, RemoteCallType callType, ref bool WeavingFailed) { // read each argument // example result @@ -820,8 +765,8 @@ public static bool ReadArguments(MethodDefinition method, ILProcessor worker, Re CallCmdDoSomething(reader.ReadPackedInt32(), reader.ReadNetworkIdentity()); */ - bool skipFirst = (callType == RemoteCallType.TargetRpc - && TargetRpcProcessor.HasNetworkConnectionParameter(method)); + bool skipFirst = callType == RemoteCallType.TargetRpc + && TargetRpcProcessor.HasNetworkConnectionParameter(method); // arg of calling function, arg 0 is "this" so start counting at 1 int argNum = 1; @@ -842,79 +787,84 @@ public static bool ReadArguments(MethodDefinition method, ILProcessor worker, Re } - MethodReference readFunc = Readers.GetReadFunc(param.ParameterType); + MethodReference readFunc = readers.GetReadFunc(param.ParameterType, ref WeavingFailed); if (readFunc == null) { - Weaver.Error($"{method.Name} has invalid parameter {param}. Unsupported type {param.ParameterType}, use a supported Mirror type instead", method); + Log.Error($"{method.Name} has invalid parameter {param}. Unsupported type {param.ParameterType}, use a supported Mirror type instead", method); + WeavingFailed = true; return false; } - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Call, readFunc)); + worker.Emit(OpCodes.Ldarg_1); + worker.Emit(OpCodes.Call, readFunc); // conversion.. is this needed? - if (param.ParameterType.FullName == WeaverTypes.singleType.FullName) + if (param.ParameterType.Is()) { - worker.Append(worker.Create(OpCodes.Conv_R4)); + worker.Emit(OpCodes.Conv_R4); } - else if (param.ParameterType.FullName == WeaverTypes.doubleType.FullName) + else if (param.ParameterType.Is()) { - worker.Append(worker.Create(OpCodes.Conv_R8)); + worker.Emit(OpCodes.Conv_R8); } } return true; } - public static void AddInvokeParameters(ICollection collection) + public static void AddInvokeParameters(WeaverTypes weaverTypes, ICollection collection) { - collection.Add(new ParameterDefinition("obj", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkBehaviourType))); - collection.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkReaderType))); + collection.Add(new ParameterDefinition("obj", ParameterAttributes.None, weaverTypes.Import())); + collection.Add(new ParameterDefinition("reader", ParameterAttributes.None, weaverTypes.Import())); // senderConnection is only used for commands but NetworkBehaviour.CmdDelegate is used for all remote calls - collection.Add(new ParameterDefinition("senderConnection", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkConnectionType))); + collection.Add(new ParameterDefinition("senderConnection", ParameterAttributes.None, weaverTypes.Import())); } // check if a Command/TargetRpc/Rpc function & parameters are valid for weaving - public static bool ValidateRemoteCallAndParameters(MethodDefinition method, RemoteCallType callType) + public bool ValidateRemoteCallAndParameters(MethodDefinition method, RemoteCallType callType, ref bool WeavingFailed) { if (method.IsStatic) { - Weaver.Error($"{method.Name} must not be static", method); + Log.Error($"{method.Name} must not be static", method); + WeavingFailed = true; return false; } - return ValidateFunction(method) && - ValidateParameters(method, callType); + return ValidateFunction(method, ref WeavingFailed) && + ValidateParameters(method, callType, ref WeavingFailed); } // check if a Command/TargetRpc/Rpc function is valid for weaving - static bool ValidateFunction(MethodReference md) + bool ValidateFunction(MethodReference md, ref bool WeavingFailed) { - if (md.ReturnType.FullName == WeaverTypes.IEnumeratorType.FullName) + if (md.ReturnType.Is()) { - Weaver.Error($"{md.Name} cannot be a coroutine", md); + Log.Error($"{md.Name} cannot be a coroutine", md); + WeavingFailed = true; return false; } - if (md.ReturnType.FullName != WeaverTypes.voidType.FullName) + if (!md.ReturnType.Is(typeof(void))) { - Weaver.Error($"{md.Name} cannot return a value. Make it void instead", md); + Log.Error($"{md.Name} cannot return a value. Make it void instead", md); + WeavingFailed = true; return false; } if (md.HasGenericParameters) { - Weaver.Error($"{md.Name} cannot have generic parameters", md); + Log.Error($"{md.Name} cannot have generic parameters", md); + WeavingFailed = true; return false; } return true; } // check if all Command/TargetRpc/Rpc function's parameters are valid for weaving - static bool ValidateParameters(MethodReference method, RemoteCallType callType) + bool ValidateParameters(MethodReference method, RemoteCallType callType, ref bool WeavingFailed) { for (int i = 0; i < method.Parameters.Count; ++i) { ParameterDefinition param = method.Parameters[i]; - if (!ValidateParameter(method, param, callType, i == 0)) + if (!ValidateParameter(method, param, callType, i == 0, ref WeavingFailed)) { return false; } @@ -923,36 +873,46 @@ static bool ValidateParameters(MethodReference method, RemoteCallType callType) } // validate parameters for a remote function call like Rpc/Cmd - static bool ValidateParameter(MethodReference method, ParameterDefinition param, RemoteCallType callType, bool firstParam) + bool ValidateParameter(MethodReference method, ParameterDefinition param, RemoteCallType callType, bool firstParam, ref bool WeavingFailed) { - bool isNetworkConnection = param.ParameterType.FullName == WeaverTypes.NetworkConnectionType.FullName; + // need to check this before any type lookups since those will fail since generic types don't resolve + if (param.ParameterType.IsGenericParameter) + { + Log.Error($"{method.Name} cannot have generic parameters", method); + WeavingFailed = true; + return false; + } + + bool isNetworkConnection = param.ParameterType.Is(); bool isSenderConnection = IsSenderConnection(param, callType); if (param.IsOut) { - Weaver.Error($"{method.Name} cannot have out parameters", method); + Log.Error($"{method.Name} cannot have out parameters", method); + WeavingFailed = true; return false; } - // if not SenderConnection And not TargetRpc NetworkConnection first param if (!isSenderConnection && isNetworkConnection && !(callType == RemoteCallType.TargetRpc && firstParam)) { if (callType == RemoteCallType.Command) { - Weaver.Error($"{method.Name} has invalid parameter {param}, Cannot pass NetworkConnections. Instead use 'NetworkConnectionToClient conn = null' to get the sender's connection on the server", method); + Log.Error($"{method.Name} has invalid parameter {param}, Cannot pass NetworkConnections. Instead use 'NetworkConnectionToClient conn = null' to get the sender's connection on the server", method); } else { - Weaver.Error($"{method.Name} has invalid parameter {param}. Cannot pass NetworkConnections", method); + Log.Error($"{method.Name} has invalid parameter {param}. Cannot pass NetworkConnections", method); } + WeavingFailed = true; return false; } // sender connection can be optional if (param.IsOptional && !isSenderConnection) { - Weaver.Error($"{method.Name} cannot have optional parameters", method); + Log.Error($"{method.Name} cannot have optional parameters", method); + WeavingFailed = true; return false; } @@ -968,13 +928,11 @@ public static bool IsSenderConnection(ParameterDefinition param, RemoteCallType TypeReference type = param.ParameterType; - const string ConnectionToClient = "Mirror.NetworkConnectionToClient"; - bool isConnectionToClient = type.FullName == ConnectionToClient || type.Resolve().IsDerivedFrom(ConnectionToClient); - - return isConnectionToClient; + return type.Is() + || type.Resolve().IsDerivedFrom(); } - void ProcessMethods() + void ProcessMethods(ref bool WeavingFailed) { HashSet names = new HashSet(); @@ -985,123 +943,109 @@ void ProcessMethods() { foreach (CustomAttribute ca in md.CustomAttributes) { - if (ca.AttributeType.FullName == WeaverTypes.CommandType.FullName) + if (ca.AttributeType.Is()) { - ProcessCommand(names, md, ca); + ProcessCommand(names, md, ca, ref WeavingFailed); break; } - if (ca.AttributeType.FullName == WeaverTypes.TargetRpcType.FullName) + if (ca.AttributeType.Is()) { - ProcessTargetRpc(names, md, ca); + ProcessTargetRpc(names, md, ca, ref WeavingFailed); break; } - if (ca.AttributeType.FullName == WeaverTypes.ClientRpcType.FullName) + if (ca.AttributeType.Is()) { - ProcessClientRpc(names, md, ca); + ProcessClientRpc(names, md, ca, ref WeavingFailed); break; } } } } - void ProcessClientRpc(HashSet names, MethodDefinition md, CustomAttribute clientRpcAttr) + void ProcessClientRpc(HashSet names, MethodDefinition md, CustomAttribute clientRpcAttr, ref bool WeavingFailed) { if (md.IsAbstract) { - Weaver.Error("Abstract ClientRpc are currently not supported, use virtual method instead", md); + Log.Error("Abstract ClientRpc are currently not supported, use virtual method instead", md); + WeavingFailed = true; return; } - if (!ValidateRemoteCallAndParameters(md, RemoteCallType.ClientRpc)) + if (!ValidateRemoteCallAndParameters(md, RemoteCallType.ClientRpc, ref WeavingFailed)) { return; } - if (names.Contains(md.Name)) - { - Weaver.Error($"Duplicate ClientRpc name {md.Name}", md); - return; - } - - bool excludeOwner = clientRpcAttr.GetField("excludeOwner", false); + bool includeOwner = clientRpcAttr.GetField("includeOwner", true); names.Add(md.Name); clientRpcs.Add(new ClientRpcResult { method = md, - excludeOwner = excludeOwner + includeOwner = includeOwner }); - MethodDefinition rpcCallFunc = RpcProcessor.ProcessRpcCall(netBehaviourSubclass, md, clientRpcAttr); + MethodDefinition rpcCallFunc = RpcProcessor.ProcessRpcCall(weaverTypes, writers, Log, netBehaviourSubclass, md, clientRpcAttr, ref WeavingFailed); // need null check here because ProcessRpcCall returns null if it can't write all the args if (rpcCallFunc == null) { return; } - MethodDefinition rpcFunc = RpcProcessor.ProcessRpcInvoke(netBehaviourSubclass, md, rpcCallFunc); + MethodDefinition rpcFunc = RpcProcessor.ProcessRpcInvoke(weaverTypes, writers, readers, Log, netBehaviourSubclass, md, rpcCallFunc, ref WeavingFailed); if (rpcFunc != null) { clientRpcInvocationFuncs.Add(rpcFunc); } } - void ProcessTargetRpc(HashSet names, MethodDefinition md, CustomAttribute targetRpcAttr) + void ProcessTargetRpc(HashSet names, MethodDefinition md, CustomAttribute targetRpcAttr, ref bool WeavingFailed) { if (md.IsAbstract) { - Weaver.Error("Abstract TargetRpc are currently not supported, use virtual method instead", md); + Log.Error("Abstract TargetRpc are currently not supported, use virtual method instead", md); + WeavingFailed = true; return; } - if (!ValidateRemoteCallAndParameters(md, RemoteCallType.TargetRpc)) + if (!ValidateRemoteCallAndParameters(md, RemoteCallType.TargetRpc, ref WeavingFailed)) return; - if (names.Contains(md.Name)) - { - Weaver.Error($"Duplicate Target Rpc name {md.Name}", md); - return; - } names.Add(md.Name); targetRpcs.Add(md); - MethodDefinition rpcCallFunc = TargetRpcProcessor.ProcessTargetRpcCall(netBehaviourSubclass, md, targetRpcAttr); + MethodDefinition rpcCallFunc = TargetRpcProcessor.ProcessTargetRpcCall(weaverTypes, writers, Log, netBehaviourSubclass, md, targetRpcAttr, ref WeavingFailed); - MethodDefinition rpcFunc = TargetRpcProcessor.ProcessTargetRpcInvoke(netBehaviourSubclass, md, rpcCallFunc); + MethodDefinition rpcFunc = TargetRpcProcessor.ProcessTargetRpcInvoke(weaverTypes, readers, Log, netBehaviourSubclass, md, rpcCallFunc, ref WeavingFailed); if (rpcFunc != null) { targetRpcInvocationFuncs.Add(rpcFunc); } } - void ProcessCommand(HashSet names, MethodDefinition md, CustomAttribute commandAttr) + void ProcessCommand(HashSet names, MethodDefinition md, CustomAttribute commandAttr, ref bool WeavingFailed) { if (md.IsAbstract) { - Weaver.Error("Abstract Commands are currently not supported, use virtual method instead", md); + Log.Error("Abstract Commands are currently not supported, use virtual method instead", md); + WeavingFailed = true; return; } - if (!ValidateRemoteCallAndParameters(md, RemoteCallType.Command)) + if (!ValidateRemoteCallAndParameters(md, RemoteCallType.Command, ref WeavingFailed)) return; - if (names.Contains(md.Name)) - { - Weaver.Error($"Duplicate Command name {md.Name}", md); - return; - } - - bool ignoreAuthority = commandAttr.GetField("ignoreAuthority", false); + bool requiresAuthority = commandAttr.GetField("requiresAuthority", true); names.Add(md.Name); commands.Add(new CmdResult { method = md, - ignoreAuthority = ignoreAuthority + requiresAuthority = requiresAuthority }); - MethodDefinition cmdCallFunc = CommandProcessor.ProcessCommandCall(netBehaviourSubclass, md, commandAttr); + MethodDefinition cmdCallFunc = CommandProcessor.ProcessCommandCall(weaverTypes, writers, Log, netBehaviourSubclass, md, commandAttr, ref WeavingFailed); - MethodDefinition cmdFunc = CommandProcessor.ProcessCommandInvoke(netBehaviourSubclass, md, cmdCallFunc); + MethodDefinition cmdFunc = CommandProcessor.ProcessCommandInvoke(weaverTypes, readers, Log, netBehaviourSubclass, md, cmdCallFunc, ref WeavingFailed); if (cmdFunc != null) { commandInvocationFuncs.Add(cmdFunc); diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta index 67c27dc00c..88f818d5e8 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs deleted file mode 100644 index c3c698eb16..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs +++ /dev/null @@ -1,214 +0,0 @@ -using System; -using Mono.CecilX; -using Mono.CecilX.Cil; - -namespace Mirror.Weaver -{ - public static class PropertySiteProcessor - { - public static void Process(ModuleDefinition moduleDef) - { - DateTime startTime = DateTime.Now; - - //Search through the types - foreach (TypeDefinition td in moduleDef.Types) - { - if (td.IsClass) - { - ProcessSiteClass(td); - } - } - - if (Weaver.WeaveLists.generateContainerClass != null) - { - moduleDef.Types.Add(Weaver.WeaveLists.generateContainerClass); - moduleDef.ImportReference(Weaver.WeaveLists.generateContainerClass); - - foreach (MethodDefinition f in Weaver.WeaveLists.generatedReadFunctions) - { - moduleDef.ImportReference(f); - } - - foreach (MethodDefinition f in Weaver.WeaveLists.generatedWriteFunctions) - { - moduleDef.ImportReference(f); - } - } - - Console.WriteLine(" ProcessSitesModule " + moduleDef.Name + " elapsed time:" + (DateTime.Now - startTime)); - } - - static void ProcessSiteClass(TypeDefinition td) - { - //Console.WriteLine(" ProcessSiteClass " + td); - foreach (MethodDefinition md in td.Methods) - { - ProcessSiteMethod(md); - } - - foreach (TypeDefinition nested in td.NestedTypes) - { - ProcessSiteClass(nested); - } - } - - static void ProcessSiteMethod(MethodDefinition md) - { - // process all references to replaced members with properties - //Weaver.DLog(td, " ProcessSiteMethod " + md); - - if (md.Name == ".cctor" || - md.Name == NetworkBehaviourProcessor.ProcessedFunctionName || - md.Name.StartsWith(Weaver.InvokeRpcPrefix)) - return; - - if (md.IsAbstract) - { - return; - } - - if (md.Body != null && md.Body.Instructions != null) - { - for (int iCount = 0; iCount < md.Body.Instructions.Count;) - { - Instruction instr = md.Body.Instructions[iCount]; - iCount += ProcessInstruction(md, instr, iCount); - } - } - } - - // replaces syncvar write access with the NetworkXYZ.get property calls - static void ProcessInstructionSetterField(MethodDefinition md, Instruction i, FieldDefinition opField) - { - // dont replace property call sites in constructors - if (md.Name == ".ctor") - return; - - // does it set a field that we replaced? - if (Weaver.WeaveLists.replacementSetterProperties.TryGetValue(opField, out MethodDefinition replacement)) - { - //replace with property - //DLog(td, " replacing " + md.Name + ":" + i); - i.OpCode = OpCodes.Call; - i.Operand = replacement; - //DLog(td, " replaced " + md.Name + ":" + i); - } - } - - // replaces syncvar read access with the NetworkXYZ.get property calls - static void ProcessInstructionGetterField(MethodDefinition md, Instruction i, FieldDefinition opField) - { - // dont replace property call sites in constructors - if (md.Name == ".ctor") - return; - - // does it set a field that we replaced? - if (Weaver.WeaveLists.replacementGetterProperties.TryGetValue(opField, out MethodDefinition replacement)) - { - //replace with property - //DLog(td, " replacing " + md.Name + ":" + i); - i.OpCode = OpCodes.Call; - i.Operand = replacement; - //DLog(td, " replaced " + md.Name + ":" + i); - } - } - - static int ProcessInstruction(MethodDefinition md, Instruction instr, int iCount) - { - if ((instr.OpCode == OpCodes.Call || instr.OpCode == OpCodes.Callvirt) - && instr.Operand is MethodReference opMethod) - { - ProcessInstructionMethod(md, instr, opMethod, iCount); - } - - if (instr.OpCode == OpCodes.Stfld && instr.Operand is FieldDefinition opFieldst) - { - // this instruction sets the value of a field. cache the field reference. - ProcessInstructionSetterField(md, instr, opFieldst); - } - - if (instr.OpCode == OpCodes.Ldfld && instr.Operand is FieldDefinition opFieldld) - { - // this instruction gets the value of a field. cache the field reference. - ProcessInstructionGetterField(md, instr, opFieldld); - } - - if (instr.OpCode == OpCodes.Ldflda && instr.Operand is FieldDefinition opFieldlda) - { - // loading a field by reference, watch out for initobj instruction - // see https://github.com/vis2k/Mirror/issues/696 - return ProcessInstructionLoadAddress(md, instr, opFieldlda, iCount); - } - - return 1; - } - - static int ProcessInstructionLoadAddress(MethodDefinition md, Instruction instr, FieldDefinition opField, int iCount) - { - // dont replace property call sites in constructors - if (md.Name == ".ctor") - return 1; - - // does it set a field that we replaced? - if (Weaver.WeaveLists.replacementSetterProperties.TryGetValue(opField, out MethodDefinition replacement)) - { - // we have a replacement for this property - // is the next instruction a initobj? - Instruction nextInstr = md.Body.Instructions[iCount + 1]; - - if (nextInstr.OpCode == OpCodes.Initobj) - { - // we need to replace this code with: - // var tmp = new MyStruct(); - // this.set_Networkxxxx(tmp); - ILProcessor worker = md.Body.GetILProcessor(); - VariableDefinition tmpVariable = new VariableDefinition(opField.FieldType); - md.Body.Variables.Add(tmpVariable); - - worker.InsertBefore(instr, worker.Create(OpCodes.Ldloca, tmpVariable)); - worker.InsertBefore(instr, worker.Create(OpCodes.Initobj, opField.FieldType)); - worker.InsertBefore(instr, worker.Create(OpCodes.Ldloc, tmpVariable)); - worker.InsertBefore(instr, worker.Create(OpCodes.Call, replacement)); - - worker.Remove(instr); - worker.Remove(nextInstr); - return 4; - } - } - - return 1; - } - - static void ProcessInstructionMethod(MethodDefinition md, Instruction instr, MethodReference opMethodRef, int iCount) - { - if (opMethodRef.Name != "Invoke") - return; - - // Events use an "Invoke" method to call the delegate. - // this code replaces the "Invoke" instruction with the generated "Call***" instruction which send the event to the server. - // but the "Invoke" instruction is called on the event field - where the "call" instruction is not. - // so the earlier instruction that loads the event field is replaced with a Noop. - - // go backwards until find a ldfld instruction that matches ANY event - while (iCount > 0) - { - iCount -= 1; - Instruction inst = md.Body.Instructions[iCount]; - if (inst.OpCode == OpCodes.Ldfld) - { - FieldReference opField = inst.Operand as FieldReference; - - // find replaceEvent with matching name - // NOTE: original weaver compared .Name, not just the MethodDefinition, - // that's why we use dict. - if (Weaver.WeaveLists.replaceEvents.TryGetValue(opField.FullName, out MethodDefinition replacement)) - { - instr.Operand = replacement; - inst.OpCode = OpCodes.Nop; - return; - } - } - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs.meta deleted file mode 100644 index e8c2500adc..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d48f1ab125e9940a995603796bccc59e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs index fc8c42b9af..58a19d893e 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs @@ -1,95 +1,232 @@ // finds all readers and writers and register them -using System.IO; +using System.Collections.Generic; +using System.Linq; using Mono.CecilX; -using UnityEditor.Compilation; +using Mono.CecilX.Cil; +using Mono.CecilX.Rocks; +using UnityEngine; namespace Mirror.Weaver { public static class ReaderWriterProcessor { - public static void Process(AssemblyDefinition CurrentAssembly) + public static bool Process(AssemblyDefinition CurrentAssembly, IAssemblyResolver resolver, Logger Log, Writers writers, Readers readers, ref bool WeavingFailed) { - Readers.Init(); - Writers.Init(); + // find NetworkReader/Writer extensions from Mirror.dll first. + // and NetworkMessage custom writer/reader extensions. + // NOTE: do not include this result in our 'modified' return value, + // otherwise Unity crashes when running tests + ProcessMirrorAssemblyClasses(CurrentAssembly, resolver, Log, writers, readers, ref WeavingFailed); - foreach (Assembly unityAsm in CompilationPipeline.GetAssemblies()) + // process dependencies first, this way weaver can process types of other assemblies properly. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2503 + // + // find NetworkReader/Writer extensions in referenced assemblies + // save a copy of the collection enumerator since it appears to be modified at some point during iteration + IEnumerable assemblyReferences = CurrentAssembly.MainModule.AssemblyReferences.ToList(); + foreach (AssemblyNameReference assemblyNameReference in assemblyReferences) { - if (unityAsm.name != CurrentAssembly.Name.Name) + AssemblyDefinition referencedAssembly = resolver.Resolve(assemblyNameReference); + if (referencedAssembly != null) { - try - { - using (DefaultAssemblyResolver asmResolver = new DefaultAssemblyResolver()) - using (AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(unityAsm.outputPath, new ReaderParameters { ReadWrite = false, ReadSymbols = false, AssemblyResolver = asmResolver })) - { - ProcessAssemblyClasses(CurrentAssembly, assembly); - } - } - catch (FileNotFoundException) - { - // During first import, this gets called before some assemblies - // are built, just skip them - } + ProcessAssemblyClasses(CurrentAssembly, referencedAssembly, writers, readers, ref WeavingFailed); } } - ProcessAssemblyClasses(CurrentAssembly, CurrentAssembly); + // find readers/writers in the assembly we are in right now. + return ProcessAssemblyClasses(CurrentAssembly, CurrentAssembly, writers, readers, ref WeavingFailed); } - static void ProcessAssemblyClasses(AssemblyDefinition CurrentAssembly, AssemblyDefinition assembly) + static void ProcessMirrorAssemblyClasses(AssemblyDefinition CurrentAssembly, IAssemblyResolver resolver, Logger Log, Writers writers, Readers readers, ref bool WeavingFailed) { + // find Mirror.dll in assembly's references. + // those are guaranteed to be resolvable and correct. + // after all, it references them :) + AssemblyNameReference mirrorAssemblyReference = CurrentAssembly.MainModule.FindReference(Weaver.MirrorAssemblyName); + if (mirrorAssemblyReference != null) + { + // resolve the assembly to load the AssemblyDefinition. + // we need to search all types in it. + // if we only were to resolve one known type like in WeaverTypes, + // then we wouldn't need it. + AssemblyDefinition mirrorAssembly = resolver.Resolve(mirrorAssemblyReference); + if (mirrorAssembly != null) + { + ProcessAssemblyClasses(CurrentAssembly, mirrorAssembly, writers, readers, ref WeavingFailed); + } + else Log.Error($"Failed to resolve {mirrorAssemblyReference}"); + } + else Log.Error("Failed to find Mirror AssemblyNameReference. Can't register Mirror.dll readers/writers."); + } + + static bool ProcessAssemblyClasses(AssemblyDefinition CurrentAssembly, AssemblyDefinition assembly, Writers writers, Readers readers, ref bool WeavingFailed) + { + bool modified = false; foreach (TypeDefinition klass in assembly.MainModule.Types) { // extension methods only live in static classes // static classes are represented as sealed and abstract if (klass.IsAbstract && klass.IsSealed) { - LoadWriters(CurrentAssembly, klass); - LoadReaders(CurrentAssembly, klass); + // if assembly has any declared writers then it is "modified" + modified |= LoadDeclaredWriters(CurrentAssembly, klass, writers); + modified |= LoadDeclaredReaders(CurrentAssembly, klass, readers); } } + + foreach (TypeDefinition klass in assembly.MainModule.Types) + { + // if assembly has any network message then it is modified + modified |= LoadMessageReadWriter(CurrentAssembly.MainModule, writers, readers, klass, ref WeavingFailed); + } + return modified; + } + + static bool LoadMessageReadWriter(ModuleDefinition module, Writers writers, Readers readers, TypeDefinition klass, ref bool WeavingFailed) + { + bool modified = false; + if (!klass.IsAbstract && !klass.IsInterface && klass.ImplementsInterface()) + { + readers.GetReadFunc(module.ImportReference(klass), ref WeavingFailed); + writers.GetWriteFunc(module.ImportReference(klass), ref WeavingFailed); + modified = true; + } + + foreach (TypeDefinition td in klass.NestedTypes) + { + modified |= LoadMessageReadWriter(module, writers, readers, td, ref WeavingFailed); + } + return modified; } - static void LoadWriters(AssemblyDefinition currentAssembly, TypeDefinition klass) + static bool LoadDeclaredWriters(AssemblyDefinition currentAssembly, TypeDefinition klass, Writers writers) { // register all the writers in this class. Skip the ones with wrong signature + bool modified = false; foreach (MethodDefinition method in klass.Methods) { if (method.Parameters.Count != 2) continue; - if (method.Parameters[0].ParameterType.FullName != "Mirror.NetworkWriter") + if (!method.Parameters[0].ParameterType.Is()) + continue; + + if (!method.ReturnType.Is(typeof(void))) continue; - if (method.ReturnType.FullName != "System.Void") + if (!method.HasCustomAttribute()) continue; - if (method.GetCustomAttribute("System.Runtime.CompilerServices.ExtensionAttribute") == null) + if (method.HasGenericParameters) continue; TypeReference dataType = method.Parameters[1].ParameterType; - Writers.Register(dataType, currentAssembly.MainModule.ImportReference(method)); + writers.Register(dataType, currentAssembly.MainModule.ImportReference(method)); + modified = true; } + return modified; } - static void LoadReaders(AssemblyDefinition currentAssembly, TypeDefinition klass) + static bool LoadDeclaredReaders(AssemblyDefinition currentAssembly, TypeDefinition klass, Readers readers) { // register all the reader in this class. Skip the ones with wrong signature + bool modified = false; foreach (MethodDefinition method in klass.Methods) { if (method.Parameters.Count != 1) continue; - if (method.Parameters[0].ParameterType.FullName != "Mirror.NetworkReader") + if (!method.Parameters[0].ParameterType.Is()) + continue; + + if (method.ReturnType.Is(typeof(void))) continue; - if (method.ReturnType.FullName == "System.Void") + if (!method.HasCustomAttribute()) continue; - if (method.GetCustomAttribute("System.Runtime.CompilerServices.ExtensionAttribute") == null) + if (method.HasGenericParameters) continue; - Readers.Register(method.ReturnType, currentAssembly.MainModule.ImportReference(method)); + readers.Register(method.ReturnType, currentAssembly.MainModule.ImportReference(method)); + modified = true; + } + return modified; + } + + // helper function to add [RuntimeInitializeOnLoad] attribute to method + static void AddRuntimeInitializeOnLoadAttribute(AssemblyDefinition assembly, WeaverTypes weaverTypes, MethodDefinition method) + { + // NOTE: previously we used reflection because according paul, + // 'weaving Mirror.dll caused unity to rebuild all dlls but in wrong + // order, which breaks rewired' + // it's not obvious why importing an attribute via reflection instead + // of cecil would break anything. let's use cecil. + + // to add a CustomAttribute, we need the attribute's constructor. + // in this case, there are two: empty, and RuntimeInitializeOnLoadType. + // we want the last one, with the type parameter. + MethodDefinition ctor = weaverTypes.runtimeInitializeOnLoadMethodAttribute.GetConstructors().Last(); + //MethodDefinition ctor = weaverTypes.runtimeInitializeOnLoadMethodAttribute.GetConstructors().First(); + // using ctor directly throws: ArgumentException: Member 'System.Void UnityEditor.InitializeOnLoadMethodAttribute::.ctor()' is declared in another module and needs to be imported + // we need to import it first. + CustomAttribute attribute = new CustomAttribute(assembly.MainModule.ImportReference(ctor)); + // add the RuntimeInitializeLoadType.BeforeSceneLoad argument to ctor + attribute.ConstructorArguments.Add(new CustomAttributeArgument(weaverTypes.Import(), RuntimeInitializeLoadType.BeforeSceneLoad)); + method.CustomAttributes.Add(attribute); + } + + // helper function to add [InitializeOnLoad] attribute to method + // (only works in Editor assemblies. check IsEditorAssembly first.) + static void AddInitializeOnLoadAttribute(AssemblyDefinition assembly, WeaverTypes weaverTypes, MethodDefinition method) + { + // NOTE: previously we used reflection because according paul, + // 'weaving Mirror.dll caused unity to rebuild all dlls but in wrong + // order, which breaks rewired' + // it's not obvious why importing an attribute via reflection instead + // of cecil would break anything. let's use cecil. + + // to add a CustomAttribute, we need the attribute's constructor. + // in this case, there's only one - and it's an empty constructor. + MethodDefinition ctor = weaverTypes.initializeOnLoadMethodAttribute.GetConstructors().First(); + // using ctor directly throws: ArgumentException: Member 'System.Void UnityEditor.InitializeOnLoadMethodAttribute::.ctor()' is declared in another module and needs to be imported + // we need to import it first. + CustomAttribute attribute = new CustomAttribute(assembly.MainModule.ImportReference(ctor)); + method.CustomAttributes.Add(attribute); + } + + // adds Mirror.GeneratedNetworkCode.InitReadWriters() method that + // registers all generated writers into Mirror.Writer static class. + // -> uses [RuntimeInitializeOnLoad] attribute so it's invoke at runtime + // -> uses [InitializeOnLoad] if UnityEditor is referenced so it works + // in Editor and in tests too + // + // use ILSpy to see the result (it's in the DLL's 'Mirror' namespace) + public static void InitializeReaderAndWriters(AssemblyDefinition currentAssembly, WeaverTypes weaverTypes, Writers writers, Readers readers, TypeDefinition GeneratedCodeClass) + { + MethodDefinition initReadWriters = new MethodDefinition("InitReadWriters", MethodAttributes.Public | + MethodAttributes.Static, + weaverTypes.Import(typeof(void))); + + // add [RuntimeInitializeOnLoad] in any case + AddRuntimeInitializeOnLoadAttribute(currentAssembly, weaverTypes, initReadWriters); + + // add [InitializeOnLoad] if UnityEditor is referenced + if (Helpers.IsEditorAssembly(currentAssembly)) + { + AddInitializeOnLoadAttribute(currentAssembly, weaverTypes, initReadWriters); } + + // fill function body with reader/writer initializers + ILProcessor worker = initReadWriters.Body.GetILProcessor(); + // for debugging: add a log to see if initialized on load + //worker.Emit(OpCodes.Ldstr, $"[InitReadWriters] called!"); + //worker.Emit(OpCodes.Call, Weaver.weaverTypes.logWarningReference); + writers.InitializeWriters(worker); + readers.InitializeReaders(worker); + worker.Emit(OpCodes.Ret); + + GeneratedCodeClass.Methods.Add(initReadWriters); } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta index c14d6faeb1..d3389ca517 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs index 6e783ffede..ca2d7b94ff 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs @@ -3,35 +3,33 @@ namespace Mirror.Weaver { - /// - /// Processes [Rpc] methods in NetworkBehaviour - /// + // Processes [Rpc] methods in NetworkBehaviour public static class RpcProcessor { - public static MethodDefinition ProcessRpcInvoke(TypeDefinition td, MethodDefinition md, MethodDefinition rpcCallFunc) + public static MethodDefinition ProcessRpcInvoke(WeaverTypes weaverTypes, Writers writers, Readers readers, Logger Log, TypeDefinition td, MethodDefinition md, MethodDefinition rpcCallFunc, ref bool WeavingFailed) { - MethodDefinition rpc = new MethodDefinition( - Weaver.InvokeRpcPrefix + md.Name, - MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig, - WeaverTypes.voidType); + string rpcName = Weaver.GenerateMethodName(RemoteCalls.RemoteProcedureCalls.InvokeRpcPrefix, md); + + MethodDefinition rpc = new MethodDefinition(rpcName, MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig, + weaverTypes.Import(typeof(void))); ILProcessor worker = rpc.Body.GetILProcessor(); Instruction label = worker.Create(OpCodes.Nop); - NetworkBehaviourProcessor.WriteClientActiveCheck(worker, md.Name, label, "RPC"); + NetworkBehaviourProcessor.WriteClientActiveCheck(worker, weaverTypes, md.Name, label, "RPC"); // setup for reader - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Castclass, td)); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Castclass, td); - if (!NetworkBehaviourProcessor.ReadArguments(md, worker, RemoteCallType.ClientRpc)) + if (!NetworkBehaviourProcessor.ReadArguments(md, readers, Log, worker, RemoteCallType.ClientRpc, ref WeavingFailed)) return null; // invoke actual command function - worker.Append(worker.Create(OpCodes.Callvirt, rpcCallFunc)); - worker.Append(worker.Create(OpCodes.Ret)); + worker.Emit(OpCodes.Callvirt, rpcCallFunc); + worker.Emit(OpCodes.Ret); - NetworkBehaviourProcessor.AddInvokeParameters(rpc.Parameters); + NetworkBehaviourProcessor.AddInvokeParameters(weaverTypes, rpc.Parameters); td.Methods.Add(rpc); return rpc; } @@ -58,46 +56,47 @@ and replaces the body of the original method with the send message code. This way we do not need to modify the code anywhere else, and this works correctly in dependent assemblies */ - public static MethodDefinition ProcessRpcCall(TypeDefinition td, MethodDefinition md, CustomAttribute clientRpcAttr) + public static MethodDefinition ProcessRpcCall(WeaverTypes weaverTypes, Writers writers, Logger Log, TypeDefinition td, MethodDefinition md, CustomAttribute clientRpcAttr, ref bool WeavingFailed) { - MethodDefinition rpc = MethodProcessor.SubstituteMethod(td, md); + MethodDefinition rpc = MethodProcessor.SubstituteMethod(Log, td, md, ref WeavingFailed); ILProcessor worker = md.Body.GetILProcessor(); - NetworkBehaviourProcessor.WriteSetupLocals(worker); + NetworkBehaviourProcessor.WriteSetupLocals(worker, weaverTypes); - if (Weaver.GenerateLogErrors) - { - worker.Append(worker.Create(OpCodes.Ldstr, "Call ClientRpc function " + md.Name)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.logErrorReference)); - } + // add a log message if needed for debugging + //worker.Emit(OpCodes.Ldstr, $"Call ClientRpc function {md.Name}"); + //worker.Emit(OpCodes.Call, WeaverTypes.logErrorReference); - NetworkBehaviourProcessor.WriteCreateWriter(worker); + NetworkBehaviourProcessor.WriteGetWriter(worker, weaverTypes); // write all the arguments that the user passed to the Rpc call - if (!NetworkBehaviourProcessor.WriteArguments(worker, md, RemoteCallType.ClientRpc)) + if (!NetworkBehaviourProcessor.WriteArguments(worker, writers, Log, md, RemoteCallType.ClientRpc, ref WeavingFailed)) return null; - string rpcName = md.Name; int channel = clientRpcAttr.GetField("channel", 0); - bool excludeOwner = clientRpcAttr.GetField("excludeOwner", false); + bool includeOwner = clientRpcAttr.GetField("includeOwner", true); // invoke SendInternal and return // this - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldtoken, td)); - // invokerClass - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.getTypeFromHandleReference)); - worker.Append(worker.Create(OpCodes.Ldstr, rpcName)); + worker.Emit(OpCodes.Ldarg_0); + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + worker.Emit(OpCodes.Ldstr, md.FullName); + // pass the function hash so we don't have to compute it at runtime + // otherwise each GetStableHash call requires O(N) complexity. + // noticeable for long function names: + // https://github.com/MirrorNetworking/Mirror/issues/3375 + worker.Emit(OpCodes.Ldc_I4, md.FullName.GetStableHashCode()); // writer - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Ldc_I4, channel)); - worker.Append(worker.Create(excludeOwner ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0)); - worker.Append(worker.Create(OpCodes.Callvirt, WeaverTypes.sendRpcInternal)); + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Ldc_I4, channel); + // includeOwner ? 1 : 0 + worker.Emit(includeOwner ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + worker.Emit(OpCodes.Callvirt, weaverTypes.sendRpcInternal); - NetworkBehaviourProcessor.WriteRecycleWriter(worker); + NetworkBehaviourProcessor.WriteReturnWriter(worker, weaverTypes); - worker.Append(worker.Create(OpCodes.Ret)); + worker.Emit(OpCodes.Ret); return rpc; } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta index 22375bacc7..6d933b7384 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs index 548743ebce..a0b77399fd 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs @@ -6,40 +6,41 @@ namespace Mirror.Weaver { static class ServerClientAttributeProcessor { - public static bool Process(TypeDefinition td) + public static bool Process(WeaverTypes weaverTypes, Logger Log, TypeDefinition td, ref bool WeavingFailed) { bool modified = false; foreach (MethodDefinition md in td.Methods) { - modified |= ProcessSiteMethod(td, md); + modified |= ProcessSiteMethod(weaverTypes, Log, md, ref WeavingFailed); } foreach (TypeDefinition nested in td.NestedTypes) { - modified |= Process(nested); + modified |= Process(weaverTypes, Log, nested, ref WeavingFailed); } return modified; } - static bool ProcessSiteMethod(TypeDefinition td, MethodDefinition md) + static bool ProcessSiteMethod(WeaverTypes weaverTypes, Logger Log, MethodDefinition md, ref bool WeavingFailed) { if (md.Name == ".cctor" || md.Name == NetworkBehaviourProcessor.ProcessedFunctionName || - md.Name.StartsWith(Weaver.InvokeRpcPrefix)) + md.Name.StartsWith(RemoteCalls.RemoteProcedureCalls.InvokeRpcPrefix)) return false; if (md.IsAbstract) { if (HasServerClientAttribute(md)) { - Weaver.Error("Server or Client Attributes can't be added to abstract method. Server and Client Attributes are not inherited so they need to be applied to the override methods instead.", md); + Log.Error("Server or Client Attributes can't be added to abstract method. Server and Client Attributes are not inherited so they need to be applied to the override methods instead.", md); + WeavingFailed = true; } return false; } if (md.Body != null && md.Body.Instructions != null) { - return ProcessMethodAttributes(td, md); + return ProcessMethodAttributes(weaverTypes, md); } return false; } @@ -62,65 +63,50 @@ public static bool HasServerClientAttribute(MethodDefinition md) return false; } - public static bool ProcessMethodAttributes(TypeDefinition td, MethodDefinition md) + public static bool ProcessMethodAttributes(WeaverTypes weaverTypes, MethodDefinition md) { - bool modified = false; - foreach (CustomAttribute attr in md.CustomAttributes) - { - switch (attr.Constructor.DeclaringType.ToString()) - { - case "Mirror.ServerAttribute": - InjectServerGuard(md, true); - modified = true; - break; - case "Mirror.ServerCallbackAttribute": - InjectServerGuard(md, false); - modified = true; - break; - case "Mirror.ClientAttribute": - InjectClientGuard(md, true); - modified = true; - break; - case "Mirror.ClientCallbackAttribute": - InjectClientGuard(md, false); - modified = true; - break; - default: - break; - } - } + if (md.HasCustomAttribute()) + InjectServerGuard(weaverTypes, md, true); + else if (md.HasCustomAttribute()) + InjectServerGuard(weaverTypes, md, false); + else if (md.HasCustomAttribute()) + InjectClientGuard(weaverTypes, md, true); + else if (md.HasCustomAttribute()) + InjectClientGuard(weaverTypes, md, false); + else + return false; - return modified; + return true; } - static void InjectServerGuard(MethodDefinition md, bool logWarning) + static void InjectServerGuard(WeaverTypes weaverTypes, MethodDefinition md, bool logWarning) { ILProcessor worker = md.Body.GetILProcessor(); Instruction top = md.Body.Instructions[0]; - worker.InsertBefore(top, worker.Create(OpCodes.Call, WeaverTypes.NetworkServerGetActive)); + worker.InsertBefore(top, worker.Create(OpCodes.Call, weaverTypes.NetworkServerGetActive)); worker.InsertBefore(top, worker.Create(OpCodes.Brtrue, top)); if (logWarning) { worker.InsertBefore(top, worker.Create(OpCodes.Ldstr, $"[Server] function '{md.FullName}' called when server was not active")); - worker.InsertBefore(top, worker.Create(OpCodes.Call, WeaverTypes.logWarningReference)); + worker.InsertBefore(top, worker.Create(OpCodes.Call, weaverTypes.logWarningReference)); } InjectGuardParameters(md, worker, top); InjectGuardReturnValue(md, worker, top); worker.InsertBefore(top, worker.Create(OpCodes.Ret)); } - static void InjectClientGuard(MethodDefinition md, bool logWarning) + static void InjectClientGuard(WeaverTypes weaverTypes, MethodDefinition md, bool logWarning) { ILProcessor worker = md.Body.GetILProcessor(); Instruction top = md.Body.Instructions[0]; - worker.InsertBefore(top, worker.Create(OpCodes.Call, WeaverTypes.NetworkClientGetActive)); + worker.InsertBefore(top, worker.Create(OpCodes.Call, weaverTypes.NetworkClientGetActive)); worker.InsertBefore(top, worker.Create(OpCodes.Brtrue, top)); if (logWarning) { worker.InsertBefore(top, worker.Create(OpCodes.Ldstr, $"[Client] function '{md.FullName}' called when client was not active")); - worker.InsertBefore(top, worker.Create(OpCodes.Call, WeaverTypes.logWarningReference)); + worker.InsertBefore(top, worker.Create(OpCodes.Call, weaverTypes.logWarningReference)); } InjectGuardParameters(md, worker, top); @@ -137,7 +123,16 @@ static void InjectGuardParameters(MethodDefinition md, ILProcessor worker, Instr ParameterDefinition param = md.Parameters[index]; if (param.IsOut) { - TypeReference elementType = param.ParameterType.GetElementType(); + // this causes IL2CPP build issues with generic out parameters: + // https://github.com/MirrorNetworking/Mirror/issues/3482 + // TypeReference elementType = param.ParameterType.GetElementType(); + // + // instead we need to use ElementType not GetElementType() + // GetElementType() will get the element type of the inner elementType + // which will return wrong type for arrays and generic + // credit: JamesFrowen + ByReferenceType byRefType = (ByReferenceType)param.ParameterType; + TypeReference elementType = byRefType.ElementType; md.Body.Variables.Add(new VariableDefinition(elementType)); md.Body.InitLocals = true; @@ -154,7 +149,7 @@ static void InjectGuardParameters(MethodDefinition md, ILProcessor worker, Instr // this is required to early-out from a function with a return value. static void InjectGuardReturnValue(MethodDefinition md, ILProcessor worker, Instruction top) { - if (md.ReturnType.FullName != WeaverTypes.voidType.FullName) + if (!md.ReturnType.Is(typeof(void))) { md.Body.Variables.Add(new VariableDefinition(md.ReturnType)); md.Body.InitLocals = true; diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs.meta index 5a5451d104..907457c10f 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs deleted file mode 100644 index b6f63e1cf3..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Mono.CecilX; - -namespace Mirror.Weaver -{ - /// - /// generates OnSerialize/OnDeserialize for SyncLists - /// - static class SyncDictionaryProcessor - { - /// - /// Generates serialization methods for synclists - /// - /// The synclist class - public static void Process(TypeDefinition td) - { - GenericArgumentResolver resolver = new GenericArgumentResolver(2); - - if (resolver.GetGenericFromBaseClass(td, 0, WeaverTypes.SyncDictionaryType, out TypeReference keyType)) - { - SyncObjectProcessor.GenerateSerialization(td, keyType, WeaverTypes.SyncDictionaryType, "SerializeKey", "DeserializeKey"); - } - else - { - Weaver.Error($"Could not find generic arguments for SyncDictionary in {td.Name}", td); - return; - } - - if (resolver.GetGenericFromBaseClass(td, 1, WeaverTypes.SyncDictionaryType, out TypeReference itemType)) - { - SyncObjectProcessor.GenerateSerialization(td, itemType, WeaverTypes.SyncDictionaryType, "SerializeItem", "DeserializeItem"); - } - else - { - Weaver.Error($"Could not find generic arguments for SyncDictionary in {td.Name}", td); - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs deleted file mode 100644 index cbc84b8b5e..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System.Collections.Generic; -using Mono.CecilX; -using Mono.CecilX.Cil; - -namespace Mirror.Weaver -{ - /// - /// Processes SyncEvents in NetworkBehaviour - /// - public static class SyncEventProcessor - { - public static MethodDefinition ProcessEventInvoke(TypeDefinition td, EventDefinition ed) - { - // find the field that matches the event - FieldDefinition eventField = null; - foreach (FieldDefinition fd in td.Fields) - { - if (fd.FullName == ed.FullName) - { - eventField = fd; - break; - } - } - if (eventField == null) - { - Weaver.Error($"event field not found for {ed.Name}. Did you declare it as an event?", ed); - return null; - } - - MethodDefinition cmd = new MethodDefinition(Weaver.InvokeRpcPrefix + ed.Name, MethodAttributes.Family | - MethodAttributes.Static | - MethodAttributes.HideBySig, - WeaverTypes.voidType); - - ILProcessor worker = cmd.Body.GetILProcessor(); - Instruction label1 = worker.Create(OpCodes.Nop); - Instruction label2 = worker.Create(OpCodes.Nop); - - NetworkBehaviourProcessor.WriteClientActiveCheck(worker, ed.Name, label1, "Event"); - - // null event check - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Castclass, td)); - worker.Append(worker.Create(OpCodes.Ldfld, eventField)); - worker.Append(worker.Create(OpCodes.Brtrue, label2)); - worker.Append(worker.Create(OpCodes.Ret)); - worker.Append(label2); - - // setup reader - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Castclass, td)); - worker.Append(worker.Create(OpCodes.Ldfld, eventField)); - - // read the event arguments - MethodReference invoke = Resolvers.ResolveMethod(eventField.FieldType, Weaver.CurrentAssembly, "Invoke"); - if (!NetworkBehaviourProcessor.ReadArguments(invoke.Resolve(), worker, RemoteCallType.SyncEvent)) - return null; - - // invoke actual event delegate function - worker.Append(worker.Create(OpCodes.Callvirt, invoke)); - worker.Append(worker.Create(OpCodes.Ret)); - - NetworkBehaviourProcessor.AddInvokeParameters(cmd.Parameters); - - return cmd; - } - - public static MethodDefinition ProcessEventCall(TypeDefinition td, EventDefinition ed, CustomAttribute syncEventAttr) - { - MethodReference invoke = Resolvers.ResolveMethod(ed.EventType, Weaver.CurrentAssembly, "Invoke"); - MethodDefinition evt = new MethodDefinition(Weaver.SyncEventPrefix + ed.Name, MethodAttributes.Public | - MethodAttributes.HideBySig, - WeaverTypes.voidType); - // add paramters - foreach (ParameterDefinition pd in invoke.Parameters) - { - evt.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); - } - - ILProcessor worker = evt.Body.GetILProcessor(); - Instruction label = worker.Create(OpCodes.Nop); - - NetworkBehaviourProcessor.WriteSetupLocals(worker); - - NetworkBehaviourProcessor.WriteServerActiveCheck(worker, ed.Name, label, "Event"); - - NetworkBehaviourProcessor.WriteCreateWriter(worker); - - // write all the arguments that the user passed to the syncevent - if (!NetworkBehaviourProcessor.WriteArguments(worker, invoke.Resolve(), RemoteCallType.SyncEvent)) - return null; - - // invoke interal send and return - // this - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldtoken, td)); - // invokerClass - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.getTypeFromHandleReference)); - worker.Append(worker.Create(OpCodes.Ldstr, ed.Name)); - // writer - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Ldc_I4, syncEventAttr.GetField("channel", 0))); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.sendEventInternal)); - - NetworkBehaviourProcessor.WriteRecycleWriter(worker); - - worker.Append(worker.Create(OpCodes.Ret)); - - return evt; - } - - public static void ProcessEvents(TypeDefinition td, List events, List eventInvocationFuncs) - { - // find events - foreach (EventDefinition ed in td.Events) - { - CustomAttribute syncEventAttr = ed.GetCustomAttribute(WeaverTypes.SyncEventType.FullName); - - if (syncEventAttr != null) - { - ProcessEvent(td, events, eventInvocationFuncs, ed, syncEventAttr); - } - } - } - - static void ProcessEvent(TypeDefinition td, List events, List eventInvocationFuncs, EventDefinition ed, CustomAttribute syncEventAttr) - { - if (ed.EventType.Resolve().HasGenericParameters) - { - Weaver.Error($"{ed.Name} must not have generic parameters. Consider creating a new class that inherits from {ed.EventType} instead", ed); - return; - } - - events.Add(ed); - MethodDefinition eventFunc = ProcessEventInvoke(td, ed); - if (eventFunc == null) - { - return; - } - - td.Methods.Add(eventFunc); - eventInvocationFuncs.Add(eventFunc); - - Weaver.DLog(td, "ProcessEvent " + ed); - - MethodDefinition eventCallFunc = ProcessEventCall(td, ed, syncEventAttr); - td.Methods.Add(eventCallFunc); - - // original weaver compares .Name, not EventDefinition. - Weaver.WeaveLists.replaceEvents[ed.FullName] = eventCallFunc; - - Weaver.DLog(td, " Event: " + ed.Name); - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs deleted file mode 100644 index 20db50b059..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs +++ /dev/null @@ -1,5 +0,0 @@ -// This file was removed in Mirror 3.4.9 -// The purpose of this file is to get the old file overwritten -// when users update from the asset store to prevent a flood of errors -// from having the old file still in the project as a straggler. -// This file will be dropped from the Asset Store package in May 2019 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs.meta deleted file mode 100644 index d3f5278de3..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 97068e5d8cc14490b85933feb119d827 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs deleted file mode 100644 index 67af00e388..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Mono.CecilX; - -namespace Mirror.Weaver -{ - /// - /// generates OnSerialize/OnDeserialize for SyncLists - /// - static class SyncListProcessor - { - /// - /// Generates serialization methods for synclists - /// - /// The synclist class - /// the base SyncObject td inherits from - public static void Process(TypeDefinition td, TypeReference mirrorBaseType) - { - GenericArgumentResolver resolver = new GenericArgumentResolver(1); - - if (resolver.GetGenericFromBaseClass(td, 0, mirrorBaseType, out TypeReference itemType)) - { - SyncObjectProcessor.GenerateSerialization(td, itemType, mirrorBaseType, "SerializeItem", "DeserializeItem"); - } - else - { - Weaver.Error($"Could not find generic arguments for {mirrorBaseType.Name} in {td}", td); - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs deleted file mode 100644 index 20db50b059..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs +++ /dev/null @@ -1,5 +0,0 @@ -// This file was removed in Mirror 3.4.9 -// The purpose of this file is to get the old file overwritten -// when users update from the asset store to prevent a flood of errors -// from having the old file still in the project as a straggler. -// This file will be dropped from the Asset Store package in May 2019 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs.meta deleted file mode 100644 index 8f234cd395..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 28fb192f6a9bc1247b90aa4710f6d34f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs index 2b6bc81952..a17440363c 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs @@ -1,4 +1,3 @@ -using System.Linq; using Mono.CecilX; using Mono.CecilX.Cil; @@ -6,49 +5,15 @@ namespace Mirror.Weaver { public static class SyncObjectInitializer { - public static void GenerateSyncObjectInitializer(ILProcessor worker, FieldDefinition fd) + // generates code like: + // this.InitSyncObject(m_sizes); + public static void GenerateSyncObjectInitializer(ILProcessor worker, WeaverTypes weaverTypes, FieldDefinition fd) { - // call syncobject constructor - GenerateSyncObjectInstanceInitializer(worker, fd); - // register syncobject in network behaviour - GenerateSyncObjectRegistration(worker, fd); - } - - // generates 'syncListInt = new SyncListInt()' if user didn't do that yet - static void GenerateSyncObjectInstanceInitializer(ILProcessor worker, FieldDefinition fd) - { - // check the ctor's instructions for an Stfld op-code for this specific sync list field. - foreach (Instruction ins in worker.Body.Instructions) - { - if (ins.OpCode.Code == Code.Stfld) - { - FieldDefinition field = (FieldDefinition)ins.Operand; - if (field.DeclaringType == fd.DeclaringType && field.Name == fd.Name) - { - // Already initialized by the user in the field definition, e.g: - // public SyncListInt Foo = new SyncListInt(); - return; - } - } - } - - // Not initialized by the user in the field definition, e.g: - // public SyncListInt Foo; - - TypeDefinition fieldType = fd.FieldType.Resolve(); - // find ctor with no parameters - MethodDefinition ctor = fieldType.Methods.FirstOrDefault(x => x.Name == ".ctor" && !x.HasParameters); - if (ctor == null) - { - Weaver.Error($"Can not initialize field {fd.Name} because no default constructor was found. Manually initialize the field (call the constructor) or add constructor without Parameter", fd); - return; - } - MethodReference objectConstructor = Weaver.CurrentAssembly.MainModule.ImportReference(ctor); - - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Newobj, objectConstructor)); - worker.Append(worker.Create(OpCodes.Stfld, fd)); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, fd); + worker.Emit(OpCodes.Call, weaverTypes.InitSyncObjectReference); } public static bool ImplementsSyncObject(TypeReference typeRef) @@ -61,7 +26,7 @@ public static bool ImplementsSyncObject(TypeReference typeRef) return false; } - return typeRef.Resolve().ImplementsInterface(WeaverTypes.SyncObjectType); + return typeRef.Resolve().IsDerivedFrom(); } catch { @@ -70,18 +35,5 @@ public static bool ImplementsSyncObject(TypeReference typeRef) return false; } - - /* - // generates code like: - this.InitSyncObject(m_sizes); - */ - static void GenerateSyncObjectRegistration(ILProcessor worker, FieldDefinition fd) - { - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, fd)); - - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.InitSyncObjectReference)); - } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta index 22f976e796..285c0da8ab 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs index b74b8e11f5..8143e861df 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs @@ -1,154 +1,90 @@ using System.Collections.Generic; using Mono.CecilX; -using Mono.CecilX.Cil; namespace Mirror.Weaver { public static class SyncObjectProcessor { - /// - /// Finds SyncObjects fields in a type - /// Type should be a NetworkBehaviour - /// - /// - /// - public static List FindSyncObjectsFields(TypeDefinition td) + // ulong = 64 bytes + const int SyncObjectsLimit = 64; + + // Finds SyncObjects fields in a type + // Type should be a NetworkBehaviour + public static List FindSyncObjectsFields(Writers writers, Readers readers, Logger Log, TypeDefinition td, ref bool WeavingFailed) { List syncObjects = new List(); foreach (FieldDefinition fd in td.Fields) { - if (fd.FieldType.Resolve().ImplementsInterface(WeaverTypes.SyncObjectType)) + if (fd.FieldType.IsGenericParameter || fd.ContainsGenericParameter) + { + // can't call .Resolve on generic ones + continue; + } + + if (fd.FieldType.Resolve().IsDerivedFrom()) { if (fd.IsStatic) { - Weaver.Error($"{fd.Name} cannot be static", fd); + Log.Error($"{fd.Name} cannot be static", fd); + WeavingFailed = true; continue; } - if (fd.FieldType.Resolve().HasGenericParameters) + // SyncObjects always needs to be readonly to guarantee. + // Weaver calls InitSyncObject on them for dirty bits etc. + // Reassigning at runtime would cause undefined behaviour. + // (C# 'readonly' is called 'initonly' in IL code.) + // + // NOTE: instead of forcing readonly, we could also scan all + // instructions for SyncObject assignments. this would + // make unit tests very difficult though. + if (!fd.IsInitOnly) { - Weaver.Error($"Cannot use generic SyncObject {fd.Name} directly in NetworkBehaviour. Create a class and inherit from the generic SyncObject instead", fd); - continue; + // just a warning for now. + // many people might still use non-readonly SyncObjects. + Log.Warning($"{fd.Name} should have a 'readonly' keyword in front of the variable because {typeof(SyncObject)}s always need to be initialized by the Weaver.", fd); + + // only log, but keep weaving. no need to break projects. + //WeavingFailed = true; } + GenerateReadersAndWriters(writers, readers, fd.FieldType, ref WeavingFailed); + syncObjects.Add(fd); } } - - return syncObjects; - } - - /// - /// Generates the serialization and deserialization methods for a specified generic argument - /// - /// The type of the class that needs serialization methods - /// generic argument to serialize - /// the base SyncObject td inherits from - /// The name of the serialize method - /// The name of the deserialize method - public static void GenerateSerialization(TypeDefinition td, TypeReference itemType, TypeReference mirrorBaseType, string serializeMethod, string deserializeMethod) - { - Weaver.DLog(td, "SyncObjectProcessor Start item:" + itemType.FullName); - - bool success = GenerateSerialization(serializeMethod, td, itemType, mirrorBaseType); - if (Weaver.WeavingFailed) - { - return; - } - - success |= GenerateDeserialization(deserializeMethod, td, itemType, mirrorBaseType); - - if (success) - Weaver.DLog(td, "SyncObjectProcessor Done"); - } - - // serialization of individual element - static bool GenerateSerialization(string methodName, TypeDefinition td, TypeReference itemType, TypeReference mirrorBaseType) - { - Weaver.DLog(td, " GenerateSerialization"); - bool existing = td.HasMethodInBaseType(methodName, mirrorBaseType); - if (existing) - return true; - - - // this check needs to happen inside GenerateSerialization because - // we need to check if user has made custom function above - if (itemType.IsGenericInstance) + // SyncObjects dirty mask is 64 bit. can't sync more than 64. + if (syncObjects.Count > 64) { - Weaver.Error($"Can not create Serialize or Deserialize for generic element in {td.Name}. Override virtual methods with custom Serialize and Deserialize to use {itemType} in SyncList", td); - return false; + Log.Error($"{td.Name} has > {SyncObjectsLimit} SyncObjects (SyncLists etc). Consider refactoring your class into multiple components", td); + WeavingFailed = true; } - MethodDefinition serializeFunc = new MethodDefinition(methodName, MethodAttributes.Public | - MethodAttributes.Virtual | - MethodAttributes.Public | - MethodAttributes.HideBySig, - WeaverTypes.voidType); - - serializeFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkWriterType))); - serializeFunc.Parameters.Add(new ParameterDefinition("item", ParameterAttributes.None, itemType)); - ILProcessor worker = serializeFunc.Body.GetILProcessor(); - - MethodReference writeFunc = Writers.GetWriteFunc(itemType); - if (writeFunc != null) - { - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Ldarg_2)); - worker.Append(worker.Create(OpCodes.Call, writeFunc)); - } - else - { - Weaver.Error($"{td.Name} has sync object generic type {itemType.Name}. Use a type supported by mirror instead", td); - return false; - } - worker.Append(worker.Create(OpCodes.Ret)); - td.Methods.Add(serializeFunc); - return true; + return syncObjects; } - static bool GenerateDeserialization(string methodName, TypeDefinition td, TypeReference itemType, TypeReference mirrorBaseType) + // Generates serialization methods for synclists + static void GenerateReadersAndWriters(Writers writers, Readers readers, TypeReference tr, ref bool WeavingFailed) { - Weaver.DLog(td, " GenerateDeserialization"); - bool existing = td.HasMethodInBaseType(methodName, mirrorBaseType); - if (existing) - return true; - - // this check needs to happen inside GenerateDeserialization because - // we need to check if user has made custom function above - if (itemType.IsGenericInstance) + if (tr is GenericInstanceType genericInstance) { - Weaver.Error($"Can not create Serialize or Deserialize for generic element in {td.Name}. Override virtual methods with custom Serialize and Deserialize to use {itemType.Name} in SyncList", td); - return false; + foreach (TypeReference argument in genericInstance.GenericArguments) + { + if (!argument.IsGenericParameter) + { + readers.GetReadFunc(argument, ref WeavingFailed); + writers.GetWriteFunc(argument, ref WeavingFailed); + } + } } - MethodDefinition deserializeFunction = new MethodDefinition(methodName, MethodAttributes.Public | - MethodAttributes.Virtual | - MethodAttributes.Public | - MethodAttributes.HideBySig, - itemType); - - deserializeFunction.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkReaderType))); - - ILProcessor worker = deserializeFunction.Body.GetILProcessor(); - - MethodReference readerFunc = Readers.GetReadFunc(itemType); - if (readerFunc != null) + if (tr != null) { - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Call, readerFunc)); - worker.Append(worker.Create(OpCodes.Ret)); + GenerateReadersAndWriters(writers, readers, tr.Resolve().BaseType, ref WeavingFailed); } - else - { - Weaver.Error($"{td.Name} has sync object generic type {itemType.Name}. Use a type supported by mirror instead", td); - return false; - } - - td.Methods.Add(deserializeFunction); - return true; } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta index 0efe434a24..e56996f822 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs new file mode 100644 index 0000000000..73a9526342 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs @@ -0,0 +1,206 @@ +// [SyncVar] int health; +// is replaced with: +// public int Networkhealth { get; set; } properties. +// this class processes all access to 'health' and replaces it with 'Networkhealth' +using System; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class SyncVarAttributeAccessReplacer + { + // process the module + public static void Process(Logger Log, ModuleDefinition moduleDef, SyncVarAccessLists syncVarAccessLists) + { + DateTime startTime = DateTime.Now; + + // process all classes in this module + foreach (TypeDefinition td in moduleDef.Types) + { + if (td.IsClass) + { + ProcessClass(Log, syncVarAccessLists, td); + } + } + + Console.WriteLine($" ProcessSitesModule {moduleDef.Name} elapsed time:{(DateTime.Now - startTime)}"); + } + + static void ProcessClass(Logger Log, SyncVarAccessLists syncVarAccessLists, TypeDefinition td) + { + //Console.WriteLine($" ProcessClass {td}"); + + // process all methods in this class + foreach (MethodDefinition md in td.Methods) + { + ProcessMethod(Log, syncVarAccessLists, md); + } + + // processes all nested classes in this class recursively + foreach (TypeDefinition nested in td.NestedTypes) + { + ProcessClass(Log, syncVarAccessLists, nested); + } + } + + static void ProcessMethod(Logger Log, SyncVarAccessLists syncVarAccessLists, MethodDefinition md) + { + // process all references to replaced members with properties + //Log.Warning($" ProcessSiteMethod {md}"); + + // skip static constructor, "MirrorProcessed", "InvokeUserCode_" + if (md.Name == ".cctor" || + md.Name == NetworkBehaviourProcessor.ProcessedFunctionName || + md.Name.StartsWith(RemoteCalls.RemoteProcedureCalls.InvokeRpcPrefix)) + return; + + // skip abstract + if (md.IsAbstract) + { + return; + } + + // go through all instructions of this method + if (md.Body != null && md.Body.Instructions != null) + { + for (int i = 0; i < md.Body.Instructions.Count;) + { + Instruction instr = md.Body.Instructions[i]; + i += ProcessInstruction(Log, syncVarAccessLists, md, instr, i); + } + } + } + + static int ProcessInstruction(Logger Log, SyncVarAccessLists syncVarAccessLists, MethodDefinition md, Instruction instr, int iCount) + { + // stfld (sets value of a field)? + if (instr.OpCode == OpCodes.Stfld) + { + // operand is a FieldDefinition in the same assembly? + if (instr.Operand is FieldDefinition opFieldst) + { + ProcessSetInstruction(syncVarAccessLists, md, instr, opFieldst); + } + // operand is a FieldReference in another assembly? + // this is not supported just yet. + // compilation error is better than silently failing SyncVar serialization at runtime. + // https://github.com/MirrorNetworking/Mirror/issues/3525 + else if (instr.Operand is FieldReference opFieldstRef) + { + // resolve it from the other assembly + FieldDefinition field = opFieldstRef.Resolve(); + + // [SyncVar]? + if (field.HasCustomAttribute()) + { + // ILPostProcessor would need to Process() the assembly's + // references before processing this one. + // we can not control the order. + // instead, Log an error to suggest adding a SetSyncVar(value) function. + // this is a very easy solution for a very rare edge case. + Log.Error($"'[SyncVar] {opFieldstRef.DeclaringType.Name}.{opFieldstRef.Name}' in '{field.Module.Name}' is modified by '{md.FullName}' in '{md.Module.Name}'. Modifying a [SyncVar] from another assembly is not supported. Please add a: 'public void Set{opFieldstRef.Name}(value) {{ this.{opFieldstRef.Name} = value; }}' method in '{opFieldstRef.DeclaringType.Name}' and call this function from '{md.FullName}' instead."); + } + } + } + + // ldfld (load value of a field)? + if (instr.OpCode == OpCodes.Ldfld) + { + // operand is a FieldDefinition in the same assembly? + if (instr.Operand is FieldDefinition opFieldld) + { + // this instruction gets the value of a field. cache the field reference. + ProcessGetInstruction(syncVarAccessLists, md, instr, opFieldld); + } + } + + // ldflda (load field address aka reference) + if (instr.OpCode == OpCodes.Ldflda) + { + // operand is a FieldDefinition in the same assembly? + if (instr.Operand is FieldDefinition opFieldlda) + { + // watch out for initobj instruction + // see https://github.com/vis2k/Mirror/issues/696 + return ProcessLoadAddressInstruction(syncVarAccessLists, md, instr, opFieldlda, iCount); + } + } + + // we processed one instruction (instr) + return 1; + } + + // replaces syncvar write access with the NetworkXYZ.set property calls + static void ProcessSetInstruction(SyncVarAccessLists syncVarAccessLists, MethodDefinition md, Instruction i, FieldDefinition opField) + { + // don't replace property call sites in constructors + if (md.Name == ".ctor") + return; + + // does it set a field that we replaced? + if (syncVarAccessLists.replacementSetterProperties.TryGetValue(opField, out MethodDefinition replacement)) + { + //replace with property + //Log.Warning($" replacing {md.Name}:{i}", opField); + i.OpCode = OpCodes.Call; + i.Operand = replacement; + //Log.Warning($" replaced {md.Name}:{i}", opField); + } + } + + // replaces syncvar read access with the NetworkXYZ.get property calls + static void ProcessGetInstruction(SyncVarAccessLists syncVarAccessLists, MethodDefinition md, Instruction i, FieldDefinition opField) + { + // don't replace property call sites in constructors + if (md.Name == ".ctor") + return; + + // does it set a field that we replaced? + if (syncVarAccessLists.replacementGetterProperties.TryGetValue(opField, out MethodDefinition replacement)) + { + //replace with property + //Log.Warning($" replacing {md.Name}:{i}"); + i.OpCode = OpCodes.Call; + i.Operand = replacement; + //Log.Warning($" replaced {md.Name}:{i}"); + } + } + + static int ProcessLoadAddressInstruction(SyncVarAccessLists syncVarAccessLists, MethodDefinition md, Instruction instr, FieldDefinition opField, int iCount) + { + // don't replace property call sites in constructors + if (md.Name == ".ctor") + return 1; + + // does it set a field that we replaced? + if (syncVarAccessLists.replacementSetterProperties.TryGetValue(opField, out MethodDefinition replacement)) + { + // we have a replacement for this property + // is the next instruction a initobj? + Instruction nextInstr = md.Body.Instructions[iCount + 1]; + + if (nextInstr.OpCode == OpCodes.Initobj) + { + // we need to replace this code with: + // var tmp = new MyStruct(); + // this.set_Networkxxxx(tmp); + ILProcessor worker = md.Body.GetILProcessor(); + VariableDefinition tmpVariable = new VariableDefinition(opField.FieldType); + md.Body.Variables.Add(tmpVariable); + + worker.InsertBefore(instr, worker.Create(OpCodes.Ldloca, tmpVariable)); + worker.InsertBefore(instr, worker.Create(OpCodes.Initobj, opField.FieldType)); + worker.InsertBefore(instr, worker.Create(OpCodes.Ldloc, tmpVariable)); + worker.InsertBefore(instr, worker.Create(OpCodes.Call, replacement)); + + worker.Remove(instr); + worker.Remove(nextInstr); + return 4; + } + } + + return 1; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs.meta new file mode 100644 index 0000000000..ad4c24483f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: d48f1ab125e9940a995603796bccc59e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs new file mode 100644 index 0000000000..76e3ac7ed5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs @@ -0,0 +1,515 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Mono.CecilX; +using Mono.CecilX.Cil; +using Mono.CecilX.Rocks; + +namespace Mirror.Weaver +{ + // Processes [SyncVar] attribute fields in NetworkBehaviour + // not static, because ILPostProcessor is multithreaded + public class SyncVarAttributeProcessor + { + // ulong = 64 bytes + const int SyncVarLimit = 64; + + AssemblyDefinition assembly; + WeaverTypes weaverTypes; + SyncVarAccessLists syncVarAccessLists; + Logger Log; + + string HookParameterMessage(string hookName, TypeReference ValueType) => + $"void {hookName}({ValueType} oldValue, {ValueType} newValue)"; + + public SyncVarAttributeProcessor(AssemblyDefinition assembly, WeaverTypes weaverTypes, SyncVarAccessLists syncVarAccessLists, Logger Log) + { + this.assembly = assembly; + this.weaverTypes = weaverTypes; + this.syncVarAccessLists = syncVarAccessLists; + this.Log = Log; + } + + // Get hook method if any + public MethodDefinition GetHookMethod(TypeDefinition td, FieldDefinition syncVar, ref bool WeavingFailed) + { + CustomAttribute syncVarAttr = syncVar.GetCustomAttribute(); + + if (syncVarAttr == null) + return null; + + string hookFunctionName = syncVarAttr.GetField("hook", null); + + if (hookFunctionName == null) + return null; + + return FindHookMethod(td, syncVar, hookFunctionName, ref WeavingFailed); + } + + // Create a field definition for a field that will store the Action delegate instance for the syncvar hook method (only instantiate delegate once) + public FieldDefinition CreateNewActionFieldDefinitionFromHookMethod(FieldDefinition syncVarField) + { + TypeReference actionRef = assembly.MainModule.ImportReference(typeof(Action<,>)); + GenericInstanceType syncVarHookActionDelegateType = actionRef.MakeGenericInstanceType(syncVarField.FieldType, syncVarField.FieldType); + string syncVarHookDelegateFieldName = $"_Mirror_SyncVarHookDelegate_{syncVarField.Name}"; + return new FieldDefinition(syncVarHookDelegateFieldName, FieldAttributes.Public, syncVarHookActionDelegateType); + } + + // push hook from GetHookMethod() onto the stack as a new Action. + // allows for reuse without handling static/virtual cases every time. + // perf warning: it is recommended to use this method only when generating IL to create a new Action() in order to store it into a field + // avoid using this to emit IL to instantiate a new action instance every single time one is needed for the same method + public void GenerateNewActionFromHookMethod(FieldDefinition syncVar, ILProcessor worker, MethodDefinition hookMethod) + { + // IL_000a: ldarg.0 + // IL_000b: ldftn instance void Mirror.Examples.Tanks.Tank::ExampleHook(int32, int32) + // IL_0011: newobj instance void class [netstandard]System.Action`2::.ctor(object, native int) + + // we support static hooks and instance hooks. + if (hookMethod.IsStatic) + { + // for static hooks, we need to push 'null' first. + // we can't just push nothing. + // stack would get out of balance because we already pushed + // other stuff above. + worker.Emit(OpCodes.Ldnull); + } + else + { + // for instance hooks, we need to push 'this.' first. + worker.Emit(OpCodes.Ldarg_0); + } + + MethodReference hookMethodReference; + // if the network behaviour class is generic, we need to make the method reference generic for correct IL + if (hookMethod.DeclaringType.HasGenericParameters) + { + hookMethodReference = hookMethod.MakeHostInstanceGeneric(hookMethod.Module, hookMethod.DeclaringType.MakeGenericInstanceType(hookMethod.DeclaringType.GenericParameters.ToArray())); + } + else + { + hookMethodReference = hookMethod; + } + + // we support regular and virtual hook functions. + if (hookMethod.IsVirtual) + { + // for virtual / overwritten hooks, we need different IL. + // this is from simply testing Action = VirtualHook; in C#. + worker.Emit(OpCodes.Dup); + worker.Emit(OpCodes.Ldvirtftn, hookMethodReference); + } + else + { + worker.Emit(OpCodes.Ldftn, hookMethodReference); + } + + // call 'new Action()' constructor to convert the function to an action + // we need to make an instance of the generic Action. + TypeReference actionRef = assembly.MainModule.ImportReference(typeof(Action<,>)); + GenericInstanceType genericInstance = actionRef.MakeGenericInstanceType(syncVar.FieldType, syncVar.FieldType); + worker.Emit(OpCodes.Newobj, weaverTypes.ActionT_T.MakeHostInstanceGeneric(assembly.MainModule, genericInstance)); + } + + // generates CIL to set an Action instance field to a new Action(hookMethod) + // this.hookDelegate = new Action(HookMethod); + public void GenerateSyncVarHookDelegateInitializer(ILProcessor worker, FieldDefinition syncVar, FieldDefinition hookDelegate, MethodDefinition hookMethod) + { + // push this + worker.Emit(OpCodes.Ldarg_0); + // push new Action(hookMethod) + GenerateNewActionFromHookMethod(syncVar, worker, hookMethod); + // set field + worker.Emit(OpCodes.Stfld, hookDelegate); + } + + MethodDefinition FindHookMethod(TypeDefinition td, FieldDefinition syncVar, string hookFunctionName, ref bool WeavingFailed) + { + List methods = td.GetMethods(hookFunctionName); + + List methodsWith2Param = new List(methods.Where(m => m.Parameters.Count == 2)); + + if (methodsWith2Param.Count == 0) + { + Log.Error($"Could not find hook for '{syncVar.Name}', hook name '{hookFunctionName}'. " + + $"Method signature should be {HookParameterMessage(hookFunctionName, syncVar.FieldType)}", + syncVar); + WeavingFailed = true; + + return null; + } + + foreach (MethodDefinition method in methodsWith2Param) + { + if (MatchesParameters(syncVar, method)) + { + return method; + } + } + + Log.Error($"Wrong type for Parameter in hook for '{syncVar.Name}', hook name '{hookFunctionName}'. " + + $"Method signature should be {HookParameterMessage(hookFunctionName, syncVar.FieldType)}", + syncVar); + WeavingFailed = true; + + return null; + } + + bool MatchesParameters(FieldDefinition syncVar, MethodDefinition method) + { + // matches void onValueChange(T oldValue, T newValue) + return method.Parameters[0].ParameterType.FullName == syncVar.FieldType.FullName && + method.Parameters[1].ParameterType.FullName == syncVar.FieldType.FullName; + } + + public MethodDefinition GenerateSyncVarGetter(FieldDefinition fd, string originalName, FieldDefinition netFieldId) + { + //Create the get method + MethodDefinition get = new MethodDefinition( + $"get_Network{originalName}", MethodAttributes.Public | + MethodAttributes.SpecialName | + MethodAttributes.HideBySig, + fd.FieldType); + + ILProcessor worker = get.Body.GetILProcessor(); + + FieldReference fr; + if (fd.DeclaringType.HasGenericParameters) + { + fr = fd.MakeHostInstanceGeneric(); + } + else + { + fr = fd; + } + + FieldReference netIdFieldReference = null; + if (netFieldId != null) + { + if (netFieldId.DeclaringType.HasGenericParameters) + { + netIdFieldReference = netFieldId.MakeHostInstanceGeneric(); + } + else + { + netIdFieldReference = netFieldId; + } + } + + // [SyncVar] GameObject? + if (fd.FieldType.Is()) + { + // return this.GetSyncVarGameObject(ref field, uint netId); + // this. + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, netIdFieldReference); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, fr); + worker.Emit(OpCodes.Call, weaverTypes.getSyncVarGameObjectReference); + worker.Emit(OpCodes.Ret); + } + // [SyncVar] NetworkIdentity? + else if (fd.FieldType.Is()) + { + // return this.GetSyncVarNetworkIdentity(ref field, uint netId); + // this. + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, netIdFieldReference); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, fr); + worker.Emit(OpCodes.Call, weaverTypes.getSyncVarNetworkIdentityReference); + worker.Emit(OpCodes.Ret); + } + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + else if (fd.FieldType.IsDerivedFrom() || fd.FieldType.Is()) + { + // return this.GetSyncVarNetworkBehaviour(ref field, uint netId); + // this. + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, netIdFieldReference); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, fr); + MethodReference getFunc = weaverTypes.getSyncVarNetworkBehaviourReference.MakeGeneric(assembly.MainModule, fd.FieldType); + worker.Emit(OpCodes.Call, getFunc); + worker.Emit(OpCodes.Ret); + } + // [SyncVar] int, string, etc. + else + { + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, fr); + worker.Emit(OpCodes.Ret); + } + + get.Body.Variables.Add(new VariableDefinition(fd.FieldType)); + get.Body.InitLocals = true; + get.SemanticsAttributes = MethodSemanticsAttributes.Getter; + + return get; + } + + // for [SyncVar] health, weaver generates + // + // NetworkHealth + // { + // get => health; + // set => GeneratedSyncVarSetter(...) + // } + // + // the setter used to be manually IL generated, but we moved it to C# :) + public MethodDefinition GenerateSyncVarSetter(TypeDefinition td, FieldDefinition fd, string originalName, long dirtyBit, FieldDefinition netFieldId, Dictionary syncVarHookDelegates, ref bool WeavingFailed) + { + //Create the set method + MethodDefinition set = new MethodDefinition($"set_Network{originalName}", MethodAttributes.Public | + MethodAttributes.SpecialName | + MethodAttributes.HideBySig, + weaverTypes.Import(typeof(void))); + + ILProcessor worker = set.Body.GetILProcessor(); + FieldReference fr; + if (fd.DeclaringType.HasGenericParameters) + { + fr = fd.MakeHostInstanceGeneric(); + } + else + { + fr = fd; + } + + FieldReference netIdFieldReference = null; + if (netFieldId != null) + { + if (netFieldId.DeclaringType.HasGenericParameters) + { + netIdFieldReference = netFieldId.MakeHostInstanceGeneric(); + } + else + { + netIdFieldReference = netFieldId; + } + } + + // if (!SyncVarEqual(value, ref playerData)) + Instruction endOfMethod = worker.Create(OpCodes.Nop); + + // NOTE: SyncVar...Equal functions are static. + // don't Emit Ldarg_0 aka 'this'. + + // call WeaverSyncVarSetter(T value, ref T field, ulong dirtyBit, Action OnChanged = null) + // IL_0000: ldarg.0 + // IL_0001: ldarg.1 + // IL_0002: ldarg.0 + // IL_0003: ldflda int32 Mirror.Examples.Tanks.Tank::health + // IL_0008: ldc.i4.1 + // IL_0009: conv.i8 + // IL_000a: ldnull + // IL_000b: call instance void [Mirror]Mirror.NetworkBehaviour::GeneratedSyncVarSetter(!!0, !!0&, uint64, class [netstandard]System.Action`2) + // IL_0010: ret + + // 'this.' for the call + worker.Emit(OpCodes.Ldarg_0); + + // first push 'value' + worker.Emit(OpCodes.Ldarg_1); + + // push 'ref T this.field' + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, fr); + + // push the dirty bit for this SyncVar + worker.Emit(OpCodes.Ldc_I8, dirtyBit); + + // hook? then push 'this.HookDelegate' onto stack + MethodDefinition hookMethod = GetHookMethod(td, fd, ref WeavingFailed); + if (hookMethod != null) + { + // Create the field that will store a single instance of the hook as a delegate (field will be set in constructor) + FieldDefinition hookActionDelegateField = CreateNewActionFieldDefinitionFromHookMethod(fd); + syncVarHookDelegates[fd] = (hookActionDelegateField, hookMethod); + + // push this.hookActionDelegateField + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, hookActionDelegateField); + } + // otherwise push 'null' as hook + else + { + worker.Emit(OpCodes.Ldnull); + } + + // call GeneratedSyncVarSetter. + // special cases for GameObject/NetworkIdentity/NetworkBehaviour + // passing netId too for persistence. + if (fd.FieldType.Is()) + { + // GameObject setter needs one more parameter: netId field ref + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdFieldReference); + worker.Emit(OpCodes.Call, weaverTypes.generatedSyncVarSetter_GameObject); + } + else if (fd.FieldType.Is()) + { + // NetworkIdentity setter needs one more parameter: netId field ref + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdFieldReference); + worker.Emit(OpCodes.Call, weaverTypes.generatedSyncVarSetter_NetworkIdentity); + } + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + else if (fd.FieldType.IsDerivedFrom() || fd.FieldType.Is()) + { + // NetworkIdentity setter needs one more parameter: netId field ref + // (actually its a NetworkBehaviourSyncVar type) + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdFieldReference); + // make generic version of GeneratedSyncVarSetter_NetworkBehaviour + MethodReference getFunc = weaverTypes.generatedSyncVarSetter_NetworkBehaviour_T.MakeGeneric(assembly.MainModule, fd.FieldType); + worker.Emit(OpCodes.Call, getFunc); + } + else + { + // make generic version of GeneratedSyncVarSetter + MethodReference generic = weaverTypes.generatedSyncVarSetter.MakeGeneric(assembly.MainModule, fd.FieldType); + worker.Emit(OpCodes.Call, generic); + } + + worker.Append(endOfMethod); + + worker.Emit(OpCodes.Ret); + + set.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.In, fd.FieldType)); + set.SemanticsAttributes = MethodSemanticsAttributes.Setter; + + return set; + } + + public void ProcessSyncVar(TypeDefinition td, FieldDefinition fd, Dictionary syncVarNetIds, Dictionary syncVarHookDelegates, long dirtyBit, ref bool WeavingFailed) + { + string originalName = fd.Name; + + // GameObject/NetworkIdentity SyncVars have a new field for netId + FieldDefinition netIdField = null; + // NetworkBehaviour has different field type than other NetworkIdentityFields + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + if (fd.FieldType.IsDerivedFrom() || fd.FieldType.Is()) + { + netIdField = new FieldDefinition($"___{fd.Name}NetId", + FieldAttributes.Family, // needs to be protected for generic classes, otherwise access isn't allowed + weaverTypes.Import()); + netIdField.DeclaringType = td; + + syncVarNetIds[fd] = netIdField; + } + else if (fd.FieldType.IsNetworkIdentityField()) + { + netIdField = new FieldDefinition($"___{fd.Name}NetId", + FieldAttributes.Family, // needs to be protected for generic classes, otherwise access isn't allowed + weaverTypes.Import()); + netIdField.DeclaringType = td; + + syncVarNetIds[fd] = netIdField; + } + + MethodDefinition get = GenerateSyncVarGetter(fd, originalName, netIdField); + MethodDefinition set = GenerateSyncVarSetter(td, fd, originalName, dirtyBit, netIdField, syncVarHookDelegates, ref WeavingFailed); + + //NOTE: is property even needed? Could just use a setter function? + //create the property + PropertyDefinition propertyDefinition = new PropertyDefinition($"Network{originalName}", PropertyAttributes.None, fd.FieldType) + { + GetMethod = get, + SetMethod = set + }; + + //add the methods and property to the type. + td.Methods.Add(get); + td.Methods.Add(set); + td.Properties.Add(propertyDefinition); + syncVarAccessLists.replacementSetterProperties[fd] = set; + + // replace getter field if GameObject/NetworkIdentity so it uses + // netId instead + // -> only for GameObjects, otherwise an int syncvar's getter would + // end up in recursion. + if (fd.FieldType.IsNetworkIdentityField()) + { + syncVarAccessLists.replacementGetterProperties[fd] = get; + } + } + + public (List syncVars, Dictionary syncVarNetIds, Dictionary syncVarHookDelegates) ProcessSyncVars(TypeDefinition td, ref bool WeavingFailed) + { + List syncVars = new List(); + Dictionary syncVarNetIds = new Dictionary(); + Dictionary syncVarHookDelegates = new Dictionary(); + + // the mapping of dirtybits to sync-vars is implicit in the order of the fields here. this order is recorded in m_replacementProperties. + // start assigning syncvars at the place the base class stopped, if any + int dirtyBitCounter = syncVarAccessLists.GetSyncVarStart(td.BaseType.FullName); + + // find syncvars + foreach (FieldDefinition fd in td.Fields) + { + if (fd.HasCustomAttribute()) + { + if ((fd.Attributes & FieldAttributes.Static) != 0) + { + Log.Error($"{fd.Name} cannot be static", fd); + WeavingFailed = true; + continue; + } + + if (fd.FieldType.IsGenericParameter) + { + Log.Error($"{fd.Name} has generic type. Generic SyncVars are not supported", fd); + WeavingFailed = true; + continue; + } + + if (SyncObjectInitializer.ImplementsSyncObject(fd.FieldType)) + { + Log.Warning($"{fd.Name} has [SyncVar] attribute. SyncLists should not be marked with SyncVar", fd); + } + else + { + syncVars.Add(fd); + + ProcessSyncVar(td, fd, syncVarNetIds, syncVarHookDelegates, 1L << dirtyBitCounter, ref WeavingFailed); + dirtyBitCounter += 1; + + if (dirtyBitCounter > SyncVarLimit) + { + Log.Error($"{td.Name} has > {SyncVarLimit} SyncVars. Consider refactoring your class into multiple components", td); + WeavingFailed = true; + continue; + } + } + } + } + + // add all the new SyncVar __netId fields + foreach (FieldDefinition fd in syncVarNetIds.Values) + { + td.Fields.Add(fd); + } + + // add all of the new SyncVar Action fields + foreach((FieldDefinition hookDelegateInstanceField, MethodDefinition) entry in syncVarHookDelegates.Values) + { + td.Fields.Add(entry.hookDelegateInstanceField); + } + + // include parent class syncvars + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3457 + int parentSyncVarCount = syncVarAccessLists.GetSyncVarStart(td.BaseType.FullName); + syncVarAccessLists.SetNumSyncVars(td.FullName, parentSyncVarCount + syncVars.Count); + + return (syncVars, syncVarNetIds, syncVarHookDelegates); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs.meta new file mode 100644 index 0000000000..492b065716 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: f52c39bddd95d42b88f9cd554dfd9198 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs deleted file mode 100644 index 71d3961948..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs +++ /dev/null @@ -1,434 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Mono.CecilX; -using Mono.CecilX.Cil; - -namespace Mirror.Weaver -{ - /// - /// Processes [SyncVar] in NetworkBehaviour - /// - public static class SyncVarProcessor - { - // ulong = 64 bytes - const int SyncVarLimit = 64; - - - static string HookParameterMessage(string hookName, TypeReference ValueType) - => string.Format("void {0}({1} oldValue, {1} newValue)", hookName, ValueType); - - // Get hook method if any - public static MethodDefinition GetHookMethod(TypeDefinition td, FieldDefinition syncVar) - { - CustomAttribute syncVarAttr = syncVar.GetCustomAttribute(WeaverTypes.SyncVarType.FullName); - - if (syncVarAttr == null) - return null; - - string hookFunctionName = syncVarAttr.GetField("hook", null); - - if (hookFunctionName == null) - return null; - - return FindHookMethod(td, syncVar, hookFunctionName); - } - - static MethodDefinition FindHookMethod(TypeDefinition td, FieldDefinition syncVar, string hookFunctionName) - { - List methods = td.GetMethods(hookFunctionName); - - List methodsWith2Param = new List(methods.Where(m => m.Parameters.Count == 2)); - - if (methodsWith2Param.Count == 0) - { - Weaver.Error($"Could not find hook for '{syncVar.Name}', hook name '{hookFunctionName}'. " + - $"Method signature should be {HookParameterMessage(hookFunctionName, syncVar.FieldType)}", - syncVar); - - return null; - } - - foreach (MethodDefinition method in methodsWith2Param) - { - if (MatchesParameters(syncVar, method)) - { - return method; - } - } - - Weaver.Error($"Wrong type for Parameter in hook for '{syncVar.Name}', hook name '{hookFunctionName}'. " + - $"Method signature should be {HookParameterMessage(hookFunctionName, syncVar.FieldType)}", - syncVar); - - return null; - } - - static bool MatchesParameters(FieldDefinition syncVar, MethodDefinition method) - { - // matches void onValueChange(T oldValue, T newValue) - return method.Parameters[0].ParameterType.FullName == syncVar.FieldType.FullName && - method.Parameters[1].ParameterType.FullName == syncVar.FieldType.FullName; - } - - public static MethodDefinition ProcessSyncVarGet(FieldDefinition fd, string originalName, FieldDefinition netFieldId) - { - //Create the get method - MethodDefinition get = new MethodDefinition( - "get_Network" + originalName, MethodAttributes.Public | - MethodAttributes.SpecialName | - MethodAttributes.HideBySig, - fd.FieldType); - - ILProcessor worker = get.Body.GetILProcessor(); - - // [SyncVar] GameObject? - if (fd.FieldType.FullName == WeaverTypes.gameObjectType.FullName) - { - // return this.GetSyncVarGameObject(ref field, uint netId); - // this. - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, netFieldId)); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldflda, fd)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.getSyncVarGameObjectReference)); - worker.Append(worker.Create(OpCodes.Ret)); - } - // [SyncVar] NetworkIdentity? - else if (fd.FieldType.FullName == WeaverTypes.NetworkIdentityType.FullName) - { - // return this.GetSyncVarNetworkIdentity(ref field, uint netId); - // this. - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, netFieldId)); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldflda, fd)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.getSyncVarNetworkIdentityReference)); - worker.Append(worker.Create(OpCodes.Ret)); - } - // [SyncVar] int, string, etc. - else - { - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, fd)); - worker.Append(worker.Create(OpCodes.Ret)); - } - - get.Body.Variables.Add(new VariableDefinition(fd.FieldType)); - get.Body.InitLocals = true; - get.SemanticsAttributes = MethodSemanticsAttributes.Getter; - - return get; - } - - public static MethodDefinition ProcessSyncVarSet(TypeDefinition td, FieldDefinition fd, string originalName, long dirtyBit, FieldDefinition netFieldId) - { - //Create the set method - MethodDefinition set = new MethodDefinition("set_Network" + originalName, MethodAttributes.Public | - MethodAttributes.SpecialName | - MethodAttributes.HideBySig, - WeaverTypes.voidType); - - ILProcessor worker = set.Body.GetILProcessor(); - - // if (!SyncVarEqual(value, ref playerData)) - Instruction endOfMethod = worker.Create(OpCodes.Nop); - - // this - worker.Append(worker.Create(OpCodes.Ldarg_0)); - // new value to set - worker.Append(worker.Create(OpCodes.Ldarg_1)); - // reference to field to set - // make generic version of SetSyncVar with field type - if (fd.FieldType.FullName == WeaverTypes.gameObjectType.FullName) - { - // reference to netId Field to set - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, netFieldId)); - - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.syncVarGameObjectEqualReference)); - } - else if (fd.FieldType.FullName == WeaverTypes.NetworkIdentityType.FullName) - { - // reference to netId Field to set - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, netFieldId)); - - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.syncVarNetworkIdentityEqualReference)); - } - else - { - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldflda, fd)); - - GenericInstanceMethod syncVarEqualGm = new GenericInstanceMethod(WeaverTypes.syncVarEqualReference); - syncVarEqualGm.GenericArguments.Add(fd.FieldType); - worker.Append(worker.Create(OpCodes.Call, syncVarEqualGm)); - } - - worker.Append(worker.Create(OpCodes.Brtrue, endOfMethod)); - - // T oldValue = value; - // TODO for GO/NI we need to backup the netId don't we? - VariableDefinition oldValue = new VariableDefinition(fd.FieldType); - set.Body.Variables.Add(oldValue); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldfld, fd)); - worker.Append(worker.Create(OpCodes.Stloc, oldValue)); - - // this - worker.Append(worker.Create(OpCodes.Ldarg_0)); - - // new value to set - worker.Append(worker.Create(OpCodes.Ldarg_1)); - - // reference to field to set - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldflda, fd)); - - // dirty bit - // 8 byte integer aka long - worker.Append(worker.Create(OpCodes.Ldc_I8, dirtyBit)); - - if (fd.FieldType.FullName == WeaverTypes.gameObjectType.FullName) - { - // reference to netId Field to set - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldflda, netFieldId)); - - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.setSyncVarGameObjectReference)); - } - else if (fd.FieldType.FullName == WeaverTypes.NetworkIdentityType.FullName) - { - // reference to netId Field to set - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldflda, netFieldId)); - - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.setSyncVarNetworkIdentityReference)); - } - else - { - // make generic version of SetSyncVar with field type - GenericInstanceMethod gm = new GenericInstanceMethod(WeaverTypes.setSyncVarReference); - gm.GenericArguments.Add(fd.FieldType); - - // invoke SetSyncVar - worker.Append(worker.Create(OpCodes.Call, gm)); - } - - MethodDefinition hookMethod = GetHookMethod(td, fd); - - if (hookMethod != null) - { - //if (NetworkServer.localClientActive && !getSyncVarHookGuard(dirtyBit)) - Instruction label = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.NetworkServerGetLocalClientActive)); - worker.Append(worker.Create(OpCodes.Brfalse, label)); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldc_I8, dirtyBit)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.getSyncVarHookGuard)); - worker.Append(worker.Create(OpCodes.Brtrue, label)); - - // setSyncVarHookGuard(dirtyBit, true); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldc_I8, dirtyBit)); - worker.Append(worker.Create(OpCodes.Ldc_I4_1)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.setSyncVarHookGuard)); - - // call hook (oldValue, newValue) - // Generates: OnValueChanged(oldValue, value); - WriteCallHookMethodUsingArgument(worker, hookMethod, oldValue); - - // setSyncVarHookGuard(dirtyBit, false); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldc_I8, dirtyBit)); - worker.Append(worker.Create(OpCodes.Ldc_I4_0)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.setSyncVarHookGuard)); - - worker.Append(label); - } - - worker.Append(endOfMethod); - - worker.Append(worker.Create(OpCodes.Ret)); - - set.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.In, fd.FieldType)); - set.SemanticsAttributes = MethodSemanticsAttributes.Setter; - - return set; - } - - public static void ProcessSyncVar(TypeDefinition td, FieldDefinition fd, Dictionary syncVarNetIds, long dirtyBit) - { - string originalName = fd.Name; - Weaver.DLog(td, "Sync Var " + fd.Name + " " + fd.FieldType + " " + WeaverTypes.gameObjectType); - - // GameObject/NetworkIdentity SyncVars have a new field for netId - FieldDefinition netIdField = null; - if (fd.FieldType.FullName == WeaverTypes.gameObjectType.FullName || - fd.FieldType.FullName == WeaverTypes.NetworkIdentityType.FullName) - { - netIdField = new FieldDefinition("___" + fd.Name + "NetId", - FieldAttributes.Private, - WeaverTypes.uint32Type); - - syncVarNetIds[fd] = netIdField; - } - - MethodDefinition get = ProcessSyncVarGet(fd, originalName, netIdField); - MethodDefinition set = ProcessSyncVarSet(td, fd, originalName, dirtyBit, netIdField); - - //NOTE: is property even needed? Could just use a setter function? - //create the property - PropertyDefinition propertyDefinition = new PropertyDefinition("Network" + originalName, PropertyAttributes.None, fd.FieldType) - { - GetMethod = get, - SetMethod = set - }; - - //add the methods and property to the type. - td.Methods.Add(get); - td.Methods.Add(set); - td.Properties.Add(propertyDefinition); - Weaver.WeaveLists.replacementSetterProperties[fd] = set; - - // replace getter field if GameObject/NetworkIdentity so it uses - // netId instead - // -> only for GameObjects, otherwise an int syncvar's getter would - // end up in recursion. - if (fd.FieldType.FullName == WeaverTypes.gameObjectType.FullName || - fd.FieldType.FullName == WeaverTypes.NetworkIdentityType.FullName) - { - Weaver.WeaveLists.replacementGetterProperties[fd] = get; - } - } - - public static (List syncVars, Dictionary syncVarNetIds) ProcessSyncVars(TypeDefinition td) - { - List syncVars = new List(); - Dictionary syncVarNetIds = new Dictionary(); - - // the mapping of dirtybits to sync-vars is implicit in the order of the fields here. this order is recorded in m_replacementProperties. - // start assigning syncvars at the place the base class stopped, if any - int dirtyBitCounter = Weaver.GetSyncVarStart(td.BaseType.FullName); - - // find syncvars - foreach (FieldDefinition fd in td.Fields) - { - if (fd.HasCustomAttribute(WeaverTypes.SyncVarType)) - { - if ((fd.Attributes & FieldAttributes.Static) != 0) - { - Weaver.Error($"{fd.Name} cannot be static", fd); - continue; - } - - if (fd.FieldType.IsArray) - { - Weaver.Error($"{fd.Name} has invalid type. Use SyncLists instead of arrays", fd); - continue; - } - - if (SyncObjectInitializer.ImplementsSyncObject(fd.FieldType)) - { - Weaver.Warning($"{fd.Name} has [SyncVar] attribute. SyncLists should not be marked with SyncVar", fd); - } - else - { - syncVars.Add(fd); - - ProcessSyncVar(td, fd, syncVarNetIds, 1L << dirtyBitCounter); - dirtyBitCounter += 1; - - if (dirtyBitCounter == SyncVarLimit) - { - Weaver.Error($"{td.Name} has too many SyncVars. Consider refactoring your class into multiple components", td); - continue; - } - } - } - } - - // add all the new SyncVar __netId fields - foreach (FieldDefinition fd in syncVarNetIds.Values) - { - td.Fields.Add(fd); - } - Weaver.SetNumSyncVars(td.FullName, syncVars.Count); - - return (syncVars, syncVarNetIds); - } - - public static void WriteCallHookMethodUsingArgument(ILProcessor worker, MethodDefinition hookMethod, VariableDefinition oldValue) - { - _WriteCallHookMethod(worker, hookMethod, oldValue, null); - } - - public static void WriteCallHookMethodUsingField(ILProcessor worker, MethodDefinition hookMethod, VariableDefinition oldValue, FieldDefinition newValue) - { - if (newValue == null) - { - Weaver.Error("NewValue field was null when writing SyncVar hook"); - } - - _WriteCallHookMethod(worker, hookMethod, oldValue, newValue); - } - - static void _WriteCallHookMethod(ILProcessor worker, MethodDefinition hookMethod, VariableDefinition oldValue, FieldDefinition newValue) - { - WriteStartFunctionCall(); - - // write args - WriteOldValue(); - WriteNewValue(); - - WriteEndFunctionCall(); - - - // *** Local functions used to write OpCodes *** - // Local functions have access to function variables, no need to pass in args - - void WriteOldValue() - { - worker.Append(worker.Create(OpCodes.Ldloc, oldValue)); - } - - void WriteNewValue() - { - // write arg1 or this.field - if (newValue == null) - { - worker.Append(worker.Create(OpCodes.Ldarg_1)); - } - else - { - // this. - worker.Append(worker.Create(OpCodes.Ldarg_0)); - // syncvar.get - worker.Append(worker.Create(OpCodes.Ldfld, newValue)); - } - } - - // Writes this before method if it is not static - void WriteStartFunctionCall() - { - // dont add this (Ldarg_0) if method is static - if (!hookMethod.IsStatic) - { - // this before method call - // eg this.onValueChanged - worker.Append(worker.Create(OpCodes.Ldarg_0)); - } - } - - // Calls method - void WriteEndFunctionCall() - { - // only use Callvirt when not static - OpCode opcode = hookMethod.IsStatic ? OpCodes.Call : OpCodes.Callvirt; - worker.Append(worker.Create(opcode, hookMethod)); - } - } - } -} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs.meta deleted file mode 100644 index 982f7680e4..0000000000 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f52c39bddd95d42b88f9cd554dfd9198 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs index 7c757cd6ab..8d56040a62 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs @@ -3,51 +3,75 @@ namespace Mirror.Weaver { - /// - /// Processes [TargetRpc] methods in NetworkBehaviour - /// + // Processes [TargetRpc] methods in NetworkBehaviour public static class TargetRpcProcessor { // helper functions to check if the method has a NetworkConnection parameter public static bool HasNetworkConnectionParameter(MethodDefinition md) { - return md.Parameters.Count > 0 && - md.Parameters[0].ParameterType.FullName == WeaverTypes.NetworkConnectionType.FullName; + if (md.Parameters.Count > 0) + { + // we need to allow both NetworkConnection, and inheriting types. + // NetworkBehaviour.SendTargetRpc takes a NetworkConnection parameter. + // fixes https://github.com/vis2k/Mirror/issues/3290 + TypeReference type = md.Parameters[0].ParameterType; + return type.Is() || + type.IsDerivedFrom(); + } + return false; } - public static MethodDefinition ProcessTargetRpcInvoke(TypeDefinition td, MethodDefinition md, MethodDefinition rpcCallFunc) + public static MethodDefinition ProcessTargetRpcInvoke(WeaverTypes weaverTypes, Readers readers, Logger Log, TypeDefinition td, MethodDefinition md, MethodDefinition rpcCallFunc, ref bool WeavingFailed) { - MethodDefinition rpc = new MethodDefinition(Weaver.InvokeRpcPrefix + md.Name, MethodAttributes.Family | + string trgName = Weaver.GenerateMethodName(RemoteCalls.RemoteProcedureCalls.InvokeRpcPrefix, md); + + MethodDefinition rpc = new MethodDefinition(trgName, MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig, - WeaverTypes.voidType); + weaverTypes.Import(typeof(void))); ILProcessor worker = rpc.Body.GetILProcessor(); Instruction label = worker.Create(OpCodes.Nop); - NetworkBehaviourProcessor.WriteClientActiveCheck(worker, md.Name, label, "TargetRPC"); + NetworkBehaviourProcessor.WriteClientActiveCheck(worker, weaverTypes, md.Name, label, "TargetRPC"); // setup for reader - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Castclass, td)); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Castclass, td); // NetworkConnection parameter is optional if (HasNetworkConnectionParameter(md)) { - // if call has NetworkConnection write clients connection as first arg - //ClientScene.readyconnection - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.ReadyConnectionReference)); + // TargetRpcs are sent from server to client. + // on server, we currently support two types: + // TargetRpc(NetworkConnection) + // TargetRpc(NetworkConnectionToClient) + // however, it's always a connection to client. + // in the future, only NetworkConnectionToClient will be supported. + // explicit typing helps catch issues at compile time. + // + // on client, InvokeTargetRpc calls the original code. + // we need to fill in the NetworkConnection parameter. + // NetworkClient.connection is always a connection to server. + // + // we used to pass NetworkClient.connection as the TargetRpc parameter. + // which caused: https://github.com/MirrorNetworking/Mirror/issues/3455 + // when the parameter is defined as a NetworkConnectionToClient. + // + // a client's connection never fits into a NetworkConnectionToClient. + // we need to always pass null here. + worker.Emit(OpCodes.Ldnull); } // process reader parameters and skip first one if first one is NetworkConnection - if (!NetworkBehaviourProcessor.ReadArguments(md, worker, RemoteCallType.TargetRpc)) + if (!NetworkBehaviourProcessor.ReadArguments(md, readers, Log, worker, RemoteCallType.TargetRpc, ref WeavingFailed)) return null; // invoke actual command function - worker.Append(worker.Create(OpCodes.Callvirt, rpcCallFunc)); - worker.Append(worker.Create(OpCodes.Ret)); + worker.Emit(OpCodes.Callvirt, rpcCallFunc); + worker.Emit(OpCodes.Ret); - NetworkBehaviourProcessor.AddInvokeParameters(rpc.Parameters); + NetworkBehaviourProcessor.AddInvokeParameters(weaverTypes, rpc.Parameters); td.Methods.Add(rpc); return rpc; } @@ -85,48 +109,49 @@ and replaces the body of the original method with the send message code. correctly in dependent assemblies */ - public static MethodDefinition ProcessTargetRpcCall(TypeDefinition td, MethodDefinition md, CustomAttribute targetRpcAttr) + public static MethodDefinition ProcessTargetRpcCall(WeaverTypes weaverTypes, Writers writers, Logger Log, TypeDefinition td, MethodDefinition md, CustomAttribute targetRpcAttr, ref bool WeavingFailed) { - MethodDefinition rpc = MethodProcessor.SubstituteMethod(td, md); + MethodDefinition rpc = MethodProcessor.SubstituteMethod(Log, td, md, ref WeavingFailed); ILProcessor worker = md.Body.GetILProcessor(); - NetworkBehaviourProcessor.WriteSetupLocals(worker); + NetworkBehaviourProcessor.WriteSetupLocals(worker, weaverTypes); - NetworkBehaviourProcessor.WriteCreateWriter(worker); + NetworkBehaviourProcessor.WriteGetWriter(worker, weaverTypes); // write all the arguments that the user passed to the TargetRpc call // (skip first one if first one is NetworkConnection) - if (!NetworkBehaviourProcessor.WriteArguments(worker, md, RemoteCallType.TargetRpc)) + if (!NetworkBehaviourProcessor.WriteArguments(worker, writers, Log, md, RemoteCallType.TargetRpc, ref WeavingFailed)) return null; - string rpcName = md.Name; - // invoke SendInternal and return // this - worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Emit(OpCodes.Ldarg_0); if (HasNetworkConnectionParameter(md)) { // connection - worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Emit(OpCodes.Ldarg_1); } else { // null - worker.Append(worker.Create(OpCodes.Ldnull)); + worker.Emit(OpCodes.Ldnull); } - worker.Append(worker.Create(OpCodes.Ldtoken, td)); - // invokerClass - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.getTypeFromHandleReference)); - worker.Append(worker.Create(OpCodes.Ldstr, rpcName)); + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + worker.Emit(OpCodes.Ldstr, md.FullName); + // pass the function hash so we don't have to compute it at runtime + // otherwise each GetStableHash call requires O(N) complexity. + // noticeable for long function names: + // https://github.com/MirrorNetworking/Mirror/issues/3375 + worker.Emit(OpCodes.Ldc_I4, md.FullName.GetStableHashCode()); // writer - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Ldc_I4, targetRpcAttr.GetField("channel", 0))); - worker.Append(worker.Create(OpCodes.Callvirt, WeaverTypes.sendTargetRpcInternal)); + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Ldc_I4, targetRpcAttr.GetField("channel", 0)); + worker.Emit(OpCodes.Callvirt, weaverTypes.sendTargetRpcInternal); - NetworkBehaviourProcessor.WriteRecycleWriter(worker); + NetworkBehaviourProcessor.WriteReturnWriter(worker, weaverTypes); - worker.Append(worker.Create(OpCodes.Ret)); + worker.Emit(OpCodes.Ret); return rpc; } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta index 0ff7cc552e..037f562c61 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Readers.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Readers.cs index b898ab08c1..33941d9f92 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Readers.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Readers.cs @@ -1,245 +1,219 @@ +using System; using System.Collections.Generic; using Mono.CecilX; using Mono.CecilX.Cil; +// to use Mono.CecilX.Rocks here, we need to 'override references' in the +// Unity.Mirror.CodeGen assembly definition file in the Editor, and add CecilX.Rocks. +// otherwise we get an unknown import exception. using Mono.CecilX.Rocks; namespace Mirror.Weaver { - public static class Readers + // not static, because ILPostProcessor is multithreaded + public class Readers { - const int MaxRecursionCount = 128; - static Dictionary readFuncs; + // Readers are only for this assembly. + // can't be used from another assembly, otherwise we will get: + // "System.ArgumentException: Member ... is declared in another module and needs to be imported" + AssemblyDefinition assembly; + WeaverTypes weaverTypes; + TypeDefinition GeneratedCodeClass; + Logger Log; + + Dictionary readFuncs = + new Dictionary(new TypeReferenceComparer()); + + public Readers(AssemblyDefinition assembly, WeaverTypes weaverTypes, TypeDefinition GeneratedCodeClass, Logger Log) + { + this.assembly = assembly; + this.weaverTypes = weaverTypes; + this.GeneratedCodeClass = GeneratedCodeClass; + this.Log = Log; + } - public static void Init() + internal void Register(TypeReference dataType, MethodReference methodReference) { - readFuncs = new Dictionary(); + if (readFuncs.ContainsKey(dataType)) + { + // TODO enable this again later. + // Reader has some obsolete functions that were renamed. + // Don't want weaver warnings for all of them. + //Log.Warning($"Registering a Read method for {dataType.FullName} when one already exists", methodReference); + } + + // we need to import type when we Initialize Readers so import here in case it is used anywhere else + TypeReference imported = assembly.MainModule.ImportReference(dataType); + readFuncs[imported] = methodReference; } - internal static void Register(TypeReference dataType, MethodReference methodReference) + void RegisterReadFunc(TypeReference typeReference, MethodDefinition newReaderFunc) { - readFuncs[dataType.FullName] = methodReference; + Register(typeReference, newReaderFunc); + GeneratedCodeClass.Methods.Add(newReaderFunc); } - public static MethodReference GetReadFunc(TypeReference variableReference, int recursionCount = 0) + // Finds existing reader for type, if non exists trys to create one + public MethodReference GetReadFunc(TypeReference variable, ref bool WeavingFailed) { - if (readFuncs.TryGetValue(variableReference.FullName, out MethodReference foundFunc)) - { + if (readFuncs.TryGetValue(variable, out MethodReference foundFunc)) return foundFunc; - } - MethodDefinition newReaderFunc; + TypeReference importedVariable = assembly.MainModule.ImportReference(variable); + return GenerateReader(importedVariable, ref WeavingFailed); + } - // Arrays are special, if we resolve them, we get teh element type, + MethodReference GenerateReader(TypeReference variableReference, ref bool WeavingFailed) + { + // Arrays are special, if we resolve them, we get the element type, // so the following ifs might choke on it for scriptable objects // or other objects that require a custom serializer // thus check if it is an array and skip all the checks. if (variableReference.IsArray) { - newReaderFunc = GenerateArrayReadFunc(variableReference, recursionCount); - if (newReaderFunc != null) + if (variableReference.IsMultidimensionalArray()) { - RegisterReadFunc(variableReference.FullName, newReaderFunc); + Log.Error($"{variableReference.Name} is an unsupported type. Multidimensional arrays are not supported", variableReference); + WeavingFailed = true; + return null; } - return newReaderFunc; + + return GenerateReadCollection(variableReference, variableReference.GetElementType(), nameof(NetworkReaderExtensions.ReadArray), ref WeavingFailed); } TypeDefinition variableDefinition = variableReference.Resolve(); + + // check if the type is completely invalid if (variableDefinition == null) { - Weaver.Error($"{variableReference.Name} is not a supported type", variableReference); + Log.Error($"{variableReference.Name} is not a supported type", variableReference); + WeavingFailed = true; return null; } - if (variableDefinition.IsDerivedFrom(WeaverTypes.ComponentType)) + else if (variableReference.IsByReference) { - Weaver.Error($"Cannot generate reader for component type {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + // error?? + Log.Error($"Cannot pass type {variableReference.Name} by reference", variableReference); + WeavingFailed = true; return null; } - if (variableReference.FullName == WeaverTypes.ObjectType.FullName) + + // use existing func for known types + if (variableDefinition.IsEnum) { - Weaver.Error($"Cannot generate reader for {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); - return null; + return GenerateEnumReadFunc(variableReference, ref WeavingFailed); } - if (variableReference.FullName == WeaverTypes.ScriptableObjectType.FullName) + else if (variableDefinition.Is(typeof(ArraySegment<>))) { - Weaver.Error($"Cannot generate reader for {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); - return null; + return GenerateArraySegmentReadFunc(variableReference, ref WeavingFailed); } - if (variableReference.IsByReference) + else if (variableDefinition.Is(typeof(List<>))) { - // error?? - Weaver.Error($"Cannot pass type {variableReference.Name} by reference", variableReference); - return null; + GenericInstanceType genericInstance = (GenericInstanceType)variableReference; + TypeReference elementType = genericInstance.GenericArguments[0]; + + return GenerateReadCollection(variableReference, elementType, nameof(NetworkReaderExtensions.ReadList), ref WeavingFailed); } - if (variableDefinition.HasGenericParameters && !variableDefinition.IsArraySegment() && !variableDefinition.IsList()) + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + else if (variableReference.IsDerivedFrom() || variableReference.Is()) { - Weaver.Error($"Cannot generate reader for generic variable {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); - return null; + return GetNetworkBehaviourReader(variableReference); } - if (variableDefinition.IsInterface) + + // check if reader generation is applicable on this type + if (variableDefinition.IsDerivedFrom()) { - Weaver.Error($"Cannot generate reader for interface {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + Log.Error($"Cannot generate reader for component type {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; return null; } - if (variableDefinition.IsAbstract) + if (variableReference.Is()) { - Weaver.Error($"Cannot generate reader for abstract class {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + Log.Error($"Cannot generate reader for {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; return null; } - - if (variableDefinition.IsEnum) - { - return GetReadFunc(variableDefinition.GetEnumUnderlyingType(), recursionCount); - } - else if (variableDefinition.IsArraySegment()) + if (variableReference.Is()) { - newReaderFunc = GenerateArraySegmentReadFunc(variableReference, recursionCount); + Log.Error($"Cannot generate reader for {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; + return null; } - else if (variableDefinition.IsList()) + if (variableDefinition.HasGenericParameters) { - newReaderFunc = GenerateListReadFunc(variableReference, recursionCount); + Log.Error($"Cannot generate reader for generic variable {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; + return null; } - else + if (variableDefinition.IsInterface) { - newReaderFunc = GenerateClassOrStructReadFunction(variableReference, recursionCount); + Log.Error($"Cannot generate reader for interface {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; + return null; } - - if (newReaderFunc == null) + if (variableDefinition.IsAbstract) { - Weaver.Error($"{variableReference.Name} is not a supported type", variableReference); + Log.Error($"Cannot generate reader for abstract class {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; return null; } - RegisterReadFunc(variableReference.FullName, newReaderFunc); - return newReaderFunc; - } - - static void RegisterReadFunc(string name, MethodDefinition newReaderFunc) - { - readFuncs[name] = newReaderFunc; - Weaver.WeaveLists.generatedReadFunctions.Add(newReaderFunc); - Weaver.ConfirmGeneratedCodeClass(); - Weaver.WeaveLists.generateContainerClass.Methods.Add(newReaderFunc); + return GenerateClassOrStructReadFunction(variableReference, ref WeavingFailed); } - static MethodDefinition GenerateArrayReadFunc(TypeReference variable, int recursionCount) + MethodReference GetNetworkBehaviourReader(TypeReference variableReference) { - if (!variable.IsArrayType()) - { - Weaver.Error($"{variable.Name} is an unsupported type. Jagged and multidimensional arrays are not supported", variable); - return null; - } + // uses generic ReadNetworkBehaviour rather than having weaver create one for each NB + MethodReference generic = weaverTypes.readNetworkBehaviourGeneric; - TypeReference elementType = variable.GetElementType(); - MethodReference elementReadFunc = GetReadFunc(elementType, recursionCount + 1); - if (elementReadFunc == null) - { - Weaver.Error($"Cannot generate reader for Array because element {elementType.Name} does not have a reader. Use a supported type or provide a custom reader", variable); - return null; - } + MethodReference readFunc = generic.MakeGeneric(assembly.MainModule, variableReference); - string functionName = "_ReadArray" + variable.GetElementType().Name + "_"; - if (variable.DeclaringType != null) - { - functionName += variable.DeclaringType.Name; - } - else - { - functionName += "None"; - } + // register function so it is added to Reader + // use Register instead of RegisterWriteFunc because this is not a generated function + Register(variableReference, readFunc); - // create new reader for this type - MethodDefinition readerFunc = new MethodDefinition(functionName, - MethodAttributes.Public | - MethodAttributes.Static | - MethodAttributes.HideBySig, - variable); - - readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkReaderType))); + return readFunc; + } - readerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - readerFunc.Body.Variables.Add(new VariableDefinition(variable)); - readerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - readerFunc.Body.InitLocals = true; + MethodDefinition GenerateEnumReadFunc(TypeReference variable, ref bool WeavingFailed) + { + MethodDefinition readerFunc = GenerateReaderFunction(variable); ILProcessor worker = readerFunc.Body.GetILProcessor(); - // int length = reader.ReadPackedInt32(); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Call, GetReadFunc(WeaverTypes.int32Type))); - worker.Append(worker.Create(OpCodes.Stloc_0)); + worker.Emit(OpCodes.Ldarg_0); - // if (length < 0) { - // return null - // } - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Ldc_I4_0)); - Instruction labelEmptyArray = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Bge, labelEmptyArray)); - // return null - worker.Append(worker.Create(OpCodes.Ldnull)); - worker.Append(worker.Create(OpCodes.Ret)); - worker.Append(labelEmptyArray); + TypeReference underlyingType = variable.Resolve().GetEnumUnderlyingType(); + MethodReference underlyingFunc = GetReadFunc(underlyingType, ref WeavingFailed); - // T value = new T[length]; - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Newarr, variable.GetElementType())); - worker.Append(worker.Create(OpCodes.Stloc_1)); - - // for (int i=0; i< length ; i++) { - worker.Append(worker.Create(OpCodes.Ldc_I4_0)); - worker.Append(worker.Create(OpCodes.Stloc_2)); - Instruction labelHead = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Br, labelHead)); - - // loop body - Instruction labelBody = worker.Create(OpCodes.Nop); - worker.Append(labelBody); - // value[i] = reader.ReadT(); - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldloc_2)); - worker.Append(worker.Create(OpCodes.Ldelema, variable.GetElementType())); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Call, elementReadFunc)); - worker.Append(worker.Create(OpCodes.Stobj, variable.GetElementType())); - - worker.Append(worker.Create(OpCodes.Ldloc_2)); - worker.Append(worker.Create(OpCodes.Ldc_I4_1)); - worker.Append(worker.Create(OpCodes.Add)); - worker.Append(worker.Create(OpCodes.Stloc_2)); - - // loop while check - worker.Append(labelHead); - worker.Append(worker.Create(OpCodes.Ldloc_2)); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Blt, labelBody)); - - // return value; - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ret)); + worker.Emit(OpCodes.Call, underlyingFunc); + worker.Emit(OpCodes.Ret); return readerFunc; } - static MethodDefinition GenerateArraySegmentReadFunc(TypeReference variable, int recursionCount) + MethodDefinition GenerateArraySegmentReadFunc(TypeReference variable, ref bool WeavingFailed) { GenericInstanceType genericInstance = (GenericInstanceType)variable; TypeReference elementType = genericInstance.GenericArguments[0]; - MethodReference elementReadFunc = GetReadFunc(elementType, recursionCount + 1); - if (elementReadFunc == null) - { - Weaver.Error($"Cannot generate reader for ArraySegment because element {elementType.Name} does not have a reader. Use a supported type or provide a custom reader", variable); - return null; - } + MethodDefinition readerFunc = GenerateReaderFunction(variable); - string functionName = "_ReadArraySegment_" + elementType.Name + "_"; - if (variable.DeclaringType != null) - { - functionName += variable.DeclaringType.Name; - } - else - { - functionName += "None"; - } + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + // $array = reader.Read<[T]>() + ArrayType arrayType = elementType.MakeArrayType(); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Call, GetReadFunc(arrayType, ref WeavingFailed)); + + // return new ArraySegment($array); + worker.Emit(OpCodes.Newobj, weaverTypes.ArraySegmentConstructorReference.MakeHostInstanceGeneric(assembly.MainModule, genericInstance)); + worker.Emit(OpCodes.Ret); + return readerFunc; + } + + MethodDefinition GenerateReaderFunction(TypeReference variable) + { + string functionName = $"_Read_{variable.FullName}"; // create new reader for this type MethodDefinition readerFunc = new MethodDefinition(functionName, @@ -248,281 +222,164 @@ static MethodDefinition GenerateArraySegmentReadFunc(TypeReference variable, int MethodAttributes.HideBySig, variable); - readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkReaderType))); - - // int lengh - readerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - // T[] array - readerFunc.Body.Variables.Add(new VariableDefinition(elementType.MakeArrayType())); - // int i; - readerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); + readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, weaverTypes.Import())); readerFunc.Body.InitLocals = true; + RegisterReadFunc(variable, readerFunc); - ILProcessor worker = readerFunc.Body.GetILProcessor(); - - // int length = reader.ReadPackedInt32(); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Call, GetReadFunc(WeaverTypes.int32Type))); - worker.Append(worker.Create(OpCodes.Stloc_0)); - - // T[] array = new int[length] - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Newarr, elementType)); - worker.Append(worker.Create(OpCodes.Stloc_1)); - - // loop through array and deserialize each element - // generates code like this - // for (int i=0; i< length ; i++) - // { - // value[i] = reader.ReadXXX(); - // } - worker.Append(worker.Create(OpCodes.Ldc_I4_0)); - worker.Append(worker.Create(OpCodes.Stloc_2)); - Instruction labelHead = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Br, labelHead)); - - // loop body - Instruction labelBody = worker.Create(OpCodes.Nop); - worker.Append(labelBody); - // value[i] = reader.ReadT(); - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldloc_2)); - worker.Append(worker.Create(OpCodes.Ldelema, elementType)); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Call, elementReadFunc)); - worker.Append(worker.Create(OpCodes.Stobj, elementType)); - - worker.Append(worker.Create(OpCodes.Ldloc_2)); - worker.Append(worker.Create(OpCodes.Ldc_I4_1)); - worker.Append(worker.Create(OpCodes.Add)); - worker.Append(worker.Create(OpCodes.Stloc_2)); - - // loop while check - worker.Append(labelHead); - worker.Append(worker.Create(OpCodes.Ldloc_2)); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Blt, labelBody)); - - // return new ArraySegment(array); - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Newobj, WeaverTypes.ArraySegmentConstructorReference.MakeHostInstanceGeneric(genericInstance))); - worker.Append(worker.Create(OpCodes.Ret)); return readerFunc; } - static MethodDefinition GenerateListReadFunc(TypeReference variable, int recursionCount) + MethodDefinition GenerateReadCollection(TypeReference variable, TypeReference elementType, string readerFunction, ref bool WeavingFailed) { - GenericInstanceType genericInstance = (GenericInstanceType)variable; - TypeReference elementType = genericInstance.GenericArguments[0]; + MethodDefinition readerFunc = GenerateReaderFunction(variable); + // generate readers for the element + GetReadFunc(elementType, ref WeavingFailed); - MethodReference elementReadFunc = GetReadFunc(elementType, recursionCount + 1); - if (elementReadFunc == null) - { - Weaver.Error($"Cannot generate reader for List because element {elementType.Name} does not have a reader. Use a supported type or provide a custom reader", variable); - return null; - } + ModuleDefinition module = assembly.MainModule; + TypeReference readerExtensions = module.ImportReference(typeof(NetworkReaderExtensions)); + MethodReference listReader = Resolvers.ResolveMethod(readerExtensions, assembly, Log, readerFunction, ref WeavingFailed); - string functionName = "_ReadList_" + elementType.Name + "_"; - if (variable.DeclaringType != null) - { - functionName += variable.DeclaringType.Name; - } - else - { - functionName += "None"; - } + GenericInstanceMethod methodRef = new GenericInstanceMethod(listReader); + methodRef.GenericArguments.Add(elementType); - // create new reader for this type - MethodDefinition readerFunc = new MethodDefinition(functionName, - MethodAttributes.Public | - MethodAttributes.Static | - MethodAttributes.HideBySig, - variable); - - readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkReaderType))); - - readerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - readerFunc.Body.Variables.Add(new VariableDefinition(variable)); - readerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - readerFunc.Body.InitLocals = true; + // generates + // return reader.ReadList(); ILProcessor worker = readerFunc.Body.GetILProcessor(); + worker.Emit(OpCodes.Ldarg_0); // reader + worker.Emit(OpCodes.Call, methodRef); // Read - // int count = reader.ReadPackedInt32(); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Call, GetReadFunc(WeaverTypes.int32Type))); - worker.Append(worker.Create(OpCodes.Stloc_0)); + worker.Emit(OpCodes.Ret); - // -1 is null list, so if count is less than 0 return null - // if (count < 0) { - // return null - // } - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Ldc_I4_0)); - Instruction labelEmptyArray = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Bge, labelEmptyArray)); - // return null - worker.Append(worker.Create(OpCodes.Ldnull)); - worker.Append(worker.Create(OpCodes.Ret)); - worker.Append(labelEmptyArray); - - // List list = new List(); - worker.Append(worker.Create(OpCodes.Newobj, WeaverTypes.ListConstructorReference.MakeHostInstanceGeneric(genericInstance))); - worker.Append(worker.Create(OpCodes.Stloc_1)); - - // loop through array and deserialize each element - // generates code like this - // for (int i=0; i< length ; i++) - // { - // list[i] = reader.ReadXXX(); - // } - worker.Append(worker.Create(OpCodes.Ldc_I4_0)); - worker.Append(worker.Create(OpCodes.Stloc_2)); - Instruction labelHead = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Br, labelHead)); - - // loop body - Instruction labelBody = worker.Create(OpCodes.Nop); - worker.Append(labelBody); - - MethodReference addItem = WeaverTypes.ListAddReference.MakeHostInstanceGeneric(genericInstance); - - // list.Add(reader.ReadT()); - worker.Append(worker.Create(OpCodes.Ldloc_1)); // list - worker.Append(worker.Create(OpCodes.Ldarg_0)); // reader - worker.Append(worker.Create(OpCodes.Call, elementReadFunc)); // Read - worker.Append(worker.Create(OpCodes.Call, addItem)); // set_Item - - // end for loop - - // for loop i++ - worker.Append(worker.Create(OpCodes.Ldloc_2)); - worker.Append(worker.Create(OpCodes.Ldc_I4_1)); - worker.Append(worker.Create(OpCodes.Add)); - worker.Append(worker.Create(OpCodes.Stloc_2)); - - // loop while check - worker.Append(labelHead); - // for loop i < count - worker.Append(worker.Create(OpCodes.Ldloc_2)); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Blt, labelBody)); - - // return value; - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ret)); return readerFunc; } - - static MethodDefinition GenerateClassOrStructReadFunction(TypeReference variable, int recursionCount) + MethodDefinition GenerateClassOrStructReadFunction(TypeReference variable, ref bool WeavingFailed) { - if (recursionCount > MaxRecursionCount) - { - Weaver.Error($"{variable.Name} can't be deserialized because it references itself", variable); - return null; - } - - string functionName = "_Read" + variable.Name + "_"; - if (variable.DeclaringType != null) - { - functionName += variable.DeclaringType.Name; - } - else - { - functionName += "None"; - } - - // create new reader for this type - MethodDefinition readerFunc = new MethodDefinition(functionName, - MethodAttributes.Public | - MethodAttributes.Static | - MethodAttributes.HideBySig, - variable); + MethodDefinition readerFunc = GenerateReaderFunction(variable); // create local for return value readerFunc.Body.Variables.Add(new VariableDefinition(variable)); - readerFunc.Body.InitLocals = true; - - readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkReaderType))); ILProcessor worker = readerFunc.Body.GetILProcessor(); TypeDefinition td = variable.Resolve(); - CreateNew(variable, worker, td); - ReadAllFields(variable, recursionCount, worker); + if (!td.IsValueType) + GenerateNullCheck(worker, ref WeavingFailed); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Ret)); + CreateNew(variable, worker, td, ref WeavingFailed); + ReadAllFields(variable, worker, ref WeavingFailed); + + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Ret); return readerFunc; } + void GenerateNullCheck(ILProcessor worker, ref bool WeavingFailed) + { + // if (!reader.ReadBoolean()) { + // return null; + // } + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Call, GetReadFunc(weaverTypes.Import(), ref WeavingFailed)); + + Instruction labelEmptyArray = worker.Create(OpCodes.Nop); + worker.Emit(OpCodes.Brtrue, labelEmptyArray); + // return null + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ret); + worker.Append(labelEmptyArray); + } + // Initialize the local variable with a new instance - static void CreateNew(TypeReference variable, ILProcessor worker, TypeDefinition td) + void CreateNew(TypeReference variable, ILProcessor worker, TypeDefinition td, ref bool WeavingFailed) { if (variable.IsValueType) { // structs are created with Initobj - worker.Append(worker.Create(OpCodes.Ldloca, 0)); - worker.Append(worker.Create(OpCodes.Initobj, variable)); + worker.Emit(OpCodes.Ldloca, 0); + worker.Emit(OpCodes.Initobj, variable); } - else if (td.IsDerivedFrom(WeaverTypes.ScriptableObjectType)) + else if (td.IsDerivedFrom()) { - GenericInstanceMethod genericInstanceMethod = new GenericInstanceMethod(WeaverTypes.ScriptableObjectCreateInstanceMethod); + GenericInstanceMethod genericInstanceMethod = new GenericInstanceMethod(weaverTypes.ScriptableObjectCreateInstanceMethod); genericInstanceMethod.GenericArguments.Add(variable); - worker.Append(worker.Create(OpCodes.Call, genericInstanceMethod)); - worker.Append(worker.Create(OpCodes.Stloc_0)); + worker.Emit(OpCodes.Call, genericInstanceMethod); + worker.Emit(OpCodes.Stloc_0); } else { // classes are created with their constructor - MethodDefinition ctor = Resolvers.ResolveDefaultPublicCtor(variable); if (ctor == null) { - Weaver.Error($"{variable.Name} can't be deserialized because it has no default constructor", variable); + Log.Error($"{variable.Name} can't be deserialized because it has no default constructor. Don't use {variable.Name} in [SyncVar]s, Rpcs, Cmds, etc.", variable); + WeavingFailed = true; return; } - MethodReference ctorRef = Weaver.CurrentAssembly.MainModule.ImportReference(ctor); + MethodReference ctorRef = assembly.MainModule.ImportReference(ctor); - worker.Append(worker.Create(OpCodes.Newobj, ctorRef)); - worker.Append(worker.Create(OpCodes.Stloc_0)); + worker.Emit(OpCodes.Newobj, ctorRef); + worker.Emit(OpCodes.Stloc_0); } } - static void ReadAllFields(TypeReference variable, int recursionCount, ILProcessor worker) + void ReadAllFields(TypeReference variable, ILProcessor worker, ref bool WeavingFailed) { - uint fields = 0; foreach (FieldDefinition field in variable.FindAllPublicFields()) { // mismatched ldloca/ldloc for struct/class combinations is invalid IL, which causes crash at runtime OpCode opcode = variable.IsValueType ? OpCodes.Ldloca : OpCodes.Ldloc; - worker.Append(worker.Create(opcode, 0)); - - MethodReference readFunc = GetReadFunc(field.FieldType, recursionCount + 1); + worker.Emit(opcode, 0); + MethodReference readFunc = GetReadFunc(field.FieldType, ref WeavingFailed); if (readFunc != null) { - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Call, readFunc)); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Call, readFunc); } else { - Weaver.Error($"{field.Name} has an unsupported type", field); + Log.Error($"{field.Name} has an unsupported type", field); + WeavingFailed = true; } - FieldReference fieldRef = Weaver.CurrentAssembly.MainModule.ImportReference(field); + FieldReference fieldRef = assembly.MainModule.ImportReference(field); - worker.Append(worker.Create(OpCodes.Stfld, fieldRef)); - fields++; + worker.Emit(OpCodes.Stfld, fieldRef); } + } + + // Save a delegate for each one of the readers into Reader.read + internal void InitializeReaders(ILProcessor worker) + { + ModuleDefinition module = assembly.MainModule; + + TypeReference genericReaderClassRef = module.ImportReference(typeof(Reader<>)); + + System.Reflection.FieldInfo fieldInfo = typeof(Reader<>).GetField(nameof(Reader.read)); + FieldReference fieldRef = module.ImportReference(fieldInfo); + TypeReference networkReaderRef = module.ImportReference(typeof(NetworkReader)); + TypeReference funcRef = module.ImportReference(typeof(Func<,>)); + MethodReference funcConstructorRef = module.ImportReference(typeof(Func<,>).GetConstructors()[0]); - if (fields == 0) + foreach (KeyValuePair kvp in readFuncs) { - Log.Warning($"{variable} has no public or non-static fields to deserialize"); + TypeReference targetType = kvp.Key; + MethodReference readFunc = kvp.Value; + + // create a Func delegate + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ldftn, readFunc); + GenericInstanceType funcGenericInstance = funcRef.MakeGenericInstanceType(networkReaderRef, targetType); + MethodReference funcConstructorInstance = funcConstructorRef.MakeHostInstanceGeneric(assembly.MainModule, funcGenericInstance); + worker.Emit(OpCodes.Newobj, funcConstructorInstance); + + // save it in Reader.read + GenericInstanceType genericInstance = genericReaderClassRef.MakeGenericInstanceType(targetType); + FieldReference specializedField = fieldRef.SpecializeField(assembly.MainModule, genericInstance); + worker.Emit(OpCodes.Stsfld, specializedField); } } - } - } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Readers.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Readers.cs.meta index 838ff590fa..11f5c52a71 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Readers.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Readers.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Readers.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Resolvers.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Resolvers.cs index 9bfbb3c8af..0af32caadf 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Resolvers.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Resolvers.cs @@ -10,51 +10,91 @@ namespace Mirror.Weaver { public static class Resolvers { - public static MethodReference ResolveMethod(TypeReference tr, AssemblyDefinition scriptDef, string name) + public static MethodReference ResolveMethod(TypeReference tr, AssemblyDefinition assembly, Logger Log, string name, ref bool WeavingFailed) { if (tr == null) { - Weaver.Error($"Cannot resolve method {name} without a class"); + Log.Error($"Cannot resolve method {name} without a class"); + WeavingFailed = true; return null; } - MethodReference method = ResolveMethod(tr, scriptDef, m => m.Name == name); + MethodReference method = ResolveMethod(tr, assembly, Log, m => m.Name == name, ref WeavingFailed); if (method == null) { - Weaver.Error($"Method not found with name {name} in type {tr.Name}", tr); + Log.Error($"Method not found with name {name} in type {tr.Name}", tr); + WeavingFailed = true; } return method; } - public static MethodReference ResolveMethod(TypeReference t, AssemblyDefinition scriptDef, System.Func predicate) + public static MethodReference ResolveMethod(TypeReference t, AssemblyDefinition assembly, Logger Log, System.Func predicate, ref bool WeavingFailed) { foreach (MethodDefinition methodRef in t.Resolve().Methods) { if (predicate(methodRef)) { - return scriptDef.MainModule.ImportReference(methodRef); + return assembly.MainModule.ImportReference(methodRef); } } - Weaver.Error($"Method not found in type {t.Name}", t); + Log.Error($"Method not found in type {t.Name}", t); + WeavingFailed = true; return null; } - public static MethodReference TryResolveMethodInParents(TypeReference tr, AssemblyDefinition scriptDef, string name) + public static FieldReference ResolveField(TypeReference tr, AssemblyDefinition assembly, Logger Log, string name, ref bool WeavingFailed) { if (tr == null) { + Log.Error($"Cannot resolve Field {name} without a class"); + WeavingFailed = true; return null; } - foreach (MethodDefinition methodRef in tr.Resolve().Methods) + FieldReference field = ResolveField(tr, assembly, Log, m => m.Name == name, ref WeavingFailed); + if (field == null) { - if (methodRef.Name == name) + Log.Error($"Field not found with name {name} in type {tr.Name}", tr); + WeavingFailed = true; + } + return field; + } + + public static FieldReference ResolveField(TypeReference t, AssemblyDefinition assembly, Logger Log, System.Func predicate, ref bool WeavingFailed) + { + foreach (FieldDefinition fieldRef in t.Resolve().Fields) + { + if (predicate(fieldRef)) + { + return assembly.MainModule.ImportReference(fieldRef); + } + } + + Log.Error($"Field not found in type {t.Name}", t); + WeavingFailed = true; + return null; + } + + public static MethodReference TryResolveMethodInParents(TypeReference tr, AssemblyDefinition assembly, string name) + { + if (tr == null) + { + return null; + } + foreach (MethodDefinition methodDef in tr.Resolve().Methods) + { + if (methodDef.Name == name) { - return scriptDef.MainModule.ImportReference(methodRef); + MethodReference methodRef = methodDef; + if (tr.IsGenericInstance) + { + methodRef = methodRef.MakeHostInstanceGeneric(tr.Module, (GenericInstanceType)tr); + } + return assembly.MainModule.ImportReference(methodRef); } } // Could not find the method in this class, try the parent - return TryResolveMethodInParents(tr.Resolve().BaseType, scriptDef, name); + return TryResolveMethodInParents(tr.Resolve().BaseType.ApplyGenericParameters(tr), assembly, name); } public static MethodDefinition ResolveDefaultPublicCtor(TypeReference variable) @@ -71,13 +111,13 @@ public static MethodDefinition ResolveDefaultPublicCtor(TypeReference variable) return null; } - public static MethodReference ResolveProperty(TypeReference tr, AssemblyDefinition scriptDef, string name) + public static MethodReference ResolveProperty(TypeReference tr, AssemblyDefinition assembly, string name) { foreach (PropertyDefinition pd in tr.Resolve().Properties) { if (pd.Name == name) { - return scriptDef.MainModule.ImportReference(pd.GetMethod); + return assembly.MainModule.ImportReference(pd.GetMethod); } } return null; diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Resolvers.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Resolvers.cs.meta index f4f66029f6..9c33042da5 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Resolvers.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Resolvers.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Resolvers.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/SyncVarAccessLists.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/SyncVarAccessLists.cs new file mode 100644 index 0000000000..fa7a6826af --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/SyncVarAccessLists.cs @@ -0,0 +1,32 @@ +// tracks SyncVar read/write access when processing NetworkBehaviour, +// to later be replaced by SyncVarAccessReplacer. +using System.Collections.Generic; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + // This data is flushed each time - if we are run multiple times in the same process/domain + public class SyncVarAccessLists + { + // setter functions that replace [SyncVar] member variable references. dict + public Dictionary replacementSetterProperties = + new Dictionary(); + + // getter functions that replace [SyncVar] member variable references. dict + public Dictionary replacementGetterProperties = + new Dictionary(); + + // amount of SyncVars per class. dict + // necessary for SyncVar dirty bits, where inheriting classes start + // their dirty bits at base class SyncVar amount. + public Dictionary numSyncVars = new Dictionary(); + + public int GetSyncVarStart(string className) => + numSyncVars.TryGetValue(className, out int value) ? value : 0; + + public void SetNumSyncVars(string className, int num) + { + numSyncVars[className] = num; + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/SyncVarAccessLists.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/SyncVarAccessLists.cs.meta new file mode 100644 index 0000000000..d8de5cc2cb --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/SyncVarAccessLists.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6905230c3c4c4e158760065a93380e83 +timeCreated: 1629348618 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/SyncVarAccessLists.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/TypeReferenceComparer.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/TypeReferenceComparer.cs new file mode 100644 index 0000000000..e3c31d5559 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/TypeReferenceComparer.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + // Compares TypeReference using FullName + public class TypeReferenceComparer : IEqualityComparer + { + public bool Equals(TypeReference x, TypeReference y) => + x.FullName == y.FullName; + + public int GetHashCode(TypeReference obj) => + obj.FullName.GetHashCode(); + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/TypeReferenceComparer.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/TypeReferenceComparer.cs.meta new file mode 100644 index 0000000000..89e3a67f71 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/TypeReferenceComparer.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 55eb9eb8794946f4da7ad39788c9920b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/TypeReferenceComparer.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef b/Assets/ImportedAssets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef new file mode 100644 index 0000000000..987382cf70 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef @@ -0,0 +1,21 @@ +{ + "name": "Unity.Mirror.CodeGen", + "rootNamespace": "", + "references": [ + "GUID:30817c1a0e6d646d99c048fc403f5979" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": true, + "precompiledReferences": [ + "Mono.CecilX.dll", + "Mono.CecilX.Rocks.dll" + ], + "autoReferenced": false, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef.meta new file mode 100644 index 0000000000..e2e602cd96 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 1d0b9d21c3ff546a4aa32399dfd33474 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Weaver.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Weaver.cs index 1393e6513d..3aef7b84c2 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Weaver.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Weaver.cs @@ -1,124 +1,80 @@ using System; using System.Collections.Generic; -using System.IO; +using System.Diagnostics; using Mono.CecilX; using Mono.CecilX.Cil; +using Mono.CecilX.Rocks; namespace Mirror.Weaver { - // This data is flushed each time - if we are run multiple times in the same process/domain - class WeaverLists + // not static, because ILPostProcessor is multithreaded + internal class Weaver { - // setter functions that replace [SyncVar] member variable references. dict - public Dictionary replacementSetterProperties = new Dictionary(); - // getter functions that replace [SyncVar] member variable references. dict - public Dictionary replacementGetterProperties = new Dictionary(); - - // [SyncEvent] invoke functions that should be replaced. dict - public Dictionary replaceEvents = new Dictionary(); - - public List generatedReadFunctions = new List(); - public List generatedWriteFunctions = new List(); - - public TypeDefinition generateContainerClass; - - // amount of SyncVars per class. dict - public Dictionary numSyncVars = new Dictionary(); - - public HashSet ProcessedMessages = new HashSet(); - } - - internal static class Weaver - { - public static string InvokeRpcPrefix => "InvokeUserCode_"; - public static string SyncEventPrefix => "SendEventMessage_"; - - public static WeaverLists WeaveLists { get; private set; } - public static AssemblyDefinition CurrentAssembly { get; private set; } - public static bool WeavingFailed { get; private set; } - public static bool GenerateLogErrors { get; set; } - - // private properties - static readonly bool DebugLogEnabled = true; - - public static void DLog(TypeDefinition td, string fmt, params object[] args) - { - if (!DebugLogEnabled) - return; - - Console.WriteLine("[" + td.Name + "] " + string.Format(fmt, args)); - } - - // display weaver error - // and mark process as failed - public static void Error(string message) - { - Log.Error(message); - WeavingFailed = true; - } - - public static void Error(string message, MemberReference mr) - { - Log.Error($"{message} (at {mr})"); - WeavingFailed = true; - } - - public static void Warning(string message, MemberReference mr) - { - Log.Warning($"{message} (at {mr})"); - } - - public static int GetSyncVarStart(string className) - { - return WeaveLists.numSyncVars.ContainsKey(className) - ? WeaveLists.numSyncVars[className] - : 0; - } - - public static void SetNumSyncVars(string className, int num) + // generated code class + public const string GeneratedCodeNamespace = "Mirror"; + public const string GeneratedCodeClassName = "GeneratedNetworkCode"; + TypeDefinition GeneratedCodeClass; + + // for resolving Mirror.dll in ReaderWriterProcessor, we need to know + // Mirror.dll name + public const string MirrorAssemblyName = "Mirror"; + + WeaverTypes weaverTypes; + SyncVarAccessLists syncVarAccessLists; + AssemblyDefinition CurrentAssembly; + Writers writers; + Readers readers; + + // in case of weaver errors, we don't stop immediately. + // we log all errors and then eventually return false if + // weaving has failed. + // this way the user can fix multiple errors at once, instead of having + // to fix -> recompile -> fix -> recompile for one error at a time. + bool WeavingFailed; + + // logger functions can be set from the outside. + // for example, Debug.Log or ILPostProcessor Diagnostics log for + // multi threaded logging. + public Logger Log; + + // remote actions now support overloads, + // -> but IL2CPP doesnt like it when two generated methods + // -> have the same signature, + // -> so, append the signature to the generated method name, + // -> to create a unique name + // Example: + // RpcTeleport(Vector3 position) -> InvokeUserCode_RpcTeleport__Vector3() + // RpcTeleport(Vector3 position, Quaternion rotation) -> InvokeUserCode_RpcTeleport__Vector3Quaternion() + // fixes https://github.com/vis2k/Mirror/issues/3060 + public static string GenerateMethodName(string initialPrefix, MethodDefinition md) { - WeaveLists.numSyncVars[className] = num; - } + initialPrefix += md.Name; - internal static void ConfirmGeneratedCodeClass() - { - if (WeaveLists.generateContainerClass == null) + for (int i = 0; i < md.Parameters.Count; ++i) { - WeaveLists.generateContainerClass = new TypeDefinition("Mirror", "GeneratedNetworkCode", - TypeAttributes.BeforeFieldInit | TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.Public | TypeAttributes.AutoClass, - WeaverTypes.objectType); - - const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; - MethodDefinition method = new MethodDefinition(".ctor", methodAttributes, WeaverTypes.voidType); - method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); - method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, Resolvers.ResolveMethod(WeaverTypes.objectType, CurrentAssembly, ".ctor"))); - method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - - WeaveLists.generateContainerClass.Methods.Add(method); + // with __ so it's more obvious that this is the parameter suffix. + // otherwise RpcTest(int) => RpcTestInt(int) which is not obvious. + initialPrefix += $"__{md.Parameters[i].ParameterType.Name}"; } - } - public static bool IsNetworkBehaviour(TypeDefinition td) - { - return td.IsDerivedFrom(WeaverTypes.NetworkBehaviourType); + return initialPrefix; } - static void CheckMonoBehaviour(TypeDefinition td) + public Weaver(Logger Log) { - if (td.IsDerivedFrom(WeaverTypes.MonoBehaviourType)) - { - MonoBehaviourProcessor.Process(td); - } + this.Log = Log; } - static bool WeaveNetworkBehavior(TypeDefinition td) + // returns 'true' if modified (=if we did anything) + bool WeaveNetworkBehavior(TypeDefinition td) { if (!td.IsClass) return false; - if (!IsNetworkBehaviour(td)) + if (!td.IsDerivedFrom()) { - CheckMonoBehaviour(td); + if (td.IsDerivedFrom()) + MonoBehaviourProcessor.Process(Log, td, ref WeavingFailed); return false; } @@ -129,7 +85,7 @@ static bool WeaveNetworkBehavior(TypeDefinition td) TypeDefinition parent = td; while (parent != null) { - if (parent.FullName == WeaverTypes.NetworkBehaviourType.FullName) + if (parent.Is()) { break; } @@ -150,164 +106,126 @@ static bool WeaveNetworkBehavior(TypeDefinition td) bool modified = false; foreach (TypeDefinition behaviour in behaviourClasses) { - modified |= new NetworkBehaviourProcessor(behaviour).Process(); + modified |= new NetworkBehaviourProcessor(CurrentAssembly, weaverTypes, syncVarAccessLists, writers, readers, Log, behaviour).Process(ref WeavingFailed); } return modified; } - static bool WeaveMessage(TypeDefinition td) + bool WeaveModule(ModuleDefinition moduleDefinition) { - if (!td.IsClass) - return false; - - // already processed - if (WeaveLists.ProcessedMessages.Contains(td.FullName)) - return false; - bool modified = false; - if (td.ImplementsInterface(WeaverTypes.IMessageBaseType)) + Stopwatch watch = Stopwatch.StartNew(); + watch.Start(); + + // ModuleDefinition.Types only finds top level types. + // GetAllTypes recursively finds all nested types as well. + // fixes nested types not being weaved, for example: + // class Parent { // ModuleDefinition.Types finds this + // class Child { // .Types.NestedTypes finds this + // class GrandChild {} // only GetAllTypes finds this too + // } + // } + // note this is not about inheritance, only about type definitions. + // see test: NetworkBehaviourTests.DeeplyNested() + foreach (TypeDefinition td in moduleDefinition.GetAllTypes()) { - // process this and base classes from parent to child order - try + if (td.IsClass && td.BaseType.CanBeResolved()) { - TypeDefinition parent = td.BaseType.Resolve(); - // process parent - WeaveMessage(parent); + modified |= WeaveNetworkBehavior(td); + modified |= ServerClientAttributeProcessor.Process(weaverTypes, Log, td, ref WeavingFailed); } - catch (AssemblyResolutionException) - { - // this can happen for plugins. - //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); - } - - // process this - MessageClassProcessor.Process(td); - WeaveLists.ProcessedMessages.Add(td.FullName); - modified = true; } - // check for embedded types - // inner classes should be processed after outter class to avoid StackOverflowException - foreach (TypeDefinition embedded in td.NestedTypes) - { - modified |= WeaveMessage(embedded); - } + watch.Stop(); + Console.WriteLine($"Weave behaviours and messages took {watch.ElapsedMilliseconds} milliseconds"); return modified; } - static bool WeaveSyncObject(TypeDefinition td) + void CreateGeneratedCodeClass() { - bool modified = false; - - // ignore generic classes - // we can not process generic classes - // we give error if a generic syncObject is used in NetworkBehaviour - if (td.HasGenericParameters) - return false; - - // ignore abstract classes - // we dont need to process abstract classes because classes that - // inherit from them will be processed instead - - // We cant early return with non classes or Abstract classes - // because we still need to check for embeded types - if (td.IsClass || !td.IsAbstract) - { - if (td.IsDerivedFrom(WeaverTypes.SyncListType)) - { - SyncListProcessor.Process(td, WeaverTypes.SyncListType); - modified = true; - } - else if (td.IsDerivedFrom(WeaverTypes.SyncSetType)) - { - SyncListProcessor.Process(td, WeaverTypes.SyncSetType); - modified = true; - } - else if (td.IsDerivedFrom(WeaverTypes.SyncDictionaryType)) - { - SyncDictionaryProcessor.Process(td); - modified = true; - } - } + // create "Mirror.GeneratedNetworkCode" class which holds all + // Readers and Writers + GeneratedCodeClass = new TypeDefinition(GeneratedCodeNamespace, GeneratedCodeClassName, + TypeAttributes.BeforeFieldInit | TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.Abstract | TypeAttributes.Sealed, + weaverTypes.Import()); + } - // check for embedded types - foreach (TypeDefinition embedded in td.NestedTypes) - { - modified |= WeaveSyncObject(embedded); - } + void ToggleWeaverFuse() + { + // // find Weaved() function + MethodDefinition func = weaverTypes.weaverFuseMethod.Resolve(); + // // change return 0 to return 1 - return modified; + ILProcessor worker = func.Body.GetILProcessor(); + func.Body.Instructions[0] = worker.Create(OpCodes.Ldc_I4_1); } - static bool WeaveModule(ModuleDefinition moduleDefinition) + // Weave takes an AssemblyDefinition to be compatible with both old and + // new weavers: + // * old takes a filepath, new takes a in-memory byte[] + // * old uses DefaultAssemblyResolver with added dependencies paths, + // new uses ...? + // + // => assembly: the one we are currently weaving (MyGame.dll) + // => resolver: useful in case we need to resolve any of the assembly's + // assembly.MainModule.AssemblyReferences. + // -> we can resolve ANY of them given that the resolver + // works properly (need custom one for ILPostProcessor) + // -> IMPORTANT: .Resolve() takes an AssemblyNameReference. + // those from assembly.MainModule.AssemblyReferences are + // guaranteed to be resolve-able. + // Parsing from a string for Library/.../Mirror.dll + // would not be guaranteed to be resolve-able because + // for ILPostProcessor we can't assume where Mirror.dll + // is etc. + public bool Weave(AssemblyDefinition assembly, IAssemblyResolver resolver, out bool modified) { + WeavingFailed = false; + modified = false; try { - bool modified = false; - - // We need to do 2 passes, because SyncListStructs might be referenced from other modules, so we must make sure we generate them first. - System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew(); - foreach (TypeDefinition td in moduleDefinition.Types) + CurrentAssembly = assembly; + + // fix "No writer found for ..." error + // https://github.com/vis2k/Mirror/issues/2579 + // -> when restarting Unity, weaver would try to weave a DLL + // again + // -> resulting in two GeneratedNetworkCode classes (see ILSpy) + // -> the second one wouldn't have all the writer types setup + if (CurrentAssembly.MainModule.ContainsClass(GeneratedCodeNamespace, GeneratedCodeClassName)) { - if (td.IsClass && td.BaseType.CanBeResolved()) - { - modified |= WeaveSyncObject(td); - } + //Log.Warning($"Weaver: skipping {CurrentAssembly.Name} because already weaved"); + return true; } - watch.Stop(); - Console.WriteLine("Weave sync objects took " + watch.ElapsedMilliseconds + " milliseconds"); - watch.Start(); - foreach (TypeDefinition td in moduleDefinition.Types) - { - if (td.IsClass && td.BaseType.CanBeResolved()) - { - modified |= WeaveNetworkBehavior(td); - modified |= WeaveMessage(td); - modified |= ServerClientAttributeProcessor.Process(td); - } - } - watch.Stop(); - Console.WriteLine("Weave behaviours and messages took" + watch.ElapsedMilliseconds + " milliseconds"); + weaverTypes = new WeaverTypes(CurrentAssembly, Log, ref WeavingFailed); - return modified; - } - catch (Exception ex) - { - Error(ex.ToString()); - throw new Exception(ex.Message, ex); - } - } + // weaverTypes are needed for CreateGeneratedCodeClass + CreateGeneratedCodeClass(); - static bool Weave(string assName, AssemblyDefinition unityAssembly, AssemblyDefinition mirrorAssembly, IEnumerable dependencies, string unityEngineDLLPath, string mirrorNetDLLPath, string outputDir) - { - using (DefaultAssemblyResolver asmResolver = new DefaultAssemblyResolver()) - using (CurrentAssembly = AssemblyDefinition.ReadAssembly(assName, new ReaderParameters { ReadWrite = true, ReadSymbols = true, AssemblyResolver = asmResolver })) - { - asmResolver.AddSearchDirectory(Path.GetDirectoryName(assName)); - asmResolver.AddSearchDirectory(Helpers.UnityEngineDllDirectoryName()); - asmResolver.AddSearchDirectory(Path.GetDirectoryName(unityEngineDLLPath)); - asmResolver.AddSearchDirectory(Path.GetDirectoryName(mirrorNetDLLPath)); - if (dependencies != null) - { - foreach (string path in dependencies) - { - asmResolver.AddSearchDirectory(path); - } - } + // WeaverList depends on WeaverTypes setup because it uses Import + syncVarAccessLists = new SyncVarAccessLists(); + + // initialize readers & writers with this assembly. + // we need to do this in every Process() call. + // otherwise we would get + // "System.ArgumentException: Member ... is declared in another module and needs to be imported" + // errors when still using the previous module's reader/writer funcs. + writers = new Writers(CurrentAssembly, weaverTypes, GeneratedCodeClass, Log); + readers = new Readers(CurrentAssembly, weaverTypes, GeneratedCodeClass, Log); - WeaverTypes.SetupTargetTypes(unityAssembly, mirrorAssembly, CurrentAssembly); - System.Diagnostics.Stopwatch rwstopwatch = System.Diagnostics.Stopwatch.StartNew(); - ReaderWriterProcessor.Process(CurrentAssembly); + Stopwatch rwstopwatch = Stopwatch.StartNew(); + // Need to track modified from ReaderWriterProcessor too because it could find custom read/write functions or create functions for NetworkMessages + modified = ReaderWriterProcessor.Process(CurrentAssembly, resolver, Log, writers, readers, ref WeavingFailed); rwstopwatch.Stop(); - Console.WriteLine("Find all reader and writers took " + rwstopwatch.ElapsedMilliseconds + " milliseconds"); + Console.WriteLine($"Find all reader and writers took {rwstopwatch.ElapsedMilliseconds} milliseconds"); ModuleDefinition moduleDefinition = CurrentAssembly.MainModule; - Console.WriteLine("Script Module: {0}", moduleDefinition.Name); + Console.WriteLine($"Script Module: {moduleDefinition.Name}"); - bool modified = WeaveModule(moduleDefinition); + modified |= WeaveModule(moduleDefinition); if (WeavingFailed) { @@ -316,103 +234,33 @@ static bool Weave(string assName, AssemblyDefinition unityAssembly, AssemblyDefi if (modified) { - // this must be done for ALL code, not just NetworkBehaviours - try - { - PropertySiteProcessor.Process(moduleDefinition); - } - catch (Exception e) - { - Log.Error("ProcessPropertySites exception: " + e); - return false; - } - - if (WeavingFailed) - { - return false; - } - - // write to outputDir if specified, otherwise perform in-place write - WriterParameters writeParams = new WriterParameters { WriteSymbols = true }; - if (!string.IsNullOrEmpty(outputDir)) - { - CurrentAssembly.Write(Helpers.DestinationFileFor(outputDir, assName), writeParams); - } - else - { - CurrentAssembly.Write(writeParams); - } - } - } + SyncVarAttributeAccessReplacer.Process(Log, moduleDefinition, syncVarAccessLists); - return true; - } + // add class that holds read/write functions + moduleDefinition.Types.Add(GeneratedCodeClass); - static bool WeaveAssemblies(IEnumerable assemblies, IEnumerable dependencies, string outputDir, string unityEngineDLLPath, string mirrorNetDLLPath) - { - WeavingFailed = false; - WeaveLists = new WeaverLists(); + ReaderWriterProcessor.InitializeReaderAndWriters(CurrentAssembly, weaverTypes, writers, readers, GeneratedCodeClass); - using (AssemblyDefinition unityAssembly = AssemblyDefinition.ReadAssembly(unityEngineDLLPath)) - using (AssemblyDefinition mirrorAssembly = AssemblyDefinition.ReadAssembly(mirrorNetDLLPath)) - { - WeaverTypes.SetupUnityTypes(unityAssembly, mirrorAssembly); - - try - { - foreach (string asm in assemblies) - { - if (!Weave(asm, unityAssembly, mirrorAssembly, dependencies, unityEngineDLLPath, mirrorNetDLLPath, outputDir)) - { - return false; - } - } + // DO NOT WRITE here. + // CompilationFinishedHook writes to the file. + // ILPostProcessor writes to in-memory assembly. + // it depends on the caller. + //CurrentAssembly.Write(new WriterParameters{ WriteSymbols = true }); } - catch (Exception e) + + // if weaving succeeded, switch on the Weaver Fuse in Mirror.dll + if (CurrentAssembly.Name.Name == MirrorAssemblyName) { - Log.Error("Exception :" + e); - return false; + ToggleWeaverFuse(); } - } - return true; - } - - public static bool Process(string unityEngine, string netDLL, string outputDirectory, string[] assemblies, string[] extraAssemblyPaths, Action printWarning, Action printError) - { - Validate(unityEngine, netDLL, outputDirectory, assemblies, extraAssemblyPaths); - Log.WarningMethod = printWarning; - Log.ErrorMethod = printError; - return WeaveAssemblies(assemblies, extraAssemblyPaths, outputDirectory, unityEngine, netDLL); - } - - static void Validate(string unityEngine, string netDLL, string outputDirectory, string[] assemblies, string[] extraAssemblyPaths) - { - CheckDllPath(unityEngine); - CheckDllPath(netDLL); - CheckOutputDirectory(outputDirectory); - CheckAssemblies(assemblies); - } - static void CheckDllPath(string path) - { - if (!File.Exists(path)) - throw new Exception("dll could not be located at " + path + "!"); - } - static void CheckAssemblies(IEnumerable assemblyPaths) - { - foreach (string assemblyPath in assemblyPaths) - CheckAssemblyPath(assemblyPath); - } - static void CheckAssemblyPath(string assemblyPath) - { - if (!File.Exists(assemblyPath)) - throw new Exception("Assembly " + assemblyPath + " does not exist!"); - } - static void CheckOutputDirectory(string outputDir) - { - if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + return true; + } + catch (Exception e) { - Directory.CreateDirectory(outputDir); + Log.Error($"Exception :{e}"); + WeavingFailed = true; + return false; } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Weaver.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Weaver.cs.meta index 0ea2dfeac6..2fd8b8d3a3 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Weaver.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Weaver.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Weaver.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverExceptions.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverExceptions.cs new file mode 100644 index 0000000000..efedd27f2e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverExceptions.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.Serialization; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + [Serializable] + public abstract class WeaverException : Exception + { + public MemberReference MemberReference { get; } + + protected WeaverException(string message, MemberReference member) : base(message) + { + MemberReference = member; + } + + protected WeaverException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) {} + } + + [Serializable] + public class GenerateWriterException : WeaverException + { + public GenerateWriterException(string message, MemberReference member) : base(message, member) {} + protected GenerateWriterException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) {} + } +} diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverExceptions.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverExceptions.cs.meta new file mode 100644 index 0000000000..757d608961 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverExceptions.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8aaaf6193bad7424492677f8e81f1b30 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverExceptions.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverTypes.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverTypes.cs index b90e02bae3..aa0d42d1dc 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverTypes.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverTypes.cs @@ -1,250 +1,171 @@ -using System.Linq; +using System; using Mono.CecilX; +using UnityEditor; +using UnityEngine; namespace Mirror.Weaver { - public static class WeaverTypes + // not static, because ILPostProcessor is multithreaded + public class WeaverTypes { - // Network types - public static TypeReference NetworkBehaviourType; - public static TypeReference RemoteCallHelperType; - public static TypeReference MonoBehaviourType; - public static TypeReference ScriptableObjectType; - public static TypeReference NetworkConnectionType; + public MethodReference ScriptableObjectCreateInstanceMethod; - public static TypeReference MessageBaseType; - public static TypeReference IMessageBaseType; - public static TypeReference SyncListType; - public static TypeReference SyncSetType; - public static TypeReference SyncDictionaryType; + public FieldReference NetworkBehaviourDirtyBitsReference; + public MethodReference GetWriterReference; + public MethodReference ReturnWriterReference; - public static MethodReference ScriptableObjectCreateInstanceMethod; + public MethodReference NetworkClientConnectionReference; - public static MethodReference NetworkBehaviourDirtyBitsReference; - public static MethodReference GetPooledWriterReference; - public static MethodReference RecycleWriterReference; - public static TypeReference NetworkClientType; - public static TypeReference NetworkServerType; + public MethodReference RemoteCallDelegateConstructor; - public static TypeReference NetworkReaderType; + public MethodReference NetworkServerGetActive; + public MethodReference NetworkClientGetActive; - public static TypeReference NetworkWriterType; - public static TypeReference PooledNetworkWriterType; + // custom attribute types + public MethodReference InitSyncObjectReference; - public static TypeReference NetworkIdentityType; - public static TypeReference IEnumeratorType; + // array segment + public MethodReference ArraySegmentConstructorReference; + + // Action for SyncVar Hooks + public MethodReference ActionT_T; + + // syncvar + public MethodReference generatedSyncVarSetter; + public MethodReference generatedSyncVarSetter_GameObject; + public MethodReference generatedSyncVarSetter_NetworkIdentity; + public MethodReference generatedSyncVarSetter_NetworkBehaviour_T; + public MethodReference generatedSyncVarDeserialize; + public MethodReference generatedSyncVarDeserialize_GameObject; + public MethodReference generatedSyncVarDeserialize_NetworkIdentity; + public MethodReference generatedSyncVarDeserialize_NetworkBehaviour_T; + public MethodReference getSyncVarGameObjectReference; + public MethodReference getSyncVarNetworkIdentityReference; + public MethodReference getSyncVarNetworkBehaviourReference; + public MethodReference registerCommandReference; + public MethodReference registerRpcReference; + public MethodReference getTypeFromHandleReference; + public MethodReference logErrorReference; + public MethodReference logWarningReference; + public MethodReference sendCommandInternal; + public MethodReference sendRpcInternal; + public MethodReference sendTargetRpcInternal; + + public MethodReference readNetworkBehaviourGeneric; + + public TypeReference weaverFuseType; + public MethodReference weaverFuseMethod; + + // attributes + public TypeDefinition initializeOnLoadMethodAttribute; + public TypeDefinition runtimeInitializeOnLoadMethodAttribute; + + AssemblyDefinition assembly; + + public TypeReference Import() => Import(typeof(T)); + + public TypeReference Import(Type t) => assembly.MainModule.ImportReference(t); + + // constructor resolves the types and stores them in fields + public WeaverTypes(AssemblyDefinition assembly, Logger Log, ref bool WeavingFailed) + { + // system types + this.assembly = assembly; - public static TypeReference ClientSceneType; - public static MethodReference ReadyConnectionReference; + TypeReference ArraySegmentType = Import(typeof(ArraySegment<>)); + ArraySegmentConstructorReference = Resolvers.ResolveMethod(ArraySegmentType, assembly, Log, ".ctor", ref WeavingFailed); - public static TypeReference ComponentType; - public static TypeReference ObjectType; + TypeReference ActionType = Import(typeof(Action<,>)); + ActionT_T = Resolvers.ResolveMethod(ActionType, assembly, Log, ".ctor", ref WeavingFailed); - public static TypeReference CmdDelegateReference; - public static MethodReference CmdDelegateConstructor; + weaverFuseType = Import(typeof(WeaverFuse)); + weaverFuseMethod = Resolvers.ResolveMethod(weaverFuseType, assembly, Log, "Weaved", ref WeavingFailed); - public static MethodReference NetworkServerGetActive; - public static MethodReference NetworkServerGetLocalClientActive; - public static MethodReference NetworkClientGetActive; + TypeReference NetworkServerType = Import(typeof(NetworkServer)); + NetworkServerGetActive = Resolvers.ResolveMethod(NetworkServerType, assembly, Log, "get_active", ref WeavingFailed); - // custom attribute types - public static TypeReference SyncVarType; - public static TypeReference CommandType; - public static TypeReference ClientRpcType; - public static TypeReference TargetRpcType; - public static TypeReference SyncEventType; - public static TypeReference SyncObjectType; - public static MethodReference InitSyncObjectReference; + TypeReference NetworkClientType = Import(typeof(NetworkClient)); + NetworkClientGetActive = Resolvers.ResolveMethod(NetworkClientType, assembly, Log, "get_active", ref WeavingFailed); + NetworkClientConnectionReference = Resolvers.ResolveMethod(NetworkClientType, assembly, Log, "get_connection", ref WeavingFailed); - // array segment - public static TypeReference ArraySegmentType; - public static MethodReference ArraySegmentConstructorReference; - public static MethodReference ArraySegmentArrayReference; - public static MethodReference ArraySegmentOffsetReference; - public static MethodReference ArraySegmentCountReference; - - // list - public static TypeReference ListType; - public static MethodReference ListConstructorReference; - public static MethodReference ListCountReference; - public static MethodReference ListGetItemReference; - public static MethodReference ListAddReference; - - // system types - public static TypeReference voidType; - public static TypeReference singleType; - public static TypeReference doubleType; - public static TypeReference boolType; - public static TypeReference int64Type; - public static TypeReference uint64Type; - public static TypeReference int32Type; - public static TypeReference uint32Type; - public static TypeReference objectType; - public static TypeReference typeType; - public static TypeReference gameObjectType; - public static TypeReference transformType; - - public static MethodReference syncVarEqualReference; - public static MethodReference syncVarNetworkIdentityEqualReference; - public static MethodReference syncVarGameObjectEqualReference; - public static MethodReference setSyncVarReference; - public static MethodReference setSyncVarHookGuard; - public static MethodReference getSyncVarHookGuard; - public static MethodReference setSyncVarGameObjectReference; - public static MethodReference getSyncVarGameObjectReference; - public static MethodReference setSyncVarNetworkIdentityReference; - public static MethodReference getSyncVarNetworkIdentityReference; - public static MethodReference registerCommandDelegateReference; - public static MethodReference registerRpcDelegateReference; - public static MethodReference registerEventDelegateReference; - public static MethodReference getTypeReference; - public static MethodReference getTypeFromHandleReference; - public static MethodReference logErrorReference; - public static MethodReference logWarningReference; - public static MethodReference sendCommandInternal; - public static MethodReference sendRpcInternal; - public static MethodReference sendTargetRpcInternal; - public static MethodReference sendEventInternal; - - - public static void SetupUnityTypes(AssemblyDefinition unityAssembly, AssemblyDefinition mirrorAssembly) - { - gameObjectType = unityAssembly.MainModule.GetType("UnityEngine.GameObject"); - transformType = unityAssembly.MainModule.GetType("UnityEngine.Transform"); - - NetworkClientType = mirrorAssembly.MainModule.GetType("Mirror.NetworkClient"); - NetworkServerType = mirrorAssembly.MainModule.GetType("Mirror.NetworkServer"); - - SyncVarType = mirrorAssembly.MainModule.GetType("Mirror.SyncVarAttribute"); - CommandType = mirrorAssembly.MainModule.GetType("Mirror.CommandAttribute"); - ClientRpcType = mirrorAssembly.MainModule.GetType("Mirror.ClientRpcAttribute"); - TargetRpcType = mirrorAssembly.MainModule.GetType("Mirror.TargetRpcAttribute"); - SyncEventType = mirrorAssembly.MainModule.GetType("Mirror.SyncEventAttribute"); - SyncObjectType = mirrorAssembly.MainModule.GetType("Mirror.SyncObject"); - } + TypeReference NetworkBehaviourType = Import(); - static ModuleDefinition ResolveSystemModule(AssemblyDefinition currentAssembly) - { - AssemblyNameReference name = AssemblyNameReference.Parse("mscorlib"); - ReaderParameters parameters = new ReaderParameters - { - AssemblyResolver = currentAssembly.MainModule.AssemblyResolver - }; - return currentAssembly.MainModule.AssemblyResolver.Resolve(name, parameters).MainModule; - } + NetworkBehaviourDirtyBitsReference = Resolvers.ResolveField(NetworkBehaviourType, assembly, Log, "syncVarDirtyBits", ref WeavingFailed); - static TypeReference ImportSystemModuleType(AssemblyDefinition currentAssembly, ModuleDefinition systemModule, string fullName) - { - TypeDefinition type = systemModule.GetType(fullName) ?? systemModule.ExportedTypes.First(t => t.FullName == fullName).Resolve(); - if (type != null) - { - return currentAssembly.MainModule.ImportReference(type); - } - Weaver.Error("Failed to import mscorlib type: " + fullName + " because Resolve failed. (Might happen when trying to Resolve in NetStandard dll, see also: https://github.com/vis2k/Mirror/issues/791)"); - return null; - } + generatedSyncVarSetter = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarSetter", ref WeavingFailed); + generatedSyncVarSetter_GameObject = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarSetter_GameObject", ref WeavingFailed); + generatedSyncVarSetter_NetworkIdentity = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarSetter_NetworkIdentity", ref WeavingFailed); + generatedSyncVarSetter_NetworkBehaviour_T = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarSetter_NetworkBehaviour", ref WeavingFailed); - public static void SetupTargetTypes(AssemblyDefinition unityAssembly, AssemblyDefinition mirrorAssembly, AssemblyDefinition currentAssembly) - { - // system types - ModuleDefinition systemModule = ResolveSystemModule(currentAssembly); - voidType = ImportSystemModuleType(currentAssembly, systemModule, "System.Void"); - singleType = ImportSystemModuleType(currentAssembly, systemModule, "System.Single"); - doubleType = ImportSystemModuleType(currentAssembly, systemModule, "System.Double"); - boolType = ImportSystemModuleType(currentAssembly, systemModule, "System.Boolean"); - int64Type = ImportSystemModuleType(currentAssembly, systemModule, "System.Int64"); - uint64Type = ImportSystemModuleType(currentAssembly, systemModule, "System.UInt64"); - int32Type = ImportSystemModuleType(currentAssembly, systemModule, "System.Int32"); - uint32Type = ImportSystemModuleType(currentAssembly, systemModule, "System.UInt32"); - objectType = ImportSystemModuleType(currentAssembly, systemModule, "System.Object"); - typeType = ImportSystemModuleType(currentAssembly, systemModule, "System.Type"); - IEnumeratorType = ImportSystemModuleType(currentAssembly, systemModule, "System.Collections.IEnumerator"); - - ArraySegmentType = ImportSystemModuleType(currentAssembly, systemModule, "System.ArraySegment`1"); - ArraySegmentArrayReference = Resolvers.ResolveProperty(ArraySegmentType, currentAssembly, "Array"); - ArraySegmentCountReference = Resolvers.ResolveProperty(ArraySegmentType, currentAssembly, "Count"); - ArraySegmentOffsetReference = Resolvers.ResolveProperty(ArraySegmentType, currentAssembly, "Offset"); - ArraySegmentConstructorReference = Resolvers.ResolveMethod(ArraySegmentType, currentAssembly, ".ctor"); - - ListType = ImportSystemModuleType(currentAssembly, systemModule, "System.Collections.Generic.List`1"); - ListCountReference = Resolvers.ResolveProperty(ListType, currentAssembly, "Count"); - ListGetItemReference = Resolvers.ResolveMethod(ListType, currentAssembly, "get_Item"); - ListAddReference = Resolvers.ResolveMethod(ListType, currentAssembly, "Add"); - ListConstructorReference = Resolvers.ResolveMethod(ListType, currentAssembly, ".ctor"); - - NetworkReaderType = mirrorAssembly.MainModule.GetType("Mirror.NetworkReader"); - NetworkWriterType = mirrorAssembly.MainModule.GetType("Mirror.NetworkWriter"); - TypeReference pooledNetworkWriterTmp = mirrorAssembly.MainModule.GetType("Mirror.PooledNetworkWriter"); - PooledNetworkWriterType = currentAssembly.MainModule.ImportReference(pooledNetworkWriterTmp); - - NetworkServerGetActive = Resolvers.ResolveMethod(NetworkServerType, currentAssembly, "get_active"); - NetworkServerGetLocalClientActive = Resolvers.ResolveMethod(NetworkServerType, currentAssembly, "get_localClientActive"); - NetworkClientGetActive = Resolvers.ResolveMethod(NetworkClientType, currentAssembly, "get_active"); - - CmdDelegateReference = mirrorAssembly.MainModule.GetType("Mirror.RemoteCalls.CmdDelegate"); - CmdDelegateConstructor = Resolvers.ResolveMethod(CmdDelegateReference, currentAssembly, ".ctor"); - - currentAssembly.MainModule.ImportReference(gameObjectType); - currentAssembly.MainModule.ImportReference(transformType); - - TypeReference networkIdentityTmp = mirrorAssembly.MainModule.GetType("Mirror.NetworkIdentity"); - NetworkIdentityType = currentAssembly.MainModule.ImportReference(networkIdentityTmp); - - NetworkBehaviourType = mirrorAssembly.MainModule.GetType("Mirror.NetworkBehaviour"); - RemoteCallHelperType = mirrorAssembly.MainModule.GetType("Mirror.RemoteCalls.RemoteCallHelper"); - NetworkConnectionType = mirrorAssembly.MainModule.GetType("Mirror.NetworkConnection"); - - MonoBehaviourType = unityAssembly.MainModule.GetType("UnityEngine.MonoBehaviour"); - ScriptableObjectType = unityAssembly.MainModule.GetType("UnityEngine.ScriptableObject"); + generatedSyncVarDeserialize_GameObject = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarDeserialize_GameObject", ref WeavingFailed); + generatedSyncVarDeserialize = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarDeserialize", ref WeavingFailed); + generatedSyncVarDeserialize_NetworkIdentity = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarDeserialize_NetworkIdentity", ref WeavingFailed); + generatedSyncVarDeserialize_NetworkBehaviour_T = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarDeserialize_NetworkBehaviour", ref WeavingFailed); + + getSyncVarGameObjectReference = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GetSyncVarGameObject", ref WeavingFailed); + getSyncVarNetworkIdentityReference = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GetSyncVarNetworkIdentity", ref WeavingFailed); + getSyncVarNetworkBehaviourReference = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GetSyncVarNetworkBehaviour", ref WeavingFailed); + + sendCommandInternal = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "SendCommandInternal", ref WeavingFailed); + sendRpcInternal = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "SendRPCInternal", ref WeavingFailed); + sendTargetRpcInternal = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "SendTargetRPCInternal", ref WeavingFailed); + + InitSyncObjectReference = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "InitSyncObject", ref WeavingFailed); + TypeReference RemoteProcedureCallsType = Import(typeof(RemoteCalls.RemoteProcedureCalls)); + registerCommandReference = Resolvers.ResolveMethod(RemoteProcedureCallsType, assembly, Log, "RegisterCommand", ref WeavingFailed); + registerRpcReference = Resolvers.ResolveMethod(RemoteProcedureCallsType, assembly, Log, "RegisterRpc", ref WeavingFailed); + + TypeReference RemoteCallDelegateType = Import(); + RemoteCallDelegateConstructor = Resolvers.ResolveMethod(RemoteCallDelegateType, assembly, Log, ".ctor", ref WeavingFailed); + + TypeReference ScriptableObjectType = Import(); ScriptableObjectCreateInstanceMethod = Resolvers.ResolveMethod( - ScriptableObjectType, currentAssembly, - md => md.Name == "CreateInstance" && md.HasGenericParameters); - - NetworkConnectionType = mirrorAssembly.MainModule.GetType("Mirror.NetworkConnection"); - NetworkConnectionType = currentAssembly.MainModule.ImportReference(NetworkConnectionType); - - MessageBaseType = mirrorAssembly.MainModule.GetType("Mirror.MessageBase"); - IMessageBaseType = mirrorAssembly.MainModule.GetType("Mirror.IMessageBase"); - SyncListType = mirrorAssembly.MainModule.GetType("Mirror.SyncList`1"); - SyncSetType = mirrorAssembly.MainModule.GetType("Mirror.SyncSet`1"); - SyncDictionaryType = mirrorAssembly.MainModule.GetType("Mirror.SyncDictionary`2"); - - NetworkBehaviourDirtyBitsReference = Resolvers.ResolveProperty(NetworkBehaviourType, currentAssembly, "syncVarDirtyBits"); - TypeDefinition NetworkWriterPoolType = mirrorAssembly.MainModule.GetType("Mirror.NetworkWriterPool"); - GetPooledWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, currentAssembly, "GetWriter"); - RecycleWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, currentAssembly, "Recycle"); - - ComponentType = unityAssembly.MainModule.GetType("UnityEngine.Component"); - ObjectType = unityAssembly.MainModule.GetType("UnityEngine.Object"); - ClientSceneType = mirrorAssembly.MainModule.GetType("Mirror.ClientScene"); - ReadyConnectionReference = Resolvers.ResolveMethod(ClientSceneType, currentAssembly, "get_readyConnection"); - - syncVarEqualReference = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SyncVarEqual"); - syncVarNetworkIdentityEqualReference = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SyncVarNetworkIdentityEqual"); - syncVarGameObjectEqualReference = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SyncVarGameObjectEqual"); - setSyncVarReference = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SetSyncVar"); - setSyncVarHookGuard = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "setSyncVarHookGuard"); - getSyncVarHookGuard = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "getSyncVarHookGuard"); - - setSyncVarGameObjectReference = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SetSyncVarGameObject"); - getSyncVarGameObjectReference = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "GetSyncVarGameObject"); - setSyncVarNetworkIdentityReference = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SetSyncVarNetworkIdentity"); - getSyncVarNetworkIdentityReference = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "GetSyncVarNetworkIdentity"); - registerCommandDelegateReference = Resolvers.ResolveMethod(RemoteCallHelperType, currentAssembly, "RegisterCommandDelegate"); - registerRpcDelegateReference = Resolvers.ResolveMethod(RemoteCallHelperType, currentAssembly, "RegisterRpcDelegate"); - registerEventDelegateReference = Resolvers.ResolveMethod(RemoteCallHelperType, currentAssembly, "RegisterEventDelegate"); - getTypeReference = Resolvers.ResolveMethod(objectType, currentAssembly, "GetType"); - getTypeFromHandleReference = Resolvers.ResolveMethod(typeType, currentAssembly, "GetTypeFromHandle"); - logErrorReference = Resolvers.ResolveMethod(unityAssembly.MainModule.GetType("UnityEngine.Debug"), currentAssembly, "LogError"); - logWarningReference = Resolvers.ResolveMethod(unityAssembly.MainModule.GetType("UnityEngine.Debug"), currentAssembly, "LogWarning"); - sendCommandInternal = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SendCommandInternal"); - sendRpcInternal = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SendRPCInternal"); - sendTargetRpcInternal = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SendTargetRPCInternal"); - sendEventInternal = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "SendEventInternal"); - - SyncObjectType = currentAssembly.MainModule.ImportReference(SyncObjectType); - InitSyncObjectReference = Resolvers.ResolveMethod(NetworkBehaviourType, currentAssembly, "InitSyncObject"); + ScriptableObjectType, assembly, Log, + md => md.Name == "CreateInstance" && md.HasGenericParameters, + ref WeavingFailed); + + TypeReference unityDebug = Import(typeof(UnityEngine.Debug)); + // these have multiple methods with same name, so need to check parameters too + logErrorReference = Resolvers.ResolveMethod(unityDebug, assembly, Log, md => + md.Name == "LogError" && + md.Parameters.Count == 1 && + md.Parameters[0].ParameterType.FullName == typeof(object).FullName, + ref WeavingFailed); + + logWarningReference = Resolvers.ResolveMethod(unityDebug, assembly, Log, md => + md.Name == "LogWarning" && + md.Parameters.Count == 1 && + md.Parameters[0].ParameterType.FullName == typeof(object).FullName, + ref WeavingFailed); + + TypeReference typeType = Import(typeof(Type)); + getTypeFromHandleReference = Resolvers.ResolveMethod(typeType, assembly, Log, "GetTypeFromHandle", ref WeavingFailed); + + TypeReference NetworkWriterPoolType = Import(typeof(NetworkWriterPool)); + GetWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, assembly, Log, "Get", ref WeavingFailed); + ReturnWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, assembly, Log, "Return", ref WeavingFailed); + + TypeReference readerExtensions = Import(typeof(NetworkReaderExtensions)); + readNetworkBehaviourGeneric = Resolvers.ResolveMethod(readerExtensions, assembly, Log, (md => + { + return md.Name == nameof(NetworkReaderExtensions.ReadNetworkBehaviour) && + md.HasGenericParameters; + }), + ref WeavingFailed); + + // [InitializeOnLoadMethod] + // 'UnityEditor' is not available in builds. + // we can only import this attribute if we are in an Editor assembly. + if (Helpers.IsEditorAssembly(assembly)) + { + TypeReference initializeOnLoadMethodAttributeRef = Import(typeof(InitializeOnLoadMethodAttribute)); + initializeOnLoadMethodAttribute = initializeOnLoadMethodAttributeRef.Resolve(); + } + + // [RuntimeInitializeOnLoadMethod] + TypeReference runtimeInitializeOnLoadMethodAttributeRef = Import(typeof(RuntimeInitializeOnLoadMethodAttribute)); + runtimeInitializeOnLoadMethodAttribute = runtimeInitializeOnLoadMethodAttributeRef.Resolve(); } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverTypes.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverTypes.cs.meta index d71c33f3c7..1d47b93066 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverTypes.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverTypes.cs.meta @@ -1,3 +1,10 @@ fileFormatVersion: 2 guid: 2585961bf7fe4c10a9143f4087efdf6f -timeCreated: 1596486854 \ No newline at end of file +timeCreated: 1596486854 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/WeaverTypes.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Writers.cs b/Assets/ImportedAssets/Mirror/Editor/Weaver/Writers.cs index e5db8e8447..8311a26156 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Writers.cs +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Writers.cs @@ -1,515 +1,341 @@ +using System; using System.Collections.Generic; using Mono.CecilX; using Mono.CecilX.Cil; +// to use Mono.CecilX.Rocks here, we need to 'override references' in the +// Unity.Mirror.CodeGen assembly definition file in the Editor, and add CecilX.Rocks. +// otherwise we get an unknown import exception. +using Mono.CecilX.Rocks; namespace Mirror.Weaver { - - public static class Writers + // not static, because ILPostProcessor is multithreaded + public class Writers { - const int MaxRecursionCount = 128; - - static Dictionary writeFuncs; - - public static void Init() + // Writers are only for this assembly. + // can't be used from another assembly, otherwise we will get: + // "System.ArgumentException: Member ... is declared in another module and needs to be imported" + AssemblyDefinition assembly; + WeaverTypes weaverTypes; + TypeDefinition GeneratedCodeClass; + Logger Log; + + Dictionary writeFuncs = + new Dictionary(new TypeReferenceComparer()); + + public Writers(AssemblyDefinition assembly, WeaverTypes weaverTypes, TypeDefinition GeneratedCodeClass, Logger Log) { - writeFuncs = new Dictionary(); + this.assembly = assembly; + this.weaverTypes = weaverTypes; + this.GeneratedCodeClass = GeneratedCodeClass; + this.Log = Log; } - public static void Register(TypeReference dataType, MethodReference methodReference) + public void Register(TypeReference dataType, MethodReference methodReference) { - writeFuncs[dataType.FullName] = methodReference; + if (writeFuncs.ContainsKey(dataType)) + { + // TODO enable this again later. + // Writer has some obsolete functions that were renamed. + // Don't want weaver warnings for all of them. + //Log.Warning($"Registering a Write method for {dataType.FullName} when one already exists", methodReference); + } + + // we need to import type when we Initialize Writers so import here in case it is used anywhere else + TypeReference imported = assembly.MainModule.ImportReference(dataType); + writeFuncs[imported] = methodReference; } - static void RegisterWriteFunc(string name, MethodDefinition newWriterFunc) + void RegisterWriteFunc(TypeReference typeReference, MethodDefinition newWriterFunc) { - writeFuncs[name] = newWriterFunc; - Weaver.WeaveLists.generatedWriteFunctions.Add(newWriterFunc); - - Weaver.ConfirmGeneratedCodeClass(); - Weaver.WeaveLists.generateContainerClass.Methods.Add(newWriterFunc); + Register(typeReference, newWriterFunc); + GeneratedCodeClass.Methods.Add(newWriterFunc); } - public static MethodReference GetWriteFunc(TypeReference variable, int recursionCount = 0) + // Finds existing writer for type, if non exists trys to create one + public MethodReference GetWriteFunc(TypeReference variable, ref bool WeavingFailed) { - if (writeFuncs.TryGetValue(variable.FullName, out MethodReference foundFunc)) - { + if (writeFuncs.TryGetValue(variable, out MethodReference foundFunc)) return foundFunc; - } - else if (variable.Resolve().IsEnum) + + // this try/catch will be removed in future PR and make `GetWriteFunc` throw instead + try { - // serialize enum as their base type - return GetWriteFunc(variable.Resolve().GetEnumUnderlyingType()); + TypeReference importedVariable = assembly.MainModule.ImportReference(variable); + return GenerateWriter(importedVariable, ref WeavingFailed); } - else + catch (GenerateWriterException e) { - MethodDefinition newWriterFunc = GenerateWriter(variable, recursionCount); - if (newWriterFunc != null) - { - RegisterWriteFunc(variable.FullName, newWriterFunc); - } - return newWriterFunc; + Log.Error(e.Message, e.MemberReference); + WeavingFailed = true; + return null; } } - static MethodDefinition GenerateWriter(TypeReference variableReference, int recursionCount = 0) + //Throws GenerateWriterException when writer could not be generated for type + MethodReference GenerateWriter(TypeReference variableReference, ref bool WeavingFailed) { - // TODO: do we need this check? do we ever receieve types that are "ByReference"s if (variableReference.IsByReference) { - // error?? - Weaver.Error($"Cannot pass {variableReference.Name} by reference", variableReference); - return null; + throw new GenerateWriterException($"Cannot pass {variableReference.Name} by reference", variableReference); } // Arrays are special, if we resolve them, we get the element type, - // eg int[] resolves to int + // e.g. int[] resolves to int // therefore process this before checks below if (variableReference.IsArray) { - return GenerateArrayWriteFunc(variableReference, recursionCount); + if (variableReference.IsMultidimensionalArray()) + { + throw new GenerateWriterException($"{variableReference.Name} is an unsupported type. Multidimensional arrays are not supported", variableReference); + } + TypeReference elementType = variableReference.GetElementType(); + return GenerateCollectionWriter(variableReference, elementType, nameof(NetworkWriterExtensions.WriteArray), ref WeavingFailed); + } + + if (variableReference.Resolve()?.IsEnum ?? false) + { + // serialize enum as their base type + return GenerateEnumWriteFunc(variableReference, ref WeavingFailed); } // check for collections + if (variableReference.Is(typeof(ArraySegment<>))) + { + GenericInstanceType genericInstance = (GenericInstanceType)variableReference; + TypeReference elementType = genericInstance.GenericArguments[0]; - if (variableReference.IsArraySegment()) + return GenerateCollectionWriter(variableReference, elementType, nameof(NetworkWriterExtensions.WriteArraySegment), ref WeavingFailed); + } + if (variableReference.Is(typeof(List<>))) { - return GenerateArraySegmentWriteFunc(variableReference, recursionCount); + GenericInstanceType genericInstance = (GenericInstanceType)variableReference; + TypeReference elementType = genericInstance.GenericArguments[0]; + + return GenerateCollectionWriter(variableReference, elementType, nameof(NetworkWriterExtensions.WriteList), ref WeavingFailed); } - if (variableReference.IsList()) + + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + if (variableReference.IsDerivedFrom() || variableReference.Is()) { - return GenerateListWriteFunc(variableReference, recursionCount); + return GetNetworkBehaviourWriter(variableReference); } // check for invalid types - TypeDefinition variableDefinition = variableReference.Resolve(); if (variableDefinition == null) { - Weaver.Error($"{variableReference.Name} is not a supported type. Use a supported type or provide a custom writer", variableReference); - return null; + throw new GenerateWriterException($"{variableReference.Name} is not a supported type. Use a supported type or provide a custom writer", variableReference); } - if (variableDefinition.IsDerivedFrom(WeaverTypes.ComponentType)) + if (variableDefinition.IsDerivedFrom()) { - Weaver.Error($"Cannot generate writer for component type {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); - return null; + throw new GenerateWriterException($"Cannot generate writer for component type {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); } - if (variableReference.FullName == WeaverTypes.ObjectType.FullName) + if (variableReference.Is()) { - Weaver.Error($"Cannot generate writer for {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); - return null; + throw new GenerateWriterException($"Cannot generate writer for {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); } - if (variableReference.FullName == WeaverTypes.ScriptableObjectType.FullName) + if (variableReference.Is()) { - Weaver.Error($"Cannot generate writer for {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); - return null; + throw new GenerateWriterException($"Cannot generate writer for {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); } if (variableDefinition.HasGenericParameters) { - Weaver.Error($"Cannot generate writer for generic type {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); - return null; + throw new GenerateWriterException($"Cannot generate writer for generic type {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); } if (variableDefinition.IsInterface) { - Weaver.Error($"Cannot generate writer for interface {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); - return null; + throw new GenerateWriterException($"Cannot generate writer for interface {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); } if (variableDefinition.IsAbstract) { - Weaver.Error($"Cannot generate writer for abstract class {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); - return null; + throw new GenerateWriterException($"Cannot generate writer for abstract class {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); } // generate writer for class/struct - - return GenerateClassOrStructWriterFunction(variableReference, recursionCount); + return GenerateClassOrStructWriterFunction(variableReference, ref WeavingFailed); } - static MethodDefinition GenerateClassOrStructWriterFunction(TypeReference variable, int recursionCount) + MethodReference GetNetworkBehaviourWriter(TypeReference variableReference) { - if (recursionCount > MaxRecursionCount) + // all NetworkBehaviours can use the same write function + if (writeFuncs.TryGetValue(weaverTypes.Import(), out MethodReference func)) { - Weaver.Error($"{variable.Name} can't be serialized because it references itself", variable); - return null; - } + // register function so it is added to writer + // use Register instead of RegisterWriteFunc because this is not a generated function + Register(variableReference, func); - string functionName = "_Write" + variable.Name + "_"; - if (variable.DeclaringType != null) - { - functionName += variable.DeclaringType.Name; + return func; } else { - functionName += "None"; + // this exception only happens if mirror is missing the WriteNetworkBehaviour method + throw new MissingMethodException($"Could not find writer for NetworkBehaviour"); } - // create new writer for this type - MethodDefinition writerFunc = new MethodDefinition(functionName, - MethodAttributes.Public | - MethodAttributes.Static | - MethodAttributes.HideBySig, - WeaverTypes.voidType); - - writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkWriterType))); - writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(variable))); - - ILProcessor worker = writerFunc.Body.GetILProcessor(); - - if (!WriteAllFields(variable, recursionCount, worker)) - return null; - - worker.Append(worker.Create(OpCodes.Ret)); - return writerFunc; } - /// - /// Find all fields in type and write them - /// - /// - /// - /// - /// false if fail - static bool WriteAllFields(TypeReference variable, int recursionCount, ILProcessor worker) + MethodDefinition GenerateEnumWriteFunc(TypeReference variable, ref bool WeavingFailed) { - uint fields = 0; - foreach (FieldDefinition field in variable.FindAllPublicFields()) - { - MethodReference writeFunc = GetWriteFunc(field.FieldType, recursionCount + 1); - if (writeFunc != null) - { - FieldReference fieldRef = Weaver.CurrentAssembly.MainModule.ImportReference(field); + MethodDefinition writerFunc = GenerateWriterFunc(variable); - fields++; - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Ldfld, fieldRef)); - worker.Append(worker.Create(OpCodes.Call, writeFunc)); - } - else - { - Weaver.Error($"{field.Name} has unsupported type. Use a type supported by Mirror instead", field); - return false; - } - } + ILProcessor worker = writerFunc.Body.GetILProcessor(); - if (fields == 0) - { - Log.Warning($"{variable} has no no public or non-static fields to serialize"); - } + MethodReference underlyingWriter = GetWriteFunc(variable.Resolve().GetEnumUnderlyingType(), ref WeavingFailed); - return true; + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_1); + worker.Emit(OpCodes.Call, underlyingWriter); + + worker.Emit(OpCodes.Ret); + return writerFunc; } - static MethodDefinition GenerateArrayWriteFunc(TypeReference variable, int recursionCount) + MethodDefinition GenerateWriterFunc(TypeReference variable) { - if (!variable.IsArrayType()) - { - Weaver.Error($"{variable.Name} is an unsupported type. Jagged and multidimensional arrays are not supported", variable); - return null; - } - - TypeReference elementType = variable.GetElementType(); - MethodReference elementWriteFunc = GetWriteFunc(elementType, recursionCount + 1); - MethodReference intWriterFunc = GetWriteFunc(WeaverTypes.int32Type); - if (elementWriteFunc == null) - { - Weaver.Error($"Cannot generate writer for Array because element {elementType.Name} does not have a writer. Use a supported type or provide a custom writer", variable); - return null; - } - - string functionName = "_WriteArray" + variable.GetElementType().Name + "_"; - if (variable.DeclaringType != null) - { - functionName += variable.DeclaringType.Name; - } - else - { - functionName += "None"; - } - + string functionName = $"_Write_{variable.FullName}"; // create new writer for this type MethodDefinition writerFunc = new MethodDefinition(functionName, MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig, - WeaverTypes.voidType); + weaverTypes.Import(typeof(void))); - writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkWriterType))); - writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(variable))); - - writerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - writerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); + writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, weaverTypes.Import())); + writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, variable)); writerFunc.Body.InitLocals = true; - ILProcessor worker = writerFunc.Body.GetILProcessor(); - - // if (value == null) - // { - // writer.WritePackedInt32(-1); - // return; - // } - Instruction labelNull = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Brtrue, labelNull)); - - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldc_I4_M1)); - worker.Append(worker.Create(OpCodes.Call, intWriterFunc)); - worker.Append(worker.Create(OpCodes.Ret)); - - // else not null - worker.Append(labelNull); - - // int length = value.Length; - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Ldlen)); - worker.Append(worker.Create(OpCodes.Stloc_0)); - - // writer.WritePackedInt32(length); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Call, intWriterFunc)); - - // for (int i=0; i< value.length; i++) { - worker.Append(worker.Create(OpCodes.Ldc_I4_0)); - worker.Append(worker.Create(OpCodes.Stloc_1)); - Instruction labelHead = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Br, labelHead)); - - // loop body - Instruction labelBody = worker.Create(OpCodes.Nop); - worker.Append(labelBody); - // writer.Write(value[i]); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldelema, elementType)); - worker.Append(worker.Create(OpCodes.Ldobj, elementType)); - worker.Append(worker.Create(OpCodes.Call, elementWriteFunc)); - - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldc_I4_1)); - worker.Append(worker.Create(OpCodes.Add)); - worker.Append(worker.Create(OpCodes.Stloc_1)); - - // end for loop - worker.Append(labelHead); - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Ldlen)); - worker.Append(worker.Create(OpCodes.Conv_I4)); - worker.Append(worker.Create(OpCodes.Blt, labelBody)); - - // return - worker.Append(worker.Create(OpCodes.Ret)); + RegisterWriteFunc(variable, writerFunc); return writerFunc; } - static MethodDefinition GenerateArraySegmentWriteFunc(TypeReference variable, int recursionCount) + MethodDefinition GenerateClassOrStructWriterFunction(TypeReference variable, ref bool WeavingFailed) { - GenericInstanceType genericInstance = (GenericInstanceType)variable; - TypeReference elementType = genericInstance.GenericArguments[0]; - MethodReference elementWriteFunc = GetWriteFunc(elementType, recursionCount + 1); - MethodReference intWriterFunc = GetWriteFunc(WeaverTypes.int32Type); - - if (elementWriteFunc == null) - { - Weaver.Error($"Cannot generate writer for ArraySegment because element {elementType.Name} does not have a writer. Use a supported type or provide a custom writer", variable); - return null; - } - - string functionName = "_WriteArraySegment_" + elementType.Name + "_"; - if (variable.DeclaringType != null) - { - functionName += variable.DeclaringType.Name; - } - else - { - functionName += "None"; - } - - // create new writer for this type - MethodDefinition writerFunc = new MethodDefinition(functionName, - MethodAttributes.Public | - MethodAttributes.Static | - MethodAttributes.HideBySig, - WeaverTypes.voidType); - - writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkWriterType))); - writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, variable)); - - writerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - writerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - writerFunc.Body.InitLocals = true; + MethodDefinition writerFunc = GenerateWriterFunc(variable); ILProcessor worker = writerFunc.Body.GetILProcessor(); - MethodReference countref = WeaverTypes.ArraySegmentCountReference.MakeHostInstanceGeneric(genericInstance); - - // int length = value.Count; - worker.Append(worker.Create(OpCodes.Ldarga_S, (byte)1)); - worker.Append(worker.Create(OpCodes.Call, countref)); - worker.Append(worker.Create(OpCodes.Stloc_0)); + if (!variable.Resolve().IsValueType) + WriteNullCheck(worker, ref WeavingFailed); + if (!WriteAllFields(variable, worker, ref WeavingFailed)) + return null; - // writer.WritePackedInt32(length); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Call, intWriterFunc)); + worker.Emit(OpCodes.Ret); + return writerFunc; + } - // Loop through the ArraySegment and call the writer for each element. - // generates this: - // for (int i=0; i< length; i++) + void WriteNullCheck(ILProcessor worker, ref bool WeavingFailed) + { + // if (value == null) // { - // writer.Write(value.Array[i + value.Offset]); + // writer.WriteBoolean(false); + // return; // } - worker.Append(worker.Create(OpCodes.Ldc_I4_0)); - worker.Append(worker.Create(OpCodes.Stloc_1)); - Instruction labelHead = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Br, labelHead)); - - // loop body - Instruction labelBody = worker.Create(OpCodes.Nop); - worker.Append(labelBody); - - // writer.Write(value.Array[i + value.Offset]); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldarga_S, (byte)1)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.ArraySegmentArrayReference.MakeHostInstanceGeneric(genericInstance))); - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldarga_S, (byte)1)); - worker.Append(worker.Create(OpCodes.Call, WeaverTypes.ArraySegmentOffsetReference.MakeHostInstanceGeneric(genericInstance))); - worker.Append(worker.Create(OpCodes.Add)); - worker.Append(worker.Create(OpCodes.Ldelema, elementType)); - worker.Append(worker.Create(OpCodes.Ldobj, elementType)); - worker.Append(worker.Create(OpCodes.Call, elementWriteFunc)); - - - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldc_I4_1)); - worker.Append(worker.Create(OpCodes.Add)); - worker.Append(worker.Create(OpCodes.Stloc_1)); - - // end for loop - worker.Append(labelHead); - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Blt, labelBody)); - - // return - worker.Append(worker.Create(OpCodes.Ret)); - return writerFunc; + // + + Instruction labelNotNull = worker.Create(OpCodes.Nop); + worker.Emit(OpCodes.Ldarg_1); + worker.Emit(OpCodes.Brtrue, labelNotNull); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldc_I4_0); + worker.Emit(OpCodes.Call, GetWriteFunc(weaverTypes.Import(), ref WeavingFailed)); + worker.Emit(OpCodes.Ret); + worker.Append(labelNotNull); + + // write.WriteBoolean(true); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldc_I4_1); + worker.Emit(OpCodes.Call, GetWriteFunc(weaverTypes.Import(), ref WeavingFailed)); } - static MethodDefinition GenerateListWriteFunc(TypeReference variable, int recursionCount) + // Find all fields in type and write them + bool WriteAllFields(TypeReference variable, ILProcessor worker, ref bool WeavingFailed) { - GenericInstanceType genericInstance = (GenericInstanceType)variable; - TypeReference elementType = genericInstance.GenericArguments[0]; - MethodReference elementWriteFunc = GetWriteFunc(elementType, recursionCount + 1); - MethodReference intWriterFunc = GetWriteFunc(WeaverTypes.int32Type); - - if (elementWriteFunc == null) + foreach (FieldDefinition field in variable.FindAllPublicFields()) { - Weaver.Error($"Cannot generate writer for List because element {elementType.Name} does not have a writer. Use a supported type or provide a custom writer", variable); - return null; - } + MethodReference writeFunc = GetWriteFunc(field.FieldType, ref WeavingFailed); + // need this null check till later PR when GetWriteFunc throws exception instead + if (writeFunc == null) { return false; } - string functionName = "_WriteList_" + elementType.Name + "_"; - if (variable.DeclaringType != null) - { - functionName += variable.DeclaringType.Name; - } - else - { - functionName += "None"; - } + FieldReference fieldRef = assembly.MainModule.ImportReference(field); - // create new writer for this type - MethodDefinition writerFunc = new MethodDefinition(functionName, - MethodAttributes.Public | - MethodAttributes.Static | - MethodAttributes.HideBySig, - WeaverTypes.voidType); - - writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(WeaverTypes.NetworkWriterType))); - writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, variable)); - - writerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - writerFunc.Body.Variables.Add(new VariableDefinition(WeaverTypes.int32Type)); - writerFunc.Body.InitLocals = true; + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_1); + worker.Emit(OpCodes.Ldfld, fieldRef); + worker.Emit(OpCodes.Call, writeFunc); + } - ILProcessor worker = writerFunc.Body.GetILProcessor(); + return true; + } - // if (value == null) - // { - // writer.WritePackedInt32(-1); - // return; - // } - Instruction labelNull = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Brtrue, labelNull)); + MethodDefinition GenerateCollectionWriter(TypeReference variable, TypeReference elementType, string writerFunction, ref bool WeavingFailed) + { - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldc_I4_M1)); - worker.Append(worker.Create(OpCodes.Call, intWriterFunc)); - worker.Append(worker.Create(OpCodes.Ret)); + MethodDefinition writerFunc = GenerateWriterFunc(variable); - // else not null - worker.Append(labelNull); + MethodReference elementWriteFunc = GetWriteFunc(elementType, ref WeavingFailed); + MethodReference intWriterFunc = GetWriteFunc(weaverTypes.Import(), ref WeavingFailed); - MethodReference countref = WeaverTypes.ListCountReference.MakeHostInstanceGeneric(genericInstance); + // need this null check till later PR when GetWriteFunc throws exception instead + if (elementWriteFunc == null) + { + Log.Error($"Cannot generate writer for {variable}. Use a supported type or provide a custom writer", variable); + WeavingFailed = true; + return writerFunc; + } - // int count = value.Count; - worker.Append(worker.Create(OpCodes.Ldarg_1)); - worker.Append(worker.Create(OpCodes.Call, countref)); - worker.Append(worker.Create(OpCodes.Stloc_0)); + ModuleDefinition module = assembly.MainModule; + TypeReference readerExtensions = module.ImportReference(typeof(NetworkWriterExtensions)); + MethodReference collectionWriter = Resolvers.ResolveMethod(readerExtensions, assembly, Log, writerFunction, ref WeavingFailed); - // writer.WritePackedInt32(count); - worker.Append(worker.Create(OpCodes.Ldarg_0)); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Call, intWriterFunc)); + GenericInstanceMethod methodRef = new GenericInstanceMethod(collectionWriter); + methodRef.GenericArguments.Add(elementType); - // Loop through the List and call the writer for each element. - // generates this: - // for (int i=0; i < count; i++) - // { - // writer.WriteT(value[i]); - // } - worker.Append(worker.Create(OpCodes.Ldc_I4_0)); - worker.Append(worker.Create(OpCodes.Stloc_1)); - Instruction labelHead = worker.Create(OpCodes.Nop); - worker.Append(worker.Create(OpCodes.Br, labelHead)); + // generates + // reader.WriteArray(array); - // loop body - Instruction labelBody = worker.Create(OpCodes.Nop); - worker.Append(labelBody); + ILProcessor worker = writerFunc.Body.GetILProcessor(); + worker.Emit(OpCodes.Ldarg_0); // writer + worker.Emit(OpCodes.Ldarg_1); // collection - MethodReference getItem = WeaverTypes.ListGetItemReference.MakeHostInstanceGeneric(genericInstance); + worker.Emit(OpCodes.Call, methodRef); // WriteArray - // writer.Write(value[i]); - worker.Append(worker.Create(OpCodes.Ldarg_0)); // writer - worker.Append(worker.Create(OpCodes.Ldarg_1)); // value - worker.Append(worker.Create(OpCodes.Ldloc_1)); // i - worker.Append(worker.Create(OpCodes.Call, getItem)); //get_Item - worker.Append(worker.Create(OpCodes.Call, elementWriteFunc)); // Write + worker.Emit(OpCodes.Ret); + return writerFunc; + } - // end for loop + // Save a delegate for each one of the writers into Writer{T}.write + internal void InitializeWriters(ILProcessor worker) + { + ModuleDefinition module = assembly.MainModule; - // for loop i++ - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldc_I4_1)); - worker.Append(worker.Create(OpCodes.Add)); - worker.Append(worker.Create(OpCodes.Stloc_1)); + TypeReference genericWriterClassRef = module.ImportReference(typeof(Writer<>)); - worker.Append(labelHead); - // for loop i < count - worker.Append(worker.Create(OpCodes.Ldloc_1)); - worker.Append(worker.Create(OpCodes.Ldloc_0)); - worker.Append(worker.Create(OpCodes.Blt, labelBody)); + System.Reflection.FieldInfo fieldInfo = typeof(Writer<>).GetField(nameof(Writer.write)); + FieldReference fieldRef = module.ImportReference(fieldInfo); + TypeReference networkWriterRef = module.ImportReference(typeof(NetworkWriter)); + TypeReference actionRef = module.ImportReference(typeof(Action<,>)); + MethodReference actionConstructorRef = module.ImportReference(typeof(Action<,>).GetConstructors()[0]); - // return - worker.Append(worker.Create(OpCodes.Ret)); - return writerFunc; + foreach (KeyValuePair kvp in writeFuncs) + { + TypeReference targetType = kvp.Key; + MethodReference writeFunc = kvp.Value; + + // create a Action delegate + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ldftn, writeFunc); + GenericInstanceType actionGenericInstance = actionRef.MakeGenericInstanceType(networkWriterRef, targetType); + MethodReference actionRefInstance = actionConstructorRef.MakeHostInstanceGeneric(assembly.MainModule, actionGenericInstance); + worker.Emit(OpCodes.Newobj, actionRefInstance); + + // save it in Writer.write + GenericInstanceType genericInstance = genericWriterClassRef.MakeGenericInstanceType(targetType); + FieldReference specializedField = fieldRef.SpecializeField(assembly.MainModule, genericInstance); + worker.Emit(OpCodes.Stsfld, specializedField); + } } } } diff --git a/Assets/ImportedAssets/Mirror/Editor/Weaver/Writers.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Weaver/Writers.cs.meta index 3769f7fdb5..bfa70b1c02 100644 --- a/Assets/ImportedAssets/Mirror/Editor/Weaver/Writers.cs.meta +++ b/Assets/ImportedAssets/Mirror/Editor/Weaver/Writers.cs.meta @@ -9,3 +9,10 @@ MonoImporter: userData: assetBundleName: assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Weaver/Writers.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Editor/Welcome.cs b/Assets/ImportedAssets/Mirror/Editor/Welcome.cs new file mode 100644 index 0000000000..14e57bce10 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Welcome.cs @@ -0,0 +1,23 @@ +// Shows either a welcome message, only once per session. +#if UNITY_EDITOR +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + static class Welcome + { + [InitializeOnLoadMethod] + static void OnInitializeOnLoad() + { + // InitializeOnLoad is called on start and after each rebuild, + // but we only want to show this once per editor session. + if (!SessionState.GetBool("MIRROR_WELCOME", false)) + { + SessionState.SetBool("MIRROR_WELCOME", true); + Debug.Log("Mirror | mirror-networking.com | discord.gg/N9QVxbM"); + } + } + } +} +#endif diff --git a/Assets/ImportedAssets/Mirror/Editor/Welcome.cs.meta b/Assets/ImportedAssets/Mirror/Editor/Welcome.cs.meta new file mode 100644 index 0000000000..f4aa38bcbe --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Editor/Welcome.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 180619c3887314f56bf396769c0a23ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.8.0 + assetPath: Assets/ImportedAssets/Mirror/Editor/Welcome.cs + uploadId: 670838 diff --git a/Assets/ImportedAssets/Mirror/Examples.meta b/Assets/ImportedAssets/Mirror/Examples.meta deleted file mode 100644 index b594a81950..0000000000 --- a/Assets/ImportedAssets/Mirror/Examples.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: a08b1f591326642d1b140fc818c9c6b1 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Hosting.meta b/Assets/ImportedAssets/Mirror/Hosting.meta new file mode 100644 index 0000000000..43de0c569b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b13bce90dfb604c2d9170e3640f59ad9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap.meta new file mode 100644 index 0000000000..c4f5fd2c18 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b7c51dc3e45095f4a8a960150837fe7b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies.meta new file mode 100644 index 0000000000..1a9b918536 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 14024ce6d2e64d5ba58ab20409ac648f +timeCreated: 1701785018 \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpEncoder.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpEncoder.cs new file mode 100644 index 0000000000..6c4b15d4ff --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpEncoder.cs @@ -0,0 +1,704 @@ +// MIRROR CHANGE: drop in Codice.Utils HttpUtility subset to not depend on Unity's plastic scm package +// SOURCE: Unity Plastic SCM package + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; + +namespace Edgegap.Codice.Utils // MIRROR CHANGE: namespace Edgegap.* to not collide if anyone has Plastic SCM installed already +{ + public class HttpEncoder + { + private static char[] hexChars = "0123456789abcdef".ToCharArray(); + private static object entitiesLock = new object(); + private static SortedDictionary entities; + private static HttpEncoder defaultEncoder = new HttpEncoder(); + private static HttpEncoder currentEncoder = HttpEncoder.defaultEncoder; + + private static IDictionary Entities + { + get + { + lock (HttpEncoder.entitiesLock) + { + if (HttpEncoder.entities == null) + HttpEncoder.InitEntities(); + return (IDictionary) HttpEncoder.entities; + } + } + } + + public static HttpEncoder Current + { + get => HttpEncoder.currentEncoder; + set => HttpEncoder.currentEncoder = value != null ? value : throw new ArgumentNullException(nameof (value)); + } + + public static HttpEncoder Default => HttpEncoder.defaultEncoder; + + protected internal virtual void HeaderNameValueEncode( + string headerName, + string headerValue, + out string encodedHeaderName, + out string encodedHeaderValue) + { + encodedHeaderName = !string.IsNullOrEmpty(headerName) ? HttpEncoder.EncodeHeaderString(headerName) : headerName; + if (string.IsNullOrEmpty(headerValue)) + encodedHeaderValue = headerValue; + else + encodedHeaderValue = HttpEncoder.EncodeHeaderString(headerValue); + } + + private static void StringBuilderAppend(string s, ref StringBuilder sb) + { + if (sb == null) + sb = new StringBuilder(s); + else + sb.Append(s); + } + + private static string EncodeHeaderString(string input) + { + StringBuilder sb = (StringBuilder) null; + for (int index = 0; index < input.Length; ++index) + { + char ch = input[index]; + if (ch < ' ' && ch != '\t' || ch == '\u007F') + HttpEncoder.StringBuilderAppend(string.Format("%{0:x2}", (object) (int) ch), ref sb); + } + return sb != null ? sb.ToString() : input; + } + + protected internal virtual void HtmlAttributeEncode(string value, TextWriter output) + { + if (output == null) + throw new ArgumentNullException(nameof (output)); + if (string.IsNullOrEmpty(value)) + return; + output.Write(HttpEncoder.HtmlAttributeEncode(value)); + } + + protected internal virtual void HtmlDecode(string value, TextWriter output) + { + if (output == null) + throw new ArgumentNullException(nameof (output)); + output.Write(HttpEncoder.HtmlDecode(value)); + } + + protected internal virtual void HtmlEncode(string value, TextWriter output) + { + if (output == null) + throw new ArgumentNullException(nameof (output)); + output.Write(HttpEncoder.HtmlEncode(value)); + } + + protected internal virtual byte[] UrlEncode(byte[] bytes, int offset, int count) => HttpEncoder.UrlEncodeToBytes(bytes, offset, count); + + protected internal virtual string UrlPathEncode(string value) + { + if (string.IsNullOrEmpty(value)) + return value; + MemoryStream result = new MemoryStream(); + int length = value.Length; + for (int index = 0; index < length; ++index) + HttpEncoder.UrlPathEncodeChar(value[index], (Stream) result); + return Encoding.ASCII.GetString(result.ToArray()); + } + + internal static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count) + { + int num1 = bytes != null ? bytes.Length : throw new ArgumentNullException(nameof (bytes)); + if (num1 == 0) + return new byte[0]; + if (offset < 0 || offset >= num1) + throw new ArgumentOutOfRangeException(nameof (offset)); + if (count < 0 || count > num1 - offset) + throw new ArgumentOutOfRangeException(nameof (count)); + MemoryStream result = new MemoryStream(count); + int num2 = offset + count; + for (int index = offset; index < num2; ++index) + HttpEncoder.UrlEncodeChar((char) bytes[index], (Stream) result, false); + return result.ToArray(); + } + + internal static string HtmlEncode(string s) + { + switch (s) + { + case "": + return string.Empty; + case null: + return (string) null; + default: + bool flag = false; + for (int index = 0; index < s.Length; ++index) + { + char ch = s[index]; + if (ch == '&' || ch == '"' || ch == '<' || ch == '>' || ch > '\u009F' || ch == '\'') + { + flag = true; + break; + } + } + if (!flag) + return s; + StringBuilder stringBuilder = new StringBuilder(); + int length = s.Length; + for (int index = 0; index < length; ++index) + { + char ch = s[index]; + switch (ch) + { + case '"': + stringBuilder.Append("""); + break; + case '&': + stringBuilder.Append("&"); + break; + case '\'': + stringBuilder.Append("'"); + break; + case '<': + stringBuilder.Append("<"); + break; + case '>': + stringBuilder.Append(">"); + break; + case '<': + stringBuilder.Append("<"); + break; + case '>': + stringBuilder.Append(">"); + break; + default: + if (ch > '\u009F' && ch < 'Ā') + { + stringBuilder.Append("&#"); + stringBuilder.Append(((int) ch).ToString((IFormatProvider) CultureInfo.InvariantCulture)); + stringBuilder.Append(";"); + break; + } + stringBuilder.Append(ch); + break; + } + } + return stringBuilder.ToString(); + } + } + + internal static string HtmlAttributeEncode(string s) + { + if (string.IsNullOrEmpty(s)) + return string.Empty; + bool flag = false; + for (int index = 0; index < s.Length; ++index) + { + char ch = s[index]; + int num; + switch (ch) + { + case '"': + case '&': + case '<': + num = 0; + break; + default: + num = ch != '\'' ? 1 : 0; + break; + } + if (num == 0) + { + flag = true; + break; + } + } + if (!flag) + return s; + StringBuilder stringBuilder = new StringBuilder(); + int length = s.Length; + for (int index = 0; index < length; ++index) + { + char ch = s[index]; + switch (ch) + { + case '"': + stringBuilder.Append("""); + break; + case '&': + stringBuilder.Append("&"); + break; + case '\'': + stringBuilder.Append("'"); + break; + case '<': + stringBuilder.Append("<"); + break; + default: + stringBuilder.Append(ch); + break; + } + } + return stringBuilder.ToString(); + } + + internal static string HtmlDecode(string s) + { + switch (s) + { + case "": + return string.Empty; + case null: + return (string) null; + default: + if (s.IndexOf('&') == -1) + return s; + StringBuilder stringBuilder1 = new StringBuilder(); + StringBuilder stringBuilder2 = new StringBuilder(); + StringBuilder stringBuilder3 = new StringBuilder(); + int length = s.Length; + int num1 = 0; + int num2 = 0; + bool flag1 = false; + bool flag2 = false; + for (int index = 0; index < length; ++index) + { + char ch = s[index]; + if (num1 == 0) + { + if (ch == '&') + { + stringBuilder2.Append(ch); + stringBuilder1.Append(ch); + num1 = 1; + } + else + stringBuilder3.Append(ch); + } + else if (ch == '&') + { + num1 = 1; + if (flag2) + { + stringBuilder2.Append(num2.ToString((IFormatProvider) CultureInfo.InvariantCulture)); + flag2 = false; + } + stringBuilder3.Append(stringBuilder2.ToString()); + stringBuilder2.Length = 0; + stringBuilder2.Append('&'); + } + else + { + switch (num1) + { + case 1: + if (ch == ';') + { + num1 = 0; + stringBuilder3.Append(stringBuilder2.ToString()); + stringBuilder3.Append(ch); + stringBuilder2.Length = 0; + break; + } + num2 = 0; + flag1 = false; + num1 = ch == '#' ? 3 : 2; + stringBuilder2.Append(ch); + stringBuilder1.Append(ch); + break; + case 2: + stringBuilder2.Append(ch); + if (ch == ';') + { + string str = stringBuilder2.ToString(); + if (str.Length > 1 && HttpEncoder.Entities.ContainsKey(str.Substring(1, str.Length - 2))) + str = HttpEncoder.Entities[str.Substring(1, str.Length - 2)].ToString(); + stringBuilder3.Append(str); + num1 = 0; + stringBuilder2.Length = 0; + stringBuilder1.Length = 0; + break; + } + break; + case 3: + if (ch == ';') + { + if (num2 == 0) + stringBuilder3.Append(stringBuilder1.ToString() + ";"); + else if (num2 > (int) ushort.MaxValue) + { + stringBuilder3.Append("&#"); + stringBuilder3.Append(num2.ToString((IFormatProvider) CultureInfo.InvariantCulture)); + stringBuilder3.Append(";"); + } + else + stringBuilder3.Append((char) num2); + num1 = 0; + stringBuilder2.Length = 0; + stringBuilder1.Length = 0; + flag2 = false; + } + else if (flag1 && Uri.IsHexDigit(ch)) + { + num2 = num2 * 16 + Uri.FromHex(ch); + flag2 = true; + stringBuilder1.Append(ch); + } + else if (char.IsDigit(ch)) + { + num2 = num2 * 10 + ((int) ch - 48); + flag2 = true; + stringBuilder1.Append(ch); + } + else if (num2 == 0 && (ch == 'x' || ch == 'X')) + { + flag1 = true; + stringBuilder1.Append(ch); + } + else + { + num1 = 2; + if (flag2) + { + stringBuilder2.Append(num2.ToString((IFormatProvider) CultureInfo.InvariantCulture)); + flag2 = false; + } + stringBuilder2.Append(ch); + } + break; + } + } + } + if (stringBuilder2.Length > 0) + stringBuilder3.Append(stringBuilder2.ToString()); + else if (flag2) + stringBuilder3.Append(num2.ToString((IFormatProvider) CultureInfo.InvariantCulture)); + return stringBuilder3.ToString(); + } + } + + internal static bool NotEncoded(char c) => c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_'; + + internal static void UrlEncodeChar(char c, Stream result, bool isUnicode) + { + if (c > 'ÿ') + { + int num = (int) c; + result.WriteByte((byte) 37); + result.WriteByte((byte) 117); + int index1 = num >> 12; + result.WriteByte((byte) HttpEncoder.hexChars[index1]); + int index2 = num >> 8 & 15; + result.WriteByte((byte) HttpEncoder.hexChars[index2]); + int index3 = num >> 4 & 15; + result.WriteByte((byte) HttpEncoder.hexChars[index3]); + int index4 = num & 15; + result.WriteByte((byte) HttpEncoder.hexChars[index4]); + } + else if (c > ' ' && HttpEncoder.NotEncoded(c)) + result.WriteByte((byte) c); + else if (c == ' ') + result.WriteByte((byte) 43); + else if (c < '0' || c < 'A' && c > '9' || c > 'Z' && c < 'a' || c > 'z') + { + if (isUnicode && c > '\u007F') + { + result.WriteByte((byte) 37); + result.WriteByte((byte) 117); + result.WriteByte((byte) 48); + result.WriteByte((byte) 48); + } + else + result.WriteByte((byte) 37); + int index5 = (int) c >> 4; + result.WriteByte((byte) HttpEncoder.hexChars[index5]); + int index6 = (int) c & 15; + result.WriteByte((byte) HttpEncoder.hexChars[index6]); + } + else + result.WriteByte((byte) c); + } + + internal static void UrlPathEncodeChar(char c, Stream result) + { + if (c < '!' || c > '~') + { + byte[] bytes = Encoding.UTF8.GetBytes(c.ToString()); + for (int index1 = 0; index1 < bytes.Length; ++index1) + { + result.WriteByte((byte) 37); + int index2 = (int) bytes[index1] >> 4; + result.WriteByte((byte) HttpEncoder.hexChars[index2]); + int index3 = (int) bytes[index1] & 15; + result.WriteByte((byte) HttpEncoder.hexChars[index3]); + } + } + else if (c == ' ') + { + result.WriteByte((byte) 37); + result.WriteByte((byte) 50); + result.WriteByte((byte) 48); + } + else + result.WriteByte((byte) c); + } + + private static void InitEntities() + { + HttpEncoder.entities = new SortedDictionary((IComparer) StringComparer.Ordinal); + HttpEncoder.entities.Add("nbsp", ' '); + HttpEncoder.entities.Add("iexcl", '¡'); + HttpEncoder.entities.Add("cent", '¢'); + HttpEncoder.entities.Add("pound", '£'); + HttpEncoder.entities.Add("curren", '¤'); + HttpEncoder.entities.Add("yen", '¥'); + HttpEncoder.entities.Add("brvbar", '¦'); + HttpEncoder.entities.Add("sect", '§'); + HttpEncoder.entities.Add("uml", '¨'); + HttpEncoder.entities.Add("copy", '©'); + HttpEncoder.entities.Add("ordf", 'ª'); + HttpEncoder.entities.Add("laquo", '«'); + HttpEncoder.entities.Add("not", '¬'); + HttpEncoder.entities.Add("shy", '\u00AD'); + HttpEncoder.entities.Add("reg", '®'); + HttpEncoder.entities.Add("macr", '¯'); + HttpEncoder.entities.Add("deg", '°'); + HttpEncoder.entities.Add("plusmn", '±'); + HttpEncoder.entities.Add("sup2", '\u00B2'); + HttpEncoder.entities.Add("sup3", '\u00B3'); + HttpEncoder.entities.Add("acute", '´'); + HttpEncoder.entities.Add("micro", 'µ'); + HttpEncoder.entities.Add("para", '¶'); + HttpEncoder.entities.Add("middot", '·'); + HttpEncoder.entities.Add("cedil", '¸'); + HttpEncoder.entities.Add("sup1", '\u00B9'); + HttpEncoder.entities.Add("ordm", 'º'); + HttpEncoder.entities.Add("raquo", '»'); + HttpEncoder.entities.Add("frac14", '\u00BC'); + HttpEncoder.entities.Add("frac12", '\u00BD'); + HttpEncoder.entities.Add("frac34", '\u00BE'); + HttpEncoder.entities.Add("iquest", '¿'); + HttpEncoder.entities.Add("Agrave", 'À'); + HttpEncoder.entities.Add("Aacute", 'Á'); + HttpEncoder.entities.Add("Acirc", 'Â'); + HttpEncoder.entities.Add("Atilde", 'Ã'); + HttpEncoder.entities.Add("Auml", 'Ä'); + HttpEncoder.entities.Add("Aring", 'Å'); + HttpEncoder.entities.Add("AElig", 'Æ'); + HttpEncoder.entities.Add("Ccedil", 'Ç'); + HttpEncoder.entities.Add("Egrave", 'È'); + HttpEncoder.entities.Add("Eacute", 'É'); + HttpEncoder.entities.Add("Ecirc", 'Ê'); + HttpEncoder.entities.Add("Euml", 'Ë'); + HttpEncoder.entities.Add("Igrave", 'Ì'); + HttpEncoder.entities.Add("Iacute", 'Í'); + HttpEncoder.entities.Add("Icirc", 'Î'); + HttpEncoder.entities.Add("Iuml", 'Ï'); + HttpEncoder.entities.Add("ETH", 'Ð'); + HttpEncoder.entities.Add("Ntilde", 'Ñ'); + HttpEncoder.entities.Add("Ograve", 'Ò'); + HttpEncoder.entities.Add("Oacute", 'Ó'); + HttpEncoder.entities.Add("Ocirc", 'Ô'); + HttpEncoder.entities.Add("Otilde", 'Õ'); + HttpEncoder.entities.Add("Ouml", 'Ö'); + HttpEncoder.entities.Add("times", '×'); + HttpEncoder.entities.Add("Oslash", 'Ø'); + HttpEncoder.entities.Add("Ugrave", 'Ù'); + HttpEncoder.entities.Add("Uacute", 'Ú'); + HttpEncoder.entities.Add("Ucirc", 'Û'); + HttpEncoder.entities.Add("Uuml", 'Ü'); + HttpEncoder.entities.Add("Yacute", 'Ý'); + HttpEncoder.entities.Add("THORN", 'Þ'); + HttpEncoder.entities.Add("szlig", 'ß'); + HttpEncoder.entities.Add("agrave", 'à'); + HttpEncoder.entities.Add("aacute", 'á'); + HttpEncoder.entities.Add("acirc", 'â'); + HttpEncoder.entities.Add("atilde", 'ã'); + HttpEncoder.entities.Add("auml", 'ä'); + HttpEncoder.entities.Add("aring", 'å'); + HttpEncoder.entities.Add("aelig", 'æ'); + HttpEncoder.entities.Add("ccedil", 'ç'); + HttpEncoder.entities.Add("egrave", 'è'); + HttpEncoder.entities.Add("eacute", 'é'); + HttpEncoder.entities.Add("ecirc", 'ê'); + HttpEncoder.entities.Add("euml", 'ë'); + HttpEncoder.entities.Add("igrave", 'ì'); + HttpEncoder.entities.Add("iacute", 'í'); + HttpEncoder.entities.Add("icirc", 'î'); + HttpEncoder.entities.Add("iuml", 'ï'); + HttpEncoder.entities.Add("eth", 'ð'); + HttpEncoder.entities.Add("ntilde", 'ñ'); + HttpEncoder.entities.Add("ograve", 'ò'); + HttpEncoder.entities.Add("oacute", 'ó'); + HttpEncoder.entities.Add("ocirc", 'ô'); + HttpEncoder.entities.Add("otilde", 'õ'); + HttpEncoder.entities.Add("ouml", 'ö'); + HttpEncoder.entities.Add("divide", '÷'); + HttpEncoder.entities.Add("oslash", 'ø'); + HttpEncoder.entities.Add("ugrave", 'ù'); + HttpEncoder.entities.Add("uacute", 'ú'); + HttpEncoder.entities.Add("ucirc", 'û'); + HttpEncoder.entities.Add("uuml", 'ü'); + HttpEncoder.entities.Add("yacute", 'ý'); + HttpEncoder.entities.Add("thorn", 'þ'); + HttpEncoder.entities.Add("yuml", 'ÿ'); + HttpEncoder.entities.Add("fnof", 'ƒ'); + HttpEncoder.entities.Add("Alpha", 'Α'); + HttpEncoder.entities.Add("Beta", 'Β'); + HttpEncoder.entities.Add("Gamma", 'Γ'); + HttpEncoder.entities.Add("Delta", 'Δ'); + HttpEncoder.entities.Add("Epsilon", 'Ε'); + HttpEncoder.entities.Add("Zeta", 'Ζ'); + HttpEncoder.entities.Add("Eta", 'Η'); + HttpEncoder.entities.Add("Theta", 'Θ'); + HttpEncoder.entities.Add("Iota", 'Ι'); + HttpEncoder.entities.Add("Kappa", 'Κ'); + HttpEncoder.entities.Add("Lambda", 'Λ'); + HttpEncoder.entities.Add("Mu", 'Μ'); + HttpEncoder.entities.Add("Nu", 'Ν'); + HttpEncoder.entities.Add("Xi", 'Ξ'); + HttpEncoder.entities.Add("Omicron", 'Ο'); + HttpEncoder.entities.Add("Pi", 'Π'); + HttpEncoder.entities.Add("Rho", 'Ρ'); + HttpEncoder.entities.Add("Sigma", 'Σ'); + HttpEncoder.entities.Add("Tau", 'Τ'); + HttpEncoder.entities.Add("Upsilon", 'Υ'); + HttpEncoder.entities.Add("Phi", 'Φ'); + HttpEncoder.entities.Add("Chi", 'Χ'); + HttpEncoder.entities.Add("Psi", 'Ψ'); + HttpEncoder.entities.Add("Omega", 'Ω'); + HttpEncoder.entities.Add("alpha", 'α'); + HttpEncoder.entities.Add("beta", 'β'); + HttpEncoder.entities.Add("gamma", 'γ'); + HttpEncoder.entities.Add("delta", 'δ'); + HttpEncoder.entities.Add("epsilon", 'ε'); + HttpEncoder.entities.Add("zeta", 'ζ'); + HttpEncoder.entities.Add("eta", 'η'); + HttpEncoder.entities.Add("theta", 'θ'); + HttpEncoder.entities.Add("iota", 'ι'); + HttpEncoder.entities.Add("kappa", 'κ'); + HttpEncoder.entities.Add("lambda", 'λ'); + HttpEncoder.entities.Add("mu", 'μ'); + HttpEncoder.entities.Add("nu", 'ν'); + HttpEncoder.entities.Add("xi", 'ξ'); + HttpEncoder.entities.Add("omicron", 'ο'); + HttpEncoder.entities.Add("pi", 'π'); + HttpEncoder.entities.Add("rho", 'ρ'); + HttpEncoder.entities.Add("sigmaf", 'ς'); + HttpEncoder.entities.Add("sigma", 'σ'); + HttpEncoder.entities.Add("tau", 'τ'); + HttpEncoder.entities.Add("upsilon", 'υ'); + HttpEncoder.entities.Add("phi", 'φ'); + HttpEncoder.entities.Add("chi", 'χ'); + HttpEncoder.entities.Add("psi", 'ψ'); + HttpEncoder.entities.Add("omega", 'ω'); + HttpEncoder.entities.Add("thetasym", 'ϑ'); + HttpEncoder.entities.Add("upsih", 'ϒ'); + HttpEncoder.entities.Add("piv", 'ϖ'); + HttpEncoder.entities.Add("bull", '•'); + HttpEncoder.entities.Add("hellip", '…'); + HttpEncoder.entities.Add("prime", '′'); + HttpEncoder.entities.Add("Prime", '″'); + HttpEncoder.entities.Add("oline", '‾'); + HttpEncoder.entities.Add("frasl", '⁄'); + HttpEncoder.entities.Add("weierp", '℘'); + HttpEncoder.entities.Add("image", 'ℑ'); + HttpEncoder.entities.Add("real", 'ℜ'); + HttpEncoder.entities.Add("trade", '™'); + HttpEncoder.entities.Add("alefsym", 'ℵ'); + HttpEncoder.entities.Add("larr", '←'); + HttpEncoder.entities.Add("uarr", '↑'); + HttpEncoder.entities.Add("rarr", '→'); + HttpEncoder.entities.Add("darr", '↓'); + HttpEncoder.entities.Add("harr", '↔'); + HttpEncoder.entities.Add("crarr", '↵'); + HttpEncoder.entities.Add("lArr", '⇐'); + HttpEncoder.entities.Add("uArr", '⇑'); + HttpEncoder.entities.Add("rArr", '⇒'); + HttpEncoder.entities.Add("dArr", '⇓'); + HttpEncoder.entities.Add("hArr", '⇔'); + HttpEncoder.entities.Add("forall", '∀'); + HttpEncoder.entities.Add("part", '∂'); + HttpEncoder.entities.Add("exist", '∃'); + HttpEncoder.entities.Add("empty", '∅'); + HttpEncoder.entities.Add("nabla", '∇'); + HttpEncoder.entities.Add("isin", '∈'); + HttpEncoder.entities.Add("notin", '∉'); + HttpEncoder.entities.Add("ni", '∋'); + HttpEncoder.entities.Add("prod", '∏'); + HttpEncoder.entities.Add("sum", '∑'); + HttpEncoder.entities.Add("minus", '−'); + HttpEncoder.entities.Add("lowast", '∗'); + HttpEncoder.entities.Add("radic", '√'); + HttpEncoder.entities.Add("prop", '∝'); + HttpEncoder.entities.Add("infin", '∞'); + HttpEncoder.entities.Add("ang", '∠'); + HttpEncoder.entities.Add("and", '∧'); + HttpEncoder.entities.Add("or", '∨'); + HttpEncoder.entities.Add("cap", '∩'); + HttpEncoder.entities.Add("cup", '∪'); + HttpEncoder.entities.Add("int", '∫'); + HttpEncoder.entities.Add("there4", '∴'); + HttpEncoder.entities.Add("sim", '∼'); + HttpEncoder.entities.Add("cong", '≅'); + HttpEncoder.entities.Add("asymp", '≈'); + HttpEncoder.entities.Add("ne", '≠'); + HttpEncoder.entities.Add("equiv", '≡'); + HttpEncoder.entities.Add("le", '≤'); + HttpEncoder.entities.Add("ge", '≥'); + HttpEncoder.entities.Add("sub", '⊂'); + HttpEncoder.entities.Add("sup", '⊃'); + HttpEncoder.entities.Add("nsub", '⊄'); + HttpEncoder.entities.Add("sube", '⊆'); + HttpEncoder.entities.Add("supe", '⊇'); + HttpEncoder.entities.Add("oplus", '⊕'); + HttpEncoder.entities.Add("otimes", '⊗'); + HttpEncoder.entities.Add("perp", '⊥'); + HttpEncoder.entities.Add("sdot", '⋅'); + HttpEncoder.entities.Add("lceil", '⌈'); + HttpEncoder.entities.Add("rceil", '⌉'); + HttpEncoder.entities.Add("lfloor", '⌊'); + HttpEncoder.entities.Add("rfloor", '⌋'); + HttpEncoder.entities.Add("lang", '〈'); + HttpEncoder.entities.Add("rang", '〉'); + HttpEncoder.entities.Add("loz", '◊'); + HttpEncoder.entities.Add("spades", '♠'); + HttpEncoder.entities.Add("clubs", '♣'); + HttpEncoder.entities.Add("hearts", '♥'); + HttpEncoder.entities.Add("diams", '♦'); + HttpEncoder.entities.Add("quot", '"'); + HttpEncoder.entities.Add("amp", '&'); + HttpEncoder.entities.Add("lt", '<'); + HttpEncoder.entities.Add("gt", '>'); + HttpEncoder.entities.Add("OElig", 'Œ'); + HttpEncoder.entities.Add("oelig", 'œ'); + HttpEncoder.entities.Add("Scaron", 'Š'); + HttpEncoder.entities.Add("scaron", 'š'); + HttpEncoder.entities.Add("Yuml", 'Ÿ'); + HttpEncoder.entities.Add("circ", 'ˆ'); + HttpEncoder.entities.Add("tilde", '˜'); + HttpEncoder.entities.Add("ensp", ' '); + HttpEncoder.entities.Add("emsp", ' '); + HttpEncoder.entities.Add("thinsp", ' '); + HttpEncoder.entities.Add("zwnj", '\u200C'); + HttpEncoder.entities.Add("zwj", '\u200D'); + HttpEncoder.entities.Add("lrm", '\u200E'); + HttpEncoder.entities.Add("rlm", '\u200F'); + HttpEncoder.entities.Add("ndash", '–'); + HttpEncoder.entities.Add("mdash", '—'); + HttpEncoder.entities.Add("lsquo", '‘'); + HttpEncoder.entities.Add("rsquo", '’'); + HttpEncoder.entities.Add("sbquo", '‚'); + HttpEncoder.entities.Add("ldquo", '“'); + HttpEncoder.entities.Add("rdquo", '”'); + HttpEncoder.entities.Add("bdquo", '„'); + HttpEncoder.entities.Add("dagger", '†'); + HttpEncoder.entities.Add("Dagger", '‡'); + HttpEncoder.entities.Add("permil", '‰'); + HttpEncoder.entities.Add("lsaquo", '‹'); + HttpEncoder.entities.Add("rsaquo", '›'); + HttpEncoder.entities.Add("euro", '€'); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpEncoder.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpEncoder.cs.meta new file mode 100644 index 0000000000..f20202cbdb --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpEncoder.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 3c9f699c227f48e381db521abe59c2e1 +timeCreated: 1701789490 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpEncoder.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpUtility.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpUtility.cs new file mode 100644 index 0000000000..ea17c9e3d8 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpUtility.cs @@ -0,0 +1,230 @@ +// MIRROR CHANGE: drop in Codice.Utils HttpUtility subset to not depend on Unity's plastic scm package +// SOURCE: Unity Plastic SCM package + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.IO; +using System.Text; + +namespace Edgegap.Codice.Utils // MIRROR CHANGE: namespace Edgegap.* to not collide if anyone has Plastic SCM installed already +{ + public sealed class HttpUtility + { + private static void WriteCharBytes(IList buf, char ch, Encoding e) + { + if (ch > 'ÿ') + { + Encoding encoding = e; + char[] chars = new char[1]{ ch }; + foreach (byte num in encoding.GetBytes(chars)) + buf.Add((object) num); + } + else + buf.Add((object) (byte) ch); + } + + public static string UrlDecode(string s, Encoding e) + { + if (null == s) + return (string) null; + if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1) + return s; + if (e == null) + e = Encoding.UTF8; + long length = (long) s.Length; + List buf = new List(); + for (int index = 0; (long) index < length; ++index) + { + char ch = s[index]; + if (ch == '%' && (long) (index + 2) < length && s[index + 1] != '%') + { + if (s[index + 1] == 'u' && (long) (index + 5) < length) + { + int num = HttpUtility.GetChar(s, index + 2, 4); + if (num != -1) + { + HttpUtility.WriteCharBytes((IList) buf, (char) num, e); + index += 5; + } + else + HttpUtility.WriteCharBytes((IList) buf, '%', e); + } + else + { + int num; + if ((num = HttpUtility.GetChar(s, index + 1, 2)) != -1) + { + HttpUtility.WriteCharBytes((IList) buf, (char) num, e); + index += 2; + } + else + HttpUtility.WriteCharBytes((IList) buf, '%', e); + } + } + else if (ch == '+') + HttpUtility.WriteCharBytes((IList) buf, ' ', e); + else + HttpUtility.WriteCharBytes((IList) buf, ch, e); + } + byte[] array = buf.ToArray(); + return e.GetString(array); + } + + private static int GetInt(byte b) + { + char ch = (char) b; + if (ch >= '0' && ch <= '9') + return (int) ch - 48; + if (ch >= 'a' && ch <= 'f') + return (int) ch - 97 + 10; + return ch >= 'A' && ch <= 'F' ? (int) ch - 65 + 10 : -1; + } + + private static int GetChar(string str, int offset, int length) + { + int num1 = 0; + int num2 = length + offset; + for (int index = offset; index < num2; ++index) + { + char b = str[index]; + if (b > '\u007F') + return -1; + int num3 = HttpUtility.GetInt((byte) b); + if (num3 == -1) + return -1; + num1 = (num1 << 4) + num3; + } + return num1; + } + + public static string UrlEncode(string str) => HttpUtility.UrlEncode(str, Encoding.UTF8); + + public static string UrlEncode(string s, Encoding Enc) + { + if (s == null) + return (string) null; + if (s == string.Empty) + return string.Empty; + bool flag = false; + int length = s.Length; + for (int index = 0; index < length; ++index) + { + char c = s[index]; + if ((c < '0' || c < 'A' && c > '9' || c > 'Z' && c < 'a' || c > 'z') && !HttpEncoder.NotEncoded(c)) + { + flag = true; + break; + } + } + if (!flag) + return s; + byte[] bytes1 = new byte[Enc.GetMaxByteCount(s.Length)]; + int bytes2 = Enc.GetBytes(s, 0, s.Length, bytes1, 0); + return Encoding.ASCII.GetString(HttpUtility.UrlEncodeToBytes(bytes1, 0, bytes2)); + } + + public static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count) => bytes == null ? (byte[]) null : HttpEncoder.Current.UrlEncode(bytes, offset, count); + + public static string HtmlDecode(string s) + { + if (s == null) + return (string) null; + using (StringWriter output = new StringWriter()) + { + HttpEncoder.Current.HtmlDecode(s, (TextWriter) output); + return output.ToString(); + } + } + + public static NameValueCollection ParseQueryString(string query) => HttpUtility.ParseQueryString(query, Encoding.UTF8); + + public static NameValueCollection ParseQueryString( + string query, + Encoding encoding) + { + if (query == null) + throw new ArgumentNullException(nameof (query)); + if (encoding == null) + throw new ArgumentNullException(nameof (encoding)); + if (query.Length == 0 || query.Length == 1 && query[0] == '?') + return (NameValueCollection) new HttpUtility.HttpQSCollection(); + if (query[0] == '?') + query = query.Substring(1); + NameValueCollection result = (NameValueCollection) new HttpUtility.HttpQSCollection(); + HttpUtility.ParseQueryString(query, encoding, result); + return result; + } + + internal static void ParseQueryString( + string query, + Encoding encoding, + NameValueCollection result) + { + if (query.Length == 0) + return; + string str1 = HttpUtility.HtmlDecode(query); + int length = str1.Length; + int num1 = 0; + bool flag = true; + while (num1 <= length) + { + int startIndex = -1; + int num2 = -1; + for (int index = num1; index < length; ++index) + { + if (startIndex == -1 && str1[index] == '=') + startIndex = index + 1; + else if (str1[index] == '&') + { + num2 = index; + break; + } + } + if (flag) + { + flag = false; + if (str1[num1] == '?') + ++num1; + } + string name; + if (startIndex == -1) + { + name = (string) null; + startIndex = num1; + } + else + name = HttpUtility.UrlDecode(str1.Substring(num1, startIndex - num1 - 1), encoding); + if (num2 < 0) + { + num1 = -1; + num2 = str1.Length; + } + else + num1 = num2 + 1; + string str2 = HttpUtility.UrlDecode(str1.Substring(startIndex, num2 - startIndex), encoding); + result.Add(name, str2); + if (num1 == -1) + break; + } + } + + private sealed class HttpQSCollection : NameValueCollection + { + public override string ToString() + { + int count = this.Count; + if (count == 0) + return ""; + StringBuilder stringBuilder = new StringBuilder(); + string[] allKeys = this.AllKeys; + for (int index = 0; index < count; ++index) + stringBuilder.AppendFormat("{0}={1}&", (object) allKeys[index], (object) HttpUtility.UrlEncode(this[allKeys[index]])); + if (stringBuilder.Length > 0) + --stringBuilder.Length; + return stringBuilder.ToString(); + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpUtility.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpUtility.cs.meta new file mode 100644 index 0000000000..dcc9f93bb7 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpUtility.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6f83f468a8b546fd92606db56038f9e6 +timeCreated: 1701785025 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Dependencies/HttpUtility.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor.meta new file mode 100644 index 0000000000..e5593273f5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 635b395f47dc9f742b4d71144921bb0d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api.meta new file mode 100644 index 0000000000..bb66b470b0 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6d2a4589d6738cb4b82bb1ceebd1453f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapApiBase.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapApiBase.cs new file mode 100644 index 0000000000..fd04901899 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapApiBase.cs @@ -0,0 +1,280 @@ +using System; +using System.Collections.Specialized; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +// using Codice.Utils; // MIRROR CHANGE +using Edgegap.Codice.Utils; // MIRROR CHANGE +using UnityEngine; + +namespace Edgegap.Editor.Api +{ + /// + /// Handles base URL and common methods for all Edgegap APIs. + /// + public abstract class EdgegapApiBase + { + #region Vars + private readonly HttpClient _httpClient = new HttpClient(); // Base address set // MIRROR CHANGE: Unity 2020 support + protected ApiEnvironment SelectedApiEnvironment { get; } + protected EdgegapWindowMetadata.LogLevel LogLevel { get; set; } + protected bool IsLogLevelDebug => LogLevel == EdgegapWindowMetadata.LogLevel.Debug; + + /// Based on SelectedApiEnvironment. + /// + private string GetBaseUrl() => + SelectedApiEnvironment == ApiEnvironment.Staging + ? ApiEnvironment.Staging.GetApiUrl() + : ApiEnvironment.Console.GetApiUrl(); + #endregion // Vars + + + /// "console" || "staging-console"? + /// Without the "token " prefix, although we'll clear this if present + /// You may want more-verbose logs other than errs + protected EdgegapApiBase( + ApiEnvironment apiEnvironment, + string apiToken, + EdgegapWindowMetadata.LogLevel logLevel = EdgegapWindowMetadata.LogLevel.Error) + { + this.SelectedApiEnvironment = apiEnvironment; + + this._httpClient.BaseAddress = new Uri($"{GetBaseUrl()}/"); + this._httpClient.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue("application/json")); + + string cleanedApiToken = apiToken.Replace("token ", ""); // We already prefixed token below + this._httpClient.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("token", cleanedApiToken); + + this.LogLevel = logLevel; + } + + + #region HTTP Requests + /// + /// POST | We already added "https://api.edgegap.com/" (or similar) BaseAddress via constructor. + /// + /// + /// Serialize to your model via Newtonsoft + /// + /// - Success => returns HttpResponseMessage result + /// - Error => Catches errs => returns null (no rethrow) + /// + protected async Task PostAsync(string relativePath = "", string json = "{}") + { + StringContent stringContent = CreateStringContent(json); + Uri uri = new Uri(_httpClient.BaseAddress, relativePath); // Normalize POST uri: Can't end with `/`. + + if (IsLogLevelDebug) + Debug.Log($"PostAsync to: `{uri}` with json: `{json}`"); + + try + { + return await ExecuteRequestAsync(() => _httpClient.PostAsync(uri, stringContent)); + } + catch (Exception e) + { + Debug.LogError($"Error: {e}"); + throw; + } + } + + /// + /// PATCH | We already added "https://api.edgegap.com/" (or similar) BaseAddress via constructor. + /// + /// + /// Serialize to your model via Newtonsoft + /// + /// - Success => returns HttpResponseMessage result + /// - Error => Catches errs => returns null (no rethrow) + /// + protected async Task PatchAsync(string relativePath = "", string json = "{}") + { + StringContent stringContent = CreateStringContent(json); + Uri uri = new Uri(_httpClient.BaseAddress, relativePath); // Normalize PATCH uri: Can't end with `/`. + + if (IsLogLevelDebug) + Debug.Log($"PatchAsync to: `{uri}` with json: `{json}`"); + + // (!) As of 11/15/2023, .PatchAsync() is "unsupported by Unity" -- so we manually set the verb and SendAsync() + // Create the request manually + HttpRequestMessage patchRequest = new HttpRequestMessage(new HttpMethod("PATCH"), uri) + { + Content = stringContent, + }; + + try + { + return await ExecuteRequestAsync(() => _httpClient.SendAsync(patchRequest)); + } + catch (Exception e) + { + Debug.LogError($"Error: {e}"); + throw; + } + } + + /// + /// GET | We already added "https://api.edgegap.com/" (or similar) BaseAddress via constructor. + /// + /// + /// + /// To append to the URL; eg: "foo=0&bar=1" + /// (!) First query key should prefix nothing, as shown + /// + /// - Success => returns HttpResponseMessage result + /// - Error => Catches errs => returns null (no rethrow) + /// + protected async Task GetAsync(string relativePath = "", string customQuery = "") + { + string completeRelativeUri = prepareEdgegapUriWithQuery( + relativePath, + customQuery); + + if (IsLogLevelDebug) + Debug.Log($"GetAsync to: `{completeRelativeUri} with customQuery: `{customQuery}`"); + + try + { + return await ExecuteRequestAsync(() => _httpClient.GetAsync(completeRelativeUri)); + } + catch (Exception e) + { + Debug.LogError($"Error: {e}"); + throw; + } + } + + /// + /// DELETE | We already added "https://api.edgegap.com/" (or similar) BaseAddress via constructor. + /// + /// + /// + /// To append to the URL; eg: "foo=0&bar=1" + /// (!) First query key should prefix nothing, as shown + /// + /// - Success => returns HttpResponseMessage result + /// - Error => Catches errs => returns null (no rethrow) + /// + protected async Task DeleteAsync(string relativePath = "", string customQuery = "") + { + string completeRelativeUri = prepareEdgegapUriWithQuery( + relativePath, + customQuery); + + if (IsLogLevelDebug) + Debug.Log($"DeleteAsync to: `{completeRelativeUri} with customQuery: `{customQuery}`"); + + try + { + return await ExecuteRequestAsync(() => _httpClient.DeleteAsync(completeRelativeUri)); + } + catch (Exception e) + { + Debug.LogError($"Error: {e}"); + throw; + } + } + + /// POST || GET + /// + /// + /// + private static async Task ExecuteRequestAsync( + Func> requestFunc, + CancellationToken cancellationToken = default) + { + HttpResponseMessage response = null; + try + { + response = await requestFunc(); + } + catch (HttpRequestException e) + { + Debug.LogError($"HttpRequestException: {e.Message}"); + return null; + } + catch (TaskCanceledException e) + { + if (cancellationToken.IsCancellationRequested) + Debug.LogError("Task was cancelled by caller."); + else + Debug.LogError($"TaskCanceledException: Timeout - {e.Message}"); + return null; + } + catch (Exception e) // Generic exception handler + { + Debug.LogError($"Unexpected error occurred: {e.Message}"); + return null; + } + + // Check for a successful status code + if (response == null) + { + Debug.Log("!Success (null response) - returning 500"); + return CreateUnknown500Err(); + } + + if (!response.IsSuccessStatusCode) + { + HttpMethod httpMethod = response.RequestMessage.Method; + Debug.Log($"!Success: {(short)response.StatusCode} {response.ReasonPhrase} - " + + $"{httpMethod} | {response.RequestMessage.RequestUri}` - " + + $"{response.Content?.ReadAsStringAsync().Result}"); + } + + return response; + } + #endregion // HTTP Requests + + + #region Utils + /// Creates a UTF-8 encoded application/json + json obj + /// Arbitrary json obj + /// + private StringContent CreateStringContent(string json = "{}") => + new StringContent(json, Encoding.UTF8, "application/json"); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + private static HttpResponseMessage CreateUnknown500Err() => + new HttpResponseMessage(HttpStatusCode.InternalServerError); // 500 - Unknown // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + /// + /// Merges Edgegap-required query params (source) -> merges with custom query -> normalizes. + /// + /// + /// + /// + private string prepareEdgegapUriWithQuery(string relativePath, string customQuery) + { + // Create UriBuilder using the BaseAddress + UriBuilder uriBuilder = new UriBuilder(_httpClient.BaseAddress); + + // Add the relative path to the UriBuilder's path + uriBuilder.Path += relativePath; + + // Parse the existing query from the UriBuilder + NameValueCollection query = HttpUtility.ParseQueryString(uriBuilder.Query); + + // Add default "source=unity" param + query["source"] = "unity"; + + // Parse and merge the custom query parameters + NameValueCollection customParams = HttpUtility.ParseQueryString(customQuery); + foreach (string key in customParams) + { + query[key] = customParams[key]; + } + + // Set the merged query back to the UriBuilder + uriBuilder.Query = query.ToString(); + + // Extract the complete relative URI and return it + return uriBuilder.Uri.PathAndQuery; + } + #endregion // Utils + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapApiBase.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapApiBase.cs.meta new file mode 100644 index 0000000000..7c1774f36b --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapApiBase.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 50379f30f5137224aa05a5c7b6b5ebba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapApiBase.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapAppApi.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapAppApi.cs new file mode 100644 index 0000000000..4e7eab14e8 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapAppApi.cs @@ -0,0 +1,148 @@ +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Edgegap.Editor.Api.Models.Requests; +using Edgegap.Editor.Api.Models.Results; + +namespace Edgegap.Editor.Api +{ + /// + /// Wraps the v1/app API endpoint: Applications Control API. + /// - API Doc | https://docs.edgegap.com/api/#tag/Applications + /// + public class EdgegapAppApi : EdgegapApiBase + { + public EdgegapAppApi( + ApiEnvironment apiEnvironment, + string apiToken, + EdgegapWindowMetadata.LogLevel logLevel = EdgegapWindowMetadata.LogLevel.Error) + : base(apiEnvironment, apiToken, logLevel) + { + } + + + #region API Methods + /// + /// POST to v1/app + /// - Create an application that will regroup application versions. + /// - API Doc | https://docs.edgegap.com/api/#tag/Applications/operation/application-post + /// + /// + /// Http info with GetCreateAppResult data model + /// - Success: 200 + /// - Fail: 409 (app already exists), 400 (reached limit) + /// + public async Task> CreateApp(CreateAppRequest request) + { + HttpResponseMessage response = await PostAsync("v1/app", request.ToString()); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + bool isSuccess = response.StatusCode == HttpStatusCode.OK; // 200 + if (!isSuccess) + return result; + + return result; + } + + /// + /// GET to v1/app + /// - Get an application that will regroup application versions. + /// - API Doc | https://docs.edgegap.com/api/#tag/Applications/operation/application-post + /// + /// + /// Http info with GetCreateAppResult data model + /// - Success: 200 + /// + public async Task> GetApp(string appName) + { + HttpResponseMessage response = await GetAsync($"v1/app/{appName}"); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + bool isSuccess = response.StatusCode == HttpStatusCode.OK; // 200 + if (!isSuccess) + return result; + + return result; + } + + /// + /// PATCH to v1/app/{app_name}/version/{version_name} + /// - Update an *existing* application version with new specifications. + /// - API Doc | https://docs.edgegap.com/api/#tag/Applications/operation/app-versions-patch + /// + /// + /// Http info with UpdateAppVersionRequest data model + /// - Success: 200 + /// + public async Task> UpdateAppVersion(UpdateAppVersionRequest request) + { + string relativePath = $"v1/app/{request.AppName}/version/{request.VersionName}"; + HttpResponseMessage response = await PatchAsync(relativePath, request.ToString()); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + bool isSuccess = response.StatusCode == HttpStatusCode.OK; // 200 + if (!isSuccess) + return result; + + return result; + } + + /// + /// POST to v1/app/{app_name}/version + /// - Create an new application version with new specifications. + /// - API Doc | https://docs.edgegap.com/api/#tag/Applications/operation/app-version-post + /// + /// + /// Http info with UpdateAppVersionRequest data model + /// - Success: 200 (no result model) + /// - Fail: 409 (app already exists), 400 (reached limit) + /// + public async Task> CreateAppVersion(CreateAppVersionRequest request) + { + string relativePath = $"v1/app/{request.AppName}/version"; + HttpResponseMessage response = await PostAsync(relativePath, request.ToString()); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + bool isSuccess = response.StatusCode == HttpStatusCode.OK; // 200 + + if (!isSuccess) + return result; + + return result; + } + #endregion // API Methods + + + #region Chained API Methods + /// + /// PATCH and/or POST to v1/app/: Upsert an *existing* application version with new specifications. + /// - Consumes either 1 or 2 API calls: 1st tries to PATCH, then POST if PATCH fails (!exists). + /// - API POST Doc | https://docs.edgegap.com/api/#tag/Applications/operation/app-version-post + /// - API PATCH Doc | https://docs.edgegap.com/api/#tag/Applications/operation/app-versions-patch + /// + /// + /// Http info with UpdateAppVersionRequest data model + /// - Success: 200 (no result model) + /// - Fail: 409 (app already exists), 400 (reached limit) + /// + public async Task> UpsertAppVersion(UpdateAppVersionRequest request) + { + EdgegapHttpResult result = await UpdateAppVersion(request); // PATCH + + if (result.HasErr) + { + // Try to create, instead + CreateAppVersionRequest createAppVersionRequest = CreateAppVersionRequest.FromUpdateRequest(request); + result = await CreateAppVersion(createAppVersionRequest); // POST + } + + bool isSuccess = result.StatusCode == HttpStatusCode.OK; // 200 + + if (!isSuccess) + return result; + + return result; + } + #endregion // Chained API Methods + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapAppApi.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapAppApi.cs.meta new file mode 100644 index 0000000000..9bc64cca07 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapAppApi.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 3b0b3b865abe64b49a4000294c4e9593 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapAppApi.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapDeploymentsApi.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapDeploymentsApi.cs new file mode 100644 index 0000000000..dda3ce24af --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapDeploymentsApi.cs @@ -0,0 +1,177 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Edgegap.Editor.Api.Models.Requests; +using Edgegap.Editor.Api.Models.Results; +using UnityEngine.Assertions; + +namespace Edgegap.Editor.Api +{ + /// + /// Wraps the v1/[deploy | status | stop] API endpoints: Deployments Control API. + /// - API Doc | https://docs.edgegap.com/api/#tag/Deployments + /// + public class EdgegapDeploymentsApi : EdgegapApiBase + { + public EdgegapDeploymentsApi( + ApiEnvironment apiEnvironment, + string apiToken, + EdgegapWindowMetadata.LogLevel logLevel = EdgegapWindowMetadata.LogLevel.Error) + : base(apiEnvironment, apiToken, logLevel) + { + } + + + #region API Methods + /// + /// POST v1/deploy + /// - Create a new deployment. Deployment is a server instance of your application version. + /// - API Doc | https://docs.edgegap.com/api/#tag/Deployments + /// + /// + /// Http info with CreateDeploymentResult data model + /// - Success: 200 + /// + public async Task> CreateDeploymentAsync( + CreateDeploymentRequest request) + { + HttpResponseMessage response = await PostAsync("v1/deploy", request.ToString()); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + bool isSuccess = response.StatusCode == HttpStatusCode.OK; // 200 + if (!isSuccess) + return result; + + return result; + } + + /// + /// GET v1/status/{requestId} + /// - Retrieve the information for a deployment. + /// - API Doc | https://docs.edgegap.com/api/#tag/Deployments/operation/deployment-status-get + /// + /// + /// Unique Identifier to keep track of your request across all Arbitrium ecosystem. + /// It's included in the response of the app deploy. Ex: "93924761ccde" + /// + /// Http info with GetDeploymentStatusResult data model + /// - Success: 200 + /// + public async Task> GetDeploymentStatusAsync(string requestId) + { + HttpResponseMessage response = await GetAsync($"v1/status/{requestId}"); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + bool isSuccess = response.StatusCode == HttpStatusCode.OK; // 200 + if (!isSuccess) + return result; + + return result; + } + + /// + /// DELETE v1/stop/{requestId} + /// - Delete an instance of deployment. It will stop the running container and all its games. + /// - API Doc | https://docs.edgegap.com/api/#tag/Deployments/operation/deployment-status-get + /// + /// + /// Unique Identifier to keep track of your request across all Arbitrium ecosystem. + /// It's included in the response of the app deploy. Ex: "93924761ccde" + /// + /// Http info with GetDeploymentStatusResult data model + /// - Success: 200 + /// + public async Task> StopActiveDeploymentAsync(string requestId) + { + HttpResponseMessage response = await DeleteAsync($"v1/stop/{requestId}"); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + bool isSuccess = response.StatusCode == HttpStatusCode.OK; // 200 + if (!isSuccess) + return result; + + return result; + } + #endregion // API Methods + + + #region Chained API Methods + /// + /// POST v1/deploy => GET v1/status/{requestId} + /// - Create a new deployment. Deployment is a server instance of your application version. + /// - Then => await READY status. + /// - API Doc | https://docs.edgegap.com/api/#tag/Deployments + /// + /// + /// Http info with CreateDeploymentResult data model (with a READY deployment status) + /// - Success: 200 + /// - Error: If createResult.HasErr, returns createResult + /// + public async Task> CreateDeploymentAwaitReadyStatusAsync( + CreateDeploymentRequest request, TimeSpan pollInterval) + { + EdgegapHttpResult createResponse = await CreateDeploymentAsync(request); + + // Create => + bool isCreateSuccess = createResponse.StatusCode == HttpStatusCode.OK; // 200 + if (!isCreateSuccess) + return createResponse; + + // Await Status READY => + string requestId = createResponse.Data.RequestId; + _ = await AwaitReadyStatusAsync(requestId, pollInterval); + + // Return no matter what the result; no need to validate + return createResponse; + } + + /// If you recently deployed but want to await READY status. + /// + /// + public async Task> AwaitReadyStatusAsync( + string requestId, + TimeSpan pollInterval) + { + Assert.IsTrue(!string.IsNullOrEmpty(requestId)); // Validate + + EdgegapHttpResult statusResponse = null; + CancellationTokenSource cts = new CancellationTokenSource (TimeSpan.FromMinutes( // MIRROR CHANGE: 'new()' not supported in Unity 2020 + EdgegapWindowMetadata.DEPLOYMENT_AWAIT_READY_STATUS_TIMEOUT_MINS)); + bool isReady = false; + + while (!isReady && !cts.Token.IsCancellationRequested) + { + await Task.Delay(pollInterval, cts.Token); + statusResponse = await GetDeploymentStatusAsync(requestId); + isReady = statusResponse.Data.CurrentStatus == EdgegapWindowMetadata.READY_STATUS; + } + + return statusResponse; + } + + /// If you recently stopped a deployment, but want to await TERMINATED (410) status. + /// + /// + public async Task> AwaitTerminatedDeleteStatusAsync( + string requestId, + TimeSpan pollInterval) + { + EdgegapHttpResult deleteResponse = null; + CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMinutes( // MIRROR CHANGE: 'new()' not supported in Unity 2020 + EdgegapWindowMetadata.DEPLOYMENT_AWAIT_READY_STATUS_TIMEOUT_MINS)); + bool isStopped = false; + + while (!isStopped && !cts.Token.IsCancellationRequested) + { + await Task.Delay(pollInterval, cts.Token); + deleteResponse = await StopActiveDeploymentAsync(requestId); + isStopped = deleteResponse.StatusCode == HttpStatusCode.Gone; // 410 + } + + return deleteResponse; + } + #endregion Chained API Methods + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapDeploymentsApi.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapDeploymentsApi.cs.meta new file mode 100644 index 0000000000..7ef02ee9ea --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapDeploymentsApi.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 37ecdc6abda4402419438f2284ef2d95 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapDeploymentsApi.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapIpApi.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapIpApi.cs new file mode 100644 index 0000000000..86e4b26a31 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapIpApi.cs @@ -0,0 +1,47 @@ +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Edgegap.Editor.Api.Models.Results; + +namespace Edgegap.Editor.Api +{ + /// + /// Wraps the v1/ip API endpoint: "IP Lookup" API. + /// - API Doc | https://docs.edgegap.com/api/#tag/IP-Lookup + /// + public class EdgegapIpApi : EdgegapApiBase + { + public EdgegapIpApi( + ApiEnvironment apiEnvironment, + string apiToken, + EdgegapWindowMetadata.LogLevel logLevel = EdgegapWindowMetadata.LogLevel.Error) + : base(apiEnvironment, apiToken, logLevel) + { + } + + + #region API Methods + /// + /// GET to v1/app + /// - Retrieve your public IP address. + /// - API Doc | https://docs.edgegap.com/api/#tag/IP-Lookup/operation/IP + /// + /// + /// Http info with GetCreateAppResult data model + /// - Success: 200 + /// - Fail: 409 (app already exists), 400 (reached limit) + /// + public async Task> GetYourPublicIp() + { + HttpResponseMessage response = await GetAsync("v1/ip"); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + bool isSuccess = response.StatusCode == HttpStatusCode.OK; // 200 + if (!isSuccess) + return result; + + return result; + } + #endregion // API Methods + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapIpApi.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapIpApi.cs.meta new file mode 100644 index 0000000000..b9e67100fa --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapIpApi.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: fac4a7425623f39488af09d60549313e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapIpApi.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapWizardApi.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapWizardApi.cs new file mode 100644 index 0000000000..5d4a25ff53 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapWizardApi.cs @@ -0,0 +1,52 @@ +using System.Net.Http; +using System.Threading.Tasks; +using Edgegap.Editor.Api.Models.Results; +using Newtonsoft.Json.Linq; + +namespace Edgegap.Editor.Api +{ + /// Wraps the v1/wizard API endpoint. Used for internal purposes. + public class EdgegapWizardApi : EdgegapApiBase + { + /// Extended path after the base uri + public EdgegapWizardApi( + ApiEnvironment apiEnvironment, + string apiToken, + EdgegapWindowMetadata.LogLevel logLevel = EdgegapWindowMetadata.LogLevel.Error) + : base(apiEnvironment, apiToken, logLevel) + { + } + + + #region API Methods + /// POST to v1/wizard/init-quick-start + /// + /// Http info with no explicit data model + /// - Success: 204 (no result model) + /// + public async Task InitQuickStart() + { + string json = new JObject { ["source"] = "unity" }.ToString(); + HttpResponseMessage response = await PostAsync("v1/wizard/init-quick-start", json); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + return result; + } + + /// GET to v1/wizard/registry-credentials + /// + /// - Http info with GetRegistryCredentialsResult data model + /// - Success: 200 + /// - Error: Likely if called before a successful InitQuickStart(), + /// or if called in a staging env. Soon, this will be available in production. + /// + public async Task> GetRegistryCredentials() + { + HttpResponseMessage response = await GetAsync("v1/wizard/registry-credentials"); + EdgegapHttpResult result = new EdgegapHttpResult(response); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + return result; + } + #endregion // API Methods + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapWizardApi.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapWizardApi.cs.meta new file mode 100644 index 0000000000..c4e279316a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapWizardApi.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: f6986ee67361f0b45928ccd70c7ab12c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/EdgegapWizardApi.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models.meta new file mode 100644 index 0000000000..2c5a793101 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: aed107c714fce71449ef56590221c567 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/AppPortsData.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/AppPortsData.cs new file mode 100644 index 0000000000..782bc7b1ee --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/AppPortsData.cs @@ -0,0 +1,28 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models +{ + /// + /// Used in `UpdateAppVersionRequest`, `CreateAppVersionRequest`. + /// For GetDeploymentStatusResult, see DeploymentPortsData + /// + public class AppPortsData + { + /// 1024~49151; Default 7770 + [JsonProperty("port")] + public int Port { get; set; } = EdgegapWindowMetadata.PORT_DEFAULT; + + /// Default "UDP" + [JsonProperty("protocol")] + public string ProtocolStr { get; set; } = EdgegapWindowMetadata.DEFAULT_PROTOCOL_TYPE.ToString(); + + [JsonProperty("to_check")] + public bool ToCheck { get; set; } = true; + + [JsonProperty("tls_upgrade")] + public bool TlsUpgrade { get; set; } + + [JsonProperty("name")] + public string PortName { get; set; } = "Game Port"; + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/AppPortsData.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/AppPortsData.cs.meta new file mode 100644 index 0000000000..865a567836 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/AppPortsData.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: b6d4864ea3706574fb35920c6fab46fa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/AppPortsData.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/DeploymentPortsData.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/DeploymentPortsData.cs new file mode 100644 index 0000000000..972205b709 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/DeploymentPortsData.cs @@ -0,0 +1,29 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models +{ + /// Used in `GetDeploymentStatus`. + public class DeploymentPortsData + { + [JsonProperty("external")] + public int External { get; set; } + + [JsonProperty("internal")] + public int Internal { get; set; } + + [JsonProperty("protocol")] + public string Protocol { get; set; } + + [JsonProperty("name")] + public string PortName { get; set; } + + [JsonProperty("tls_upgrade")] + public bool TlsUpgrade { get; set; } + + [JsonProperty("link")] + public string Link { get; set; } + + [JsonProperty("proxy")] + public int? Proxy { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/DeploymentPortsData.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/DeploymentPortsData.cs.meta new file mode 100644 index 0000000000..6a46d310b6 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/DeploymentPortsData.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 62d51b44b8414c9f968ca607ccb06b7e +timeCreated: 1701522748 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/DeploymentPortsData.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/LocationData.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/LocationData.cs new file mode 100644 index 0000000000..d9c89bb1ce --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/LocationData.cs @@ -0,0 +1,28 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models +{ + public class LocationData + { + [JsonProperty("city")] + public string City { get; set; } + + [JsonProperty("country")] + public string Country { get; set; } + + [JsonProperty("continent")] + public string Continent { get; set; } + + [JsonProperty("administrative_division")] + public string AdministrativeDivision { get; set; } + + [JsonProperty("timezone")] + public string Timezone { get; set; } + + [JsonProperty("latitude")] + public double Latitude { get; set; } + + [JsonProperty("longitude")] + public double Longitude { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/LocationData.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/LocationData.cs.meta new file mode 100644 index 0000000000..244b86ef6f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/LocationData.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 57eed0dbd556e074c992cf6599a1f6bd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/LocationData.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/ProtocolType.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/ProtocolType.cs new file mode 100644 index 0000000000..d72086db0f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/ProtocolType.cs @@ -0,0 +1,18 @@ +namespace Edgegap.Editor.Api.Models +{ + /// + /// Unity default: UDP. + /// (!) UDP !works in WebGL. + /// + public enum ProtocolType + { + /// Unity default - fastest; !works in WebGL. + UDP, + + /// Slower, but more reliable; works in WebGL. + TCP, + + /// Slower, but more reliable; works in WebGL. + WS, + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/ProtocolType.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/ProtocolType.cs.meta new file mode 100644 index 0000000000..121fd32a19 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/ProtocolType.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: be5acd63e783b364ebdbb783639e2d32 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/ProtocolType.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests.meta new file mode 100644 index 0000000000..bcd87e4493 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d1b2a5c481353934f906c30ba047df9b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppRequest.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppRequest.cs new file mode 100644 index 0000000000..91e3c2616e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppRequest.cs @@ -0,0 +1,55 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Requests +{ + /// + /// Request model for https://docs.edgegap.com/api/#tag/Applications/operation/application-post + /// + public class CreateAppRequest + { + #region Required + /// *The application name. + [JsonProperty("name")] + public string AppName { get; set; } + #endregion // Required + + + #region Optional + /// *If the application can be deployed. + [JsonProperty("is_active")] + public bool IsActive { get; set; } + + /// *Image base64 string. + [JsonProperty("image")] + public string Image { get; set; } + + /// If the telemetry agent is installed on the versions of this app. + [JsonProperty("is_telemetry_agent_active")] + public bool IsTelemetryAgentActive { get; set; } + #endregion // Optional + + + /// Used by Newtonsoft + public CreateAppRequest() + { + } + + /// Init with required info + /// The application name + /// If the application can be deployed + /// Image base64 string + public CreateAppRequest( + string appName, + bool isActive, + string image) + { + this.AppName = appName; + this.IsActive = isActive; + this.Image = image; + } + + /// Parse to json str + public override string ToString() => + JsonConvert.SerializeObject(this); + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppRequest.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppRequest.cs.meta new file mode 100644 index 0000000000..e30c720a60 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppRequest.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 0a492d7c515b8894ea30b37db6b7efe4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppRequest.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppVersionRequest.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppVersionRequest.cs new file mode 100644 index 0000000000..360ed43b68 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppVersionRequest.cs @@ -0,0 +1,225 @@ +using System; +using Newtonsoft.Json; +using UnityEngine; + +namespace Edgegap.Editor.Api.Models.Requests +{ + /// + /// Request model for `POST v1/app/{app_name}/version`. + /// API Doc | https://docs.edgegap.com/api/#tag/Applications/operation/app-version-post + /// + public class CreateAppVersionRequest + { + #region Required + /// *The name of the application associated. + [JsonIgnore] // *Path var + public string AppName { get; set; } + + /// *The name of the application associated. + [JsonProperty("name")] + public string VersionName { get; set; } = EdgegapWindowMetadata.DEFAULT_VERSION_TAG; + + /// *The tag of your image. Default == "latest". + /// "0.1.2" || "latest" (although "latest" !recommended; use actual versions in production) + [JsonProperty("docker_tag")] + public string DockerTag { get; set; } = EdgegapWindowMetadata.DEFAULT_VERSION_TAG; + + /// *The name of your image. + /// "edgegap/demo" || "myCompany-someId/mylowercaseapp" + [JsonProperty("docker_image")] + public string DockerImage { get; set; } = ""; + + /// *The Repository where the image is. + /// "registry.edgegap.com" || "harbor.edgegap.com" || "docker.io" + [JsonProperty("docker_repository")] + public string DockerRepository { get; set; } = ""; + + /// *Units of vCPU needed (1024 = 1vcpu) + [JsonProperty("req_cpu")] + public int ReqCpu { get; set; } = 256; + + /// *Units of memory in MB needed (1024 = 1 GPU) + [JsonProperty("req_memory")] + public int ReqMemory { get; set; } = 256; + + /// *Required: At least 1 { Port, ProtocolStr }. + [JsonProperty("ports")] + public AppPortsData[] Ports { get; set; } = {}; + + /// The username to access the docker repository + [JsonProperty("private_username")] + public string PrivateUsername { get; set; } = ""; + + /// The Private Password or Token of the username (We recommend to use a token) + [JsonProperty("private_token")] + public string PrivateToken { get; set; } = ""; + #endregion // Required + + + // #region Optional + // [JsonProperty("is_active")] + // public bool IsActive { get; set; } = true; + // + // [JsonProperty("req_video")] + // public int ReqVideo { get; set; } = 256; + // + // [JsonProperty("max_duration")] + // public int MaxDuration { get; set; } = 30; + // + // [JsonProperty("use_telemetry")] + // public bool UseTelemetry { get; set; } = true; + // + // [JsonProperty("inject_context_env")] + // public bool InjectContextEnv { get; set; } = true; + // + // [JsonProperty("whitelisting_active")] + // public bool WhitelistingActive { get; set; } = true; + // + // [JsonProperty("force_cache")] + // public bool ForceCache { get; set; } + // + // [JsonProperty("cache_min_hour")] + // public int CacheMinHour { get; set; } + // + // [JsonProperty("cache_max_hour")] + // public int CacheMaxHour { get; set; } + // + // [JsonProperty("time_to_deploy")] + // public int TimeToDeploy { get; set; } = 15; + // + // [JsonProperty("enable_all_locations")] + // public bool EnableAllLocations { get; set; } + // + // [JsonProperty("termination_grace_period_seconds")] + // public int TerminationGracePeriodSeconds { get; set; } = 5; + // + // [JsonProperty("endpoint_storage")] + // public string EndpointStorage { get; set; } = ""; + // + // [JsonProperty("command")] + // public string Command { get; set; } + // + // [JsonProperty("arguments")] + // public string Arguments { get; set; } + // + // [JsonProperty("verify_image")] + // public bool VerifyImage { get; set; } + // + // [JsonProperty("session_config")] + // public SessionConfigData SessionConfig { get; set; } = new(); + // + // [JsonProperty("probe")] + // public ProbeData Probe { get; set; } = new(); + // + // [JsonProperty("envs")] + // public EnvsData[] Envs { get; set; } = {}; + // + // public class SessionConfigData + // { + // [JsonProperty("kind")] + // public string Kind { get; set; } = "Seat"; + // + // [JsonProperty("sockets")] + // public int Sockets { get; set; } = 10; + // + // [JsonProperty("autodeploy")] + // public bool Autodeploy { get; set; } = true; + // + // [JsonProperty("empty_ttl")] + // public int EmptyTtl { get; set; } = 60; + // + // [JsonProperty("session_max_duration")] + // public int SessionMaxDuration { get; set; } = 60; + // } + // + // + // public class ProbeData + // { + // [JsonProperty("optimal_ping")] + // public int OptimalPing { get; set; } = 60; + // + // [JsonProperty("rejected_ping")] + // public int RejectedPing { get; set; } = 180; + // } + // + // public class EnvsData + // { + // [JsonProperty("key")] + // public string Key { get; set; } + // + // [JsonProperty("value")] + // public string Value { get; set; } + // + // [JsonProperty("is_secret")] + // public bool IsSecret { get; set; } = true; + // } + // #endregion // Optional + + /// Used by Newtonsoft + public CreateAppVersionRequest() + { + } + + /// + /// Init with required info. + /// (!) If looking for refs, also see FromUpdateRequest() builder below. + /// + /// The name of the application. + /// + /// + /// + /// + public CreateAppVersionRequest( + string appName, + string containerRegistryUsername, + string containerRegistryPasswordToken, + int portNum, + ProtocolType protocolType) + { + this.AppName = appName; + this.PrivateUsername = containerRegistryUsername; + this.PrivateToken = containerRegistryPasswordToken; + this.Ports = new AppPortsData[] + { + new AppPortsData() // MIRROR CHANGE: 'new()' not supported in Unity 2020 + { + Port = portNum, + ProtocolStr = protocolType.ToString(), + }, + }; + } + + /// + /// Port from Update PATCH model: If you tried to Update, but !exists, you probably want to create it next. + /// + /// + public static CreateAppVersionRequest FromUpdateRequest(UpdateAppVersionRequest updateRequest) + { + // Convert the updateRequest to JSON + string json = JsonConvert.SerializeObject(updateRequest); + + // Deserialize the JSON back to CreateAppVersionRequest + CreateAppVersionRequest createReq = null; + + try + { + createReq = JsonConvert.DeserializeObject(json); + createReq.AppName = updateRequest.AppName; // Normally JsonIgnored in Update + createReq.VersionName = updateRequest.VersionName; // Normally JsonIgnored in Update + createReq.PrivateUsername = updateRequest.PrivateUsername; + createReq.PrivateToken = updateRequest.PrivateToken; + } + catch (Exception e) + { + Debug.LogError($"Error (when parsing CreateAppVersionRequest from CreateAppVersionRequest): {e}"); + throw; + } + + return createReq; + } + + /// Parse to json str + public override string ToString() => + JsonConvert.SerializeObject(this); + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppVersionRequest.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppVersionRequest.cs.meta new file mode 100644 index 0000000000..0b3baff886 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppVersionRequest.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 0bb645e2f9d04384a85739269cc8a4e1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateAppVersionRequest.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateDeploymentRequest.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateDeploymentRequest.cs new file mode 100644 index 0000000000..968821cc93 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateDeploymentRequest.cs @@ -0,0 +1,63 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Requests +{ + /// + /// Request model for `POST v1/deploy`. + /// API Doc | https://docs.edgegap.com/api/#tag/Deployments/operation/deploy + /// + public class CreateDeploymentRequest + { + #region Required + /// *Required: The name of the App you want to deploy. + [JsonProperty("app_name")] + public string AppName { get; set; } + + /// + /// *Required: The name of the App Version you want to deploy; + /// if not present, the last version created is picked. + /// + [JsonProperty("version_name")] + public string VersionName { get; set; } + + /// + /// *Required: The List of IP of your user. + /// + [JsonProperty("ip_list")] + public string[] IpList { get; set; } + + /// + /// *Required: The list of IP of your user with their location (latitude, longitude). + /// + [JsonProperty("geo_ip_list")] + public string[] GeoIpList { get; set; } = {}; + #endregion // Required + + + /// Used by Newtonsoft + public CreateDeploymentRequest() + { + } + + /// Init with required info; used for a single external IP address. + /// The name of the application. + /// + /// The name of the App Version you want to deploy, if not present, + /// the last version created is picked. + /// + /// Obtain from IpApi. + public CreateDeploymentRequest( + string appName, + string versionName, + string externalIp) + { + this.AppName = appName; + this.VersionName = versionName; + this.IpList = new[] { externalIp }; + } + + /// Parse to json str + public override string ToString() => + JsonConvert.SerializeObject(this); + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateDeploymentRequest.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateDeploymentRequest.cs.meta new file mode 100644 index 0000000000..cb00a989ad --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateDeploymentRequest.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: aae7b317093230e419bc0f8be1097ea6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/CreateDeploymentRequest.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/UpdateAppVersionRequest.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/UpdateAppVersionRequest.cs new file mode 100644 index 0000000000..8a1d76b1c2 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/UpdateAppVersionRequest.cs @@ -0,0 +1,175 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Requests +{ + /// + /// Request model for `PATCH v1/app/{app_name}/version/{version_name}`. + /// Request model for https://docs.edgegap.com/api/#tag/Applications/operation/app-versions-patch + /// TODO: Split "Create" and "Update" into their own, separate models: CTRL+F for "(!)" for more info. + /// + public class UpdateAppVersionRequest + { + #region Required + /// *Required: The name of the application. + [JsonIgnore] // *Path var + public string AppName { get; set; } + #endregion // Required + + + #region Optional + /// The name of the application version. + [JsonIgnore] // *Path var + public string VersionName { get; set; } = EdgegapWindowMetadata.DEFAULT_VERSION_TAG; + + /// At least 1 { Port, ProtocolStr } + [JsonProperty("ports")] + public AppPortsData[] Ports { get; set; } = {}; + + /// The Repository where the image is. + /// "registry.edgegap.com" || "harbor.edgegap.com" || "docker.io" + [JsonProperty("docker_repository")] + public string DockerRepository { get; set; } = ""; + + /// The name of your image. + /// "edgegap/demo" || "myCompany-someId/mylowercaseapp" + [JsonProperty("docker_image")] + public string DockerImage { get; set; } = ""; + + /// The tag of your image. Default == "latest". + /// "0.1.2" || "latest" (although "latest" !recommended; use actual versions in production) + [JsonProperty("docker_tag")] + public string DockerTag { get; set; } = EdgegapWindowMetadata.DEFAULT_VERSION_TAG; + + [JsonProperty("is_active")] + public bool IsActive { get; set; } = true; + + [JsonProperty("private_username")] + public string PrivateUsername { get; set; } = ""; + + [JsonProperty("private_token")] + public string PrivateToken { get; set; } = ""; + + #region (!) Shows in API docs for PATCH, but could be CREATE only? "Unknown Args" + // [JsonProperty("req_cpu")] + // public int ReqCpu { get; set; } = 256; + // + // [JsonProperty("req_memory")] + // public int ReqMemory { get; set; } = 256; + // + // [JsonProperty("req_video")] + // public int ReqVideo { get; set; } = 256; + #endregion // (!) Shows in API docs for PATCH, but could be CREATE only? "Unknown Args" + + [JsonProperty("max_duration")] + public int MaxDuration { get; set; } = 60; + + [JsonProperty("use_telemetry")] + public bool UseTelemetry { get; set; } = true; + + [JsonProperty("inject_context_env")] + public bool InjectContextEnv { get; set; } = true; + + [JsonProperty("whitelisting_active")] + public bool WhitelistingActive { get; set; } = false; + + [JsonProperty("force_cache")] + public bool ForceCache { get; set; } + + [JsonProperty("cache_min_hour")] + public int CacheMinHour { get; set; } + + [JsonProperty("cache_max_hour")] + public int CacheMaxHour { get; set; } + + [JsonProperty("time_to_deploy")] + public int TimeToDeploy { get; set; } = 120; + + [JsonProperty("enable_all_locations")] + public bool EnableAllLocations { get; set; } + + [JsonProperty("termination_grace_period_seconds")] + public int TerminationGracePeriodSeconds { get; set; } = 5; + + // // (!) BUG: Expects empty string "" at minimum; however, empty string will throw server err + // [JsonProperty("endpoint_storage")] + // public string EndpointStorage { get; set; } + + [JsonProperty("command")] + public string Command { get; set; } + + [JsonProperty("arguments")] + public string Arguments { get; set; } + + // /// + // /// (!) Setting this will trigger a very specific type of game that will affect the AppVersion. + // /// TODO: Is leaving as null the same as commenting out? + // /// + // [JsonProperty("session_config")] + // public SessionConfigData SessionConfig { get; set; } + + [JsonProperty("probe")] + public ProbeData Probe { get; set; } = new ProbeData(); // MIRROR CHANGE: 'new()' not supported in Unity 2020 + + [JsonProperty("envs")] + public EnvsData[] Envs { get; set; } = {}; + + public class SessionConfigData + { + [JsonProperty("kind")] + public string Kind { get; set; } = "Seat"; + + [JsonProperty("sockets")] + public int Sockets { get; set; } = 10; + + [JsonProperty("autodeploy")] + public bool Autodeploy { get; set; } = true; + + [JsonProperty("empty_ttl")] + public int EmptyTtl { get; set; } = 60; + + [JsonProperty("session_max_duration")] + public int SessionMaxDuration { get; set; } = 60; + } + + public class ProbeData + { + [JsonProperty("optimal_ping")] + public int OptimalPing { get; set; } = 60; + + [JsonProperty("rejected_ping")] + public int RejectedPing { get; set; } = 180; + } + + public class EnvsData + { + [JsonProperty("key")] + public string Key { get; set; } + + [JsonProperty("value")] + public string Value { get; set; } + + [JsonProperty("is_secret")] + public bool IsSecret { get; set; } = true; + } + #endregion // Optional + + /// Used by Newtonsoft + public UpdateAppVersionRequest() + { + } + + /// + /// Init with required info. Default version/tag == "default". + /// Since we're updating, we only require the AppName. + /// + /// The name of the application. + public UpdateAppVersionRequest(string appName) + { + this.AppName = appName; + } + + /// Parse to json str + public override string ToString() => + JsonConvert.SerializeObject(this); + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/UpdateAppVersionRequest.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/UpdateAppVersionRequest.cs.meta new file mode 100644 index 0000000000..31339b92f5 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/UpdateAppVersionRequest.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8da9712633ee1e64faca0b960d4bed31 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Requests/UpdateAppVersionRequest.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results.meta new file mode 100644 index 0000000000..63ab7622f4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: aa4ceffbc97b8254885a63937def2324 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/CreateDeploymentResult.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/CreateDeploymentResult.cs new file mode 100644 index 0000000000..407d681a26 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/CreateDeploymentResult.cs @@ -0,0 +1,53 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Results +{ + /// + /// Result model for `POST v1/deploy`. + /// + public class CreateDeploymentResult + { + [JsonProperty("request_id")] + public string RequestId { get; set; } + + [JsonProperty("request_dns")] + public string RequestDns { get; set; } + + [JsonProperty("request_app")] + public string RequestApp { get; set; } + + [JsonProperty("request_version")] + public string RequestVersion { get; set; } + + [JsonProperty("request_user_count")] + public int RequestUserCount { get; set; } + + [JsonProperty("city")] + public string City { get; set; } + + [JsonProperty("country")] + public string Country { get; set; } + + [JsonProperty("continent")] + public string Continent { get; set; } + + [JsonProperty("administrative_division")] + public string AdministrativeDivision { get; set; } + + [JsonProperty("tags")] + public string[] Tags { get; set; } + + [JsonProperty("container_log_storage")] + public ContainerLogStorageData ContainerLogStorage { get; set; } + + + public class ContainerLogStorageData + { + [JsonProperty("enabled")] + public bool Enabled { get; set; } + + [JsonProperty("endpoint_storage")] + public string EndpointStorage { get; set; } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/CreateDeploymentResult.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/CreateDeploymentResult.cs.meta new file mode 100644 index 0000000000..800c301289 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/CreateDeploymentResult.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8361abc6f84fccd4cba26dc285d335dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/CreateDeploymentResult.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapErrorResult.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapErrorResult.cs new file mode 100644 index 0000000000..55b03f2c2f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapErrorResult.cs @@ -0,0 +1,12 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Results +{ + /// Edgegap error, generally just containing `message` + public class EdgegapErrorResult + { + /// Friendly, UI-facing error message from Edgegap; can be lengthy. + [JsonProperty("message")] + public string ErrorMessage { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapErrorResult.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapErrorResult.cs.meta new file mode 100644 index 0000000000..87f7c0432d --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapErrorResult.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 5b29093cb10cf3040b76f4fbe77a435d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapErrorResult.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapHttpResult.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapHttpResult.cs new file mode 100644 index 0000000000..55b4892b85 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapHttpResult.cs @@ -0,0 +1,118 @@ +using System; +using System.Net; +using System.Net.Http; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using UnityEngine; + +namespace Edgegap.Editor.Api.Models.Results +{ + /// + /// Wraps the inner json data with outer http info. + /// This class overload contains no json-deserialiable data result. + /// + public class EdgegapHttpResult + { + /// HTTP Status code for the request. + public HttpStatusCode StatusCode { get; } + + /// This could be err, success, or null. + public string Json { get; } + + /// eg: "POST" + public HttpMethod HttpMethod; + + /// + /// Typically is sent by servers together with the status code. + /// Useful for fallback err descriptions, often based on the status code. + /// + public string ReasonPhrase { get; } + + /// Contains `message` with friendly info. + public bool HasErr => Error != null; + public EdgegapErrorResult Error { get; set; } + + #region Common Shortcuts + /// OK + public bool IsResultCode200 => StatusCode == HttpStatusCode.OK; + + /// NoContent + public bool IsResultCode204 => StatusCode == HttpStatusCode.NoContent; + + /// Forbidden + public bool IsResultCode403 => StatusCode == HttpStatusCode.Forbidden; + + /// Conflict + public bool IsResultCode409 => StatusCode == HttpStatusCode.Conflict; + + /// BadRequest + public bool IsResultCode400 => StatusCode == HttpStatusCode.BadRequest; + + /// Gone + public bool IsResultCode410 => StatusCode == HttpStatusCode.Gone; + #endregion // Common Shortcuts + + + /// + /// Constructor that initializes the class based on an HttpResponseMessage. + /// + public EdgegapHttpResult(HttpResponseMessage httpResponse) + { + this.ReasonPhrase = httpResponse.ReasonPhrase; + this.StatusCode = httpResponse.StatusCode; + + try + { + // TODO: This can be read async with `await`, but can't do this in a Constructor. + // Instead, make a factory builder Task => + this.Json = httpResponse.Content.ReadAsStringAsync().Result; + + this.Error = JsonConvert.DeserializeObject(Json); + if (Error != null && string.IsNullOrEmpty(Error.ErrorMessage)) + Error = null; + } + catch (Exception e) + { + Debug.LogError("Error (reading httpResponse.Content): Client expected json, " + + $"but server returned !json: {e} - "); + } + } + } + + /// + /// Wraps the inner json data with outer http info. + /// This class overload contains json-deserialiable data result. + /// + public class EdgegapHttpResult : EdgegapHttpResult + { + /// The actual result model from Json. Could be null! + public TResult Data { get; set; } + + + public EdgegapHttpResult(HttpResponseMessage httpResponse, bool isLogLevelDebug = false) + : base(httpResponse) + { + this.HttpMethod = httpResponse.RequestMessage.Method; + + // Assuming JSON content and using Newtonsoft.Json for deserialization + bool isDeserializable = httpResponse.Content != null && + httpResponse.Content.Headers.ContentType.MediaType == "application/json"; + + if (isDeserializable) + { + try + { + this.Data = JsonConvert.DeserializeObject(Json); + } + catch (Exception e) + { + Debug.LogError($"Error (deserializing EdgegapHttpResult.Data): {e} - json: {Json}"); + throw; + } + } + + if (isLogLevelDebug) + UnityEngine.Debug.Log($"{typeof(TResult).Name} result: {JObject.Parse(Json)}"); // Prettified + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapHttpResult.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapHttpResult.cs.meta new file mode 100644 index 0000000000..5fcd47d342 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapHttpResult.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 888bfc2c113487b44a3103648d2c2ae3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/EdgegapHttpResult.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetCreateAppResult.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetCreateAppResult.cs new file mode 100644 index 0000000000..b9df98f494 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetCreateAppResult.cs @@ -0,0 +1,31 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Results +{ + /// + /// Result model for `[GET | POST] v1/app`. + /// POST API Doc | https://docs.edgegap.com/api/#tag/Applications/operation/application-post + /// GET API Doc | https://docs.edgegap.com/api/#tag/Applications/operation/application-get + /// + public class GetCreateAppResult + { + [JsonProperty("name")] + public string AppName { get; set; } + + [JsonProperty("is_active")] + public bool IsActive { get; set; } + + /// Optional + [JsonProperty("is_telemetry_agent_active")] + public bool IsTelemetryAgentActive { get; set; } + + [JsonProperty("image")] + public string Image { get; set; } + + [JsonProperty("create_time")] + public string CreateTimeStr { get; set; } + + [JsonProperty("last_updated")] + public string LastUpdatedStr { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetCreateAppResult.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetCreateAppResult.cs.meta new file mode 100644 index 0000000000..2db5099811 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetCreateAppResult.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a66c935238edd8846b1e9e9e19cfab70 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetCreateAppResult.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetDeploymentStatusResult.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetDeploymentStatusResult.cs new file mode 100644 index 0000000000..57c4540fff --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetDeploymentStatusResult.cs @@ -0,0 +1,89 @@ +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Results +{ + /// + /// Result model for `GET v1/status/{request_id}`. + /// API Doc | https://docs.edgegap.com/api/#tag/Deployments/operation/deployment-status-get + /// + public class GetDeploymentStatusResult + { + [JsonProperty("request_id")] + public string RequestId { get; set; } + + [JsonProperty("fqdn")] + public string Fqdn { get; set; } + + [JsonProperty("app_name")] + public string AppName { get; set; } + + [JsonProperty("app_version")] + public string AppVersion { get; set; } + + [JsonProperty("current_status")] + public string CurrentStatus { get; set; } + + [JsonProperty("running")] + public bool Running { get; set; } + + [JsonProperty("whitelisting_active")] + public bool WhitelistingActive { get; set; } + + [JsonProperty("start_time")] + public string StartTime { get; set; } + + [JsonProperty("removal_time")] + public string RemovalTime { get; set; } + + [JsonProperty("elapsed_time")] + public int? ElapsedTime { get; set; } + + [JsonProperty("last_status")] + public string LastStatus { get; set; } + + [JsonProperty("error")] + public bool Error { get; set; } + + [JsonProperty("error_detail")] + public string ErrorDetail { get; set; } + + [JsonProperty("public_ip")] + public string PublicIp { get; set; } + + [JsonProperty("sessions")] + public SessionData[] Sessions { get; set; } + + [JsonProperty("location")] + public LocationData Location { get; set; } + + [JsonProperty("tags")] + public string[] Tags { get; set; } + + [JsonProperty("sockets")] + public string Sockets { get; set; } + + [JsonProperty("sockets_usage")] + public string SocketsUsage { get; set; } + + [JsonProperty("command")] + public string Command { get; set; } + + [JsonProperty("arguments")] + public string Arguments { get; set; } + + /// + /// TODO: Server should swap `ports` to an array of DeploymentPortsData (instead of an object of dynamic unknown objects). + /// + /// { + /// "7777", {} + /// }, + /// { + /// "Some Port Name", {} + /// } + /// + /// + [JsonProperty("ports")] + public Dictionary PortsDict { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetDeploymentStatusResult.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetDeploymentStatusResult.cs.meta new file mode 100644 index 0000000000..fb90a5974e --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetDeploymentStatusResult.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: c658b7f5c5d5d0648934b0ae1d71de9a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetDeploymentStatusResult.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetRegistryCredentialsResult.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetRegistryCredentialsResult.cs new file mode 100644 index 0000000000..8c3bd5457c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetRegistryCredentialsResult.cs @@ -0,0 +1,22 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Results +{ + /// + /// Result model for `GET v1/wizard/registry-credentials`. + /// + public class GetRegistryCredentialsResult + { + [JsonProperty("registry_url")] + public string RegistryUrl { get; set; } + + [JsonProperty("project")] + public string Project { get; set; } + + [JsonProperty("username")] + public string Username { get; set; } + + [JsonProperty("token")] + public string Token { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetRegistryCredentialsResult.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetRegistryCredentialsResult.cs.meta new file mode 100644 index 0000000000..c760a1a4ea --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetRegistryCredentialsResult.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 8e6af130c329d2b43b2f4b0dc8639477 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetRegistryCredentialsResult.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetYourPublicIpResult.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetYourPublicIpResult.cs new file mode 100644 index 0000000000..71d76b77f0 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetYourPublicIpResult.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Results +{ + /// + /// Result model for `GET v1/ip`. + /// GET API Doc | https://docs.edgegap.com/api/#tag/IP-Lookup/operation/IP + /// + public class GetYourPublicIpResult + { + [JsonProperty("public_ip")] + public string PublicIp { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetYourPublicIpResult.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetYourPublicIpResult.cs.meta new file mode 100644 index 0000000000..766d081e94 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetYourPublicIpResult.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 73c9651ef0fdfcb449ec0120016963a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/GetYourPublicIpResult.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/StopActiveDeploymentResult.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/StopActiveDeploymentResult.cs new file mode 100644 index 0000000000..5d4d6a0b44 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/StopActiveDeploymentResult.cs @@ -0,0 +1,89 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Results +{ + public class StopActiveDeploymentResult + { + [JsonProperty("message")] + public string Message { get; set; } + + [JsonProperty("deployment_summary")] + public DeploymentSummaryData DeploymentSummary { get; set; } + + + public class DeploymentSummaryData + { + [JsonProperty("request_id")] + public string RequestId { get; set; } + + [JsonProperty("fqdn")] + public string Fqdn { get; set; } + + [JsonProperty("app_name")] + public string AppName { get; set; } + + [JsonProperty("app_version")] + public string AppVersion { get; set; } + + [JsonProperty("current_status")] + public string CurrentStatus { get; set; } + + [JsonProperty("running")] + public bool Running { get; set; } + + [JsonProperty("whitelisting_active")] + public bool WhitelistingActive { get; set; } + + [JsonProperty("start_time")] + public string StartTime { get; set; } + + [JsonProperty("removal_time")] + public string RemovalTime { get; set; } + + [JsonProperty("elapsed_time")] + public int ElapsedTime { get; set; } + + [JsonProperty("last_status")] + public string LastStatus { get; set; } + + [JsonProperty("error")] + public bool Error { get; set; } + + [JsonProperty("error_detail")] + public string ErrorDetail { get; set; } + + [JsonProperty("ports")] + public PortsData Ports { get; set; } + + [JsonProperty("public_ip")] + public string PublicIp { get; set; } + + [JsonProperty("sessions")] + public SessionData[] Sessions { get; set; } + + [JsonProperty("location")] + public LocationData Location { get; set; } + + [JsonProperty("tags")] + public string[] Tags { get; set; } + + [JsonProperty("sockets")] + public string Sockets { get; set; } + + [JsonProperty("sockets_usage")] + public string SocketsUsage { get; set; } + + [JsonProperty("command")] + public string Command { get; set; } + + [JsonProperty("arguments")] + public string Arguments { get; set; } + + } + + public class PortsData + { + + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/StopActiveDeploymentResult.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/StopActiveDeploymentResult.cs.meta new file mode 100644 index 0000000000..580756556f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/StopActiveDeploymentResult.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 9e2e4d9424ca8f7459803e631acf912f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/StopActiveDeploymentResult.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/UpsertAppVersionResult.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/UpsertAppVersionResult.cs new file mode 100644 index 0000000000..bc869d5f24 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/UpsertAppVersionResult.cs @@ -0,0 +1,165 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models.Results +{ + /// + /// Result model for: + /// - `POST 1/app/{app_name}/version` + /// - `PATCH v1/app/{app_name}/version/{version_name}` + /// POST API Doc | https://docs.edgegap.com/api/#tag/Applications/operation/application-post + /// PATCH API Doc | https://docs.edgegap.com/api/#tag/Applications/operation/app-versions-patch + /// + public class UpsertAppVersionResult + { + [JsonProperty("success")] + public bool Success { get; set; } + + [JsonProperty("version")] + public VersionData Version { get; set; } + + public class VersionData + { + [JsonProperty("name")] + public string VersionName { get; set; } + + [JsonProperty("is_active")] + public bool IsActive { get; set; } + + [JsonProperty("docker_repository")] + public string DockerRepository { get; set; } + + [JsonProperty("docker_image")] + public string DockerImage { get; set; } + + [JsonProperty("docker_tag")] + public string DockerTag { get; set; } + + [JsonProperty("private_username")] + public string PrivateUsername { get; set; } + + [JsonProperty("private_token")] + public string PrivateToken { get; set; } + + [JsonProperty("req_cpu")] + public int? ReqCpu { get; set; } + + [JsonProperty("req_memory")] + public int? ReqMemory { get; set; } + + [JsonProperty("req_video")] + public int? ReqVideo { get; set; } + + [JsonProperty("max_duration")] + public int? MaxDuration { get; set; } + + [JsonProperty("use_telemetry")] + public bool UseTelemetry { get; set; } + + [JsonProperty("inject_context_env")] + public bool InjectContextEnv { get; set; } + + [JsonProperty("whitelisting_active")] + public bool WhitelistingActive { get; set; } + + [JsonProperty("force_cache")] + public bool ForceCache { get; set; } + + [JsonProperty("cache_min_hour")] + public int? CacheMinHour { get; set; } + + [JsonProperty("cache_max_hour")] + public int? CacheMaxHour { get; set; } + + [JsonProperty("time_to_deploy")] + public int? TimeToDeploy { get; set; } + + [JsonProperty("enable_all_locations")] + public bool EnableAllLocations { get; set; } + + [JsonProperty("session_config")] + public SessionConfigData SessionConfig { get; set; } + + [JsonProperty("ports")] + public PortsData[] Ports { get; set; } + + [JsonProperty("probe")] + public ProbeData Probe { get; set; } + + [JsonProperty("envs")] + public EnvsData[] Envs { get; set; } + + [JsonProperty("verify_image")] + public bool VerifyImage { get; set; } + + [JsonProperty("termination_grace_period_seconds")] + public int? TerminationGracePeriodSeconds { get; set; } + + [JsonProperty("endpoint_storage")] + public string EndpointStorage { get; set; } + + [JsonProperty("command")] + public string Command { get; set; } + + [JsonProperty("arguments")] + public string Arguments { get; set; } + } + + public class SessionConfigData + { + [JsonProperty("kind")] + public string Kind { get; set; } + + [JsonProperty("sockets")] + public int? Sockets { get; set; } + + [JsonProperty("autodeploy")] + public bool Autodeploy { get; set; } + + [JsonProperty("empty_ttl")] + public int? EmptyTtl { get; set; } + + [JsonProperty("session_max_duration")] + public int? SessionMaxDuration { get; set; } + } + + public class PortsData + { + [JsonProperty("port")] + public int? Port { get; set; } + + [JsonProperty("protocol")] + public string Protocol { get; set; } + + [JsonProperty("to_check")] + public bool ToCheck { get; set; } + + [JsonProperty("tls_upgrade")] + public bool TlsUpgrade { get; set; } + + [JsonProperty("name")] + public string PortName { get; set; } + } + + public class ProbeData + { + [JsonProperty("optimal_ping")] + public int? OptimalPing { get; set; } + + [JsonProperty("rejected_ping")] + public int? RejectedPing { get; set; } + } + + public class EnvsData + { + [JsonProperty("key")] + public string Key { get; set; } + + [JsonProperty("value")] + public string Value { get; set; } + + [JsonProperty("is_secret")] + public bool IsSecret { get; set; } + } + + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/UpsertAppVersionResult.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/UpsertAppVersionResult.cs.meta new file mode 100644 index 0000000000..fcc0c28f02 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/UpsertAppVersionResult.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: a7dde7d59c66d8c44b86af35e853f9f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/Results/UpsertAppVersionResult.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/SessionData.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/SessionData.cs new file mode 100644 index 0000000000..458da78d27 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/SessionData.cs @@ -0,0 +1,28 @@ +using Newtonsoft.Json; + +namespace Edgegap.Editor.Api.Models +{ + /// + /// Shared model for `GetDeploymentStatusResult`, `StopActiveDeploymentResult`. + /// + public class SessionData + { + [JsonProperty("session_id")] + public string SessionId { get; set; } + + [JsonProperty("status")] + public string Status { get; set; } + + [JsonProperty("ready")] + public bool Ready { get; set; } + + [JsonProperty("linked")] + public bool Linked { get; set; } + + [JsonProperty("kind")] + public string Kind { get; set; } + + [JsonProperty("user_count")] + public string UserCount { get; set; } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/SessionData.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/SessionData.cs.meta new file mode 100644 index 0000000000..7d35b5be96 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/SessionData.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 5f9024e4ca5438e4788e461387313531 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/Api/Models/SessionData.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/ButtonShaker.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/ButtonShaker.cs new file mode 100644 index 0000000000..40203eaa6f --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/ButtonShaker.cs @@ -0,0 +1,37 @@ +using System.Threading.Tasks; +using UnityEngine.UIElements; + +namespace Edgegap.Editor +{ + /// Slightly shake a UI button to indicate attention. + public class ButtonShaker + { + const string SHAKE_START_CLASS = "shakeStart"; + const string SHAKE_STOP_CLASS = "shakeEnd"; + private Button targetButton; + + public ButtonShaker(Button buttonToShake) => + targetButton = buttonToShake; + + /// Shake the button x times for x msDelayBetweenShakes each. + /// 1 shake = 1 bigger -> followed by 1 smaller. + /// + /// # of shakes + public async Task ApplyShakeAsync(int msDelayBetweenShakes = 40, int iterations = 2) + { + for (int i = 0; i < iterations; i++) + await shakeOnce(msDelayBetweenShakes); + } + + private async Task shakeOnce(int msDelayBetweenShakes) + { + targetButton.AddToClassList(SHAKE_START_CLASS); + await Task.Delay(msDelayBetweenShakes); // duration of the first transition + targetButton.RemoveFromClassList(SHAKE_START_CLASS); + + targetButton.AddToClassList(SHAKE_STOP_CLASS); + await Task.Delay(msDelayBetweenShakes); // duration of the second transition + targetButton.RemoveFromClassList(SHAKE_STOP_CLASS); + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/ButtonShaker.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/ButtonShaker.cs.meta new file mode 100644 index 0000000000..1c5c268a60 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/ButtonShaker.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: f963d64ffcf32ba4bba54fe1cd70b5a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/ButtonShaker.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapBuildUtils.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapBuildUtils.cs new file mode 100644 index 0000000000..50d814ab90 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapBuildUtils.cs @@ -0,0 +1,298 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using UnityEditor; +using UnityEditor.Build.Reporting; + +using Debug = UnityEngine.Debug; + +namespace Edgegap +{ + internal static class EdgegapBuildUtils + { + public static bool IsArmCPU() => + RuntimeInformation.ProcessArchitecture == Architecture.Arm || + RuntimeInformation.ProcessArchitecture == Architecture.Arm64; + + public static BuildReport BuildServer() + { + IEnumerable scenes = EditorBuildSettings.scenes.Select(s=>s.path); + BuildPlayerOptions options = new BuildPlayerOptions + { + scenes = scenes.ToArray(), + target = BuildTarget.StandaloneLinux64, + // MIRROR CHANGE +#if UNITY_2021_3_OR_NEWER + subtarget = (int)StandaloneBuildSubtarget.Server, // dedicated server with UNITY_SERVER define +#else + options = BuildOptions.EnableHeadlessMode, // obsolete and missing UNITY_SERVER define +#endif + // END MIRROR CHANGE + locationPathName = "Builds/EdgegapServer/ServerBuild" + }; + + return BuildPipeline.BuildPlayer(options); + } + + public static async Task DockerSetupAndInstallationCheck() + { + if (!File.Exists("Dockerfile")) + { + File.WriteAllText("Dockerfile", dockerFileText); + } + + string output = null; + string error = null; + await RunCommand_DockerVersion(msg => output = msg, msg => error = msg); // MIRROR CHANGE + if (!string.IsNullOrEmpty(error)) + { + Debug.LogError(error); + return false; + } + Debug.Log($"[Edgegap] Docker version detected: {output}"); // MIRROR CHANGE + return true; + } + + // MIRROR CHANGE + static async Task RunCommand_DockerVersion(Action outputReciever = null, Action errorReciever = null) + { +#if UNITY_EDITOR_WIN + await RunCommand("cmd.exe", "/c docker --version", outputReciever, errorReciever); +#elif UNITY_EDITOR_OSX + await RunCommand("/bin/bash", "-c \"docker --version\"", outputReciever, errorReciever); +#elif UNITY_EDITOR_LINUX + await RunCommand("/bin/bash", "-c \"docker --version\"", outputReciever, errorReciever); +#else + Debug.LogError("The platform is not supported yet."); +#endif + } + + // MIRROR CHANGE + public static async Task RunCommand_DockerBuild(string registry, string imageRepo, string tag, Action onStatusUpdate) + { + string realErrorMessage = null; + + // ARM -> x86 support: + // build commands use 'buildx' on ARM cpus for cross compilation. + // otherwise docker builds would not launch when deployed because + // Edgegap's infrastructure is on x86. instead the deployment logs + // would show an error in a linux .go file with 'not found'. + string buildCommand = IsArmCPU() ? "buildx build --platform linux/amd64" : "build"; + +#if UNITY_EDITOR_WIN + await RunCommand("docker.exe", $"{buildCommand} -t {registry}/{imageRepo}:{tag} .", onStatusUpdate, +#elif UNITY_EDITOR_OSX + await RunCommand("/bin/bash", $"-c \"docker {buildCommand} -t {registry}/{imageRepo}:{tag} .\"", onStatusUpdate, +#elif UNITY_EDITOR_LINUX + await RunCommand("/bin/bash", $"-c \"docker {buildCommand} -t {registry}/{imageRepo}:{tag} .\"", onStatusUpdate, +#endif + (msg) => + { + if (msg.Contains("ERROR")) + { + realErrorMessage = msg; + } + onStatusUpdate(msg); + }); + + if(realErrorMessage != null) + { + throw new Exception(realErrorMessage); + } + } + + public static async Task<(bool, string)> RunCommand_DockerPush(string registry, string imageRepo, string tag, Action onStatusUpdate) + { + string error = string.Empty; +#if UNITY_EDITOR_WIN + await RunCommand("docker.exe", $"push {registry}/{imageRepo}:{tag}", onStatusUpdate, (msg) => error += msg + "\n"); +#elif UNITY_EDITOR_OSX + await RunCommand("/bin/bash", $"-c \"docker push {registry}/{imageRepo}:{tag}\"", onStatusUpdate, (msg) => error += msg + "\n"); +#elif UNITY_EDITOR_LINUX + await RunCommand("/bin/bash", $"-c \"docker push {registry}/{imageRepo}:{tag}\"", onStatusUpdate, (msg) => error += msg + "\n"); +#endif + if (!string.IsNullOrEmpty(error)) + { + Debug.LogError(error); + return (false, error); + } + return (true, null); + } + // END MIRROR CHANGE + + static async Task RunCommand(string command, string arguments, Action outputReciever = null, Action errorReciever = null) + { + ProcessStartInfo startInfo = new ProcessStartInfo() + { + FileName = command, + Arguments = arguments, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + + // MIRROR CHANGE +#if !UNITY_EDITOR_WIN + // on mac, commands like 'docker' aren't found because it's not in the application's PATH + // even if it runs on mac's terminal. + // to solve this we need to do two steps: + // 1. add /usr/bin/local to PATH if it's not there already. often this is missing in the application. + // this is where docker is usually instaled. + // 2. add PATH to ProcessStartInfo + string existingPath = Environment.GetEnvironmentVariable("PATH"); + string customPath = $"{existingPath}:/usr/local/bin"; + startInfo.EnvironmentVariables["PATH"] = customPath; + // Debug.Log("PATH: " + customPath); +#endif + // END MIRROR CHANGE + + Process proc = new Process() { StartInfo = startInfo, }; + proc.EnableRaisingEvents = true; + + ConcurrentQueue errors = new ConcurrentQueue(); + ConcurrentQueue outputs = new ConcurrentQueue(); + + void pipeQueue(ConcurrentQueue q, Action opt) + { + while (!q.IsEmpty) + { + if (q.TryDequeue(out string msg) && !string.IsNullOrWhiteSpace(msg)) + { + opt?.Invoke(msg); + } + } + } + + proc.OutputDataReceived += (s, e) => outputs.Enqueue(e.Data); + proc.ErrorDataReceived += (s, e) => errors.Enqueue(e.Data); + + proc.Start(); + proc.BeginOutputReadLine(); + proc.BeginErrorReadLine(); + + while (!proc.HasExited) + { + await Task.Delay(100); + pipeQueue(errors, errorReciever); + pipeQueue(outputs, outputReciever); + } + + pipeQueue(errors, errorReciever); + pipeQueue(outputs, outputReciever); + + + } + + static void Proc_OutputDataReceived(object sender, DataReceivedEventArgs e) + { + throw new NotImplementedException(); + } + + static Regex lastDigitsRegex = new Regex("([0-9])+$"); + + public static string IncrementTag(string tag) + { + Match lastDigits = lastDigitsRegex.Match(tag); + if (!lastDigits.Success) + { + return tag + " _1"; + } + + int number = int.Parse(lastDigits.Groups[0].Value); + + number++; + + return lastDigitsRegex.Replace(tag, number.ToString()); + } + + public static void UpdateEdgegapAppTag(string tag) + { + // throw new NotImplementedException(); + } + + // -batchmode -nographics remains for Unity 2019/2020 support pre-dedicated server builds + static string dockerFileText = @"FROM ubuntu:bionic + +ARG DEBIAN_FRONTEND=noninteractive + +COPY Builds/EdgegapServer /root/build/ + +WORKDIR /root/ + +RUN chmod +x /root/build/ServerBuild + +ENTRYPOINT [ ""/root/build/ServerBuild"", ""-batchmode"", ""-nographics""] +"; + + /// Run a Docker cmd with streaming log response. TODO: Plugin to other Docker cmds + /// Throws if logs contain "ERROR" + /// + /// ex: "registry.edgegap.com" + /// ex: "robot$mycompany-asdf+client-push" + /// Different from ApiToken; sometimes called "Container Registry Password" + /// Log stream + // MIRROR CHANGE: CROSS PLATFORM SUPPORT + static async Task RunCommand_DockerLogin( + string registryUrl, + string repoUsername, + string repoPasswordToken, + Action outputReciever = null, Action errorReciever = null) + { + // TODO: Use --password-stdin for security (!) This is no easy task for child Process | https://stackoverflow.com/q/51489359/6541639 + // (!) Don't use single quotes for cross-platform support (works unexpectedly in `cmd`). + + try + { +#if UNITY_EDITOR_WIN + await RunCommand("cmd.exe", $"/c docker login -u \"{repoUsername}\" --password \"{repoPasswordToken}\" \"{registryUrl}\"", outputReciever, errorReciever); +#elif UNITY_EDITOR_OSX + await RunCommand("/bin/bash", $"-c \"docker login -u \"{repoUsername}\" --password \"{repoPasswordToken}\" \"{registryUrl}\"\"", outputReciever, errorReciever); +#elif UNITY_EDITOR_LINUX + await RunCommand("/bin/bash", $"-c \"docker login -u \"{repoUsername}\" --password \"{repoPasswordToken}\" \"{registryUrl}\"\"", outputReciever, errorReciever); +#else + Debug.LogError("The platform is not supported yet."); +#endif + } + catch (Exception e) + { + Debug.LogError($"Error: {e}"); + return false; + } + + return true; + } + + /// + /// v2: Login to Docker Registry via RunCommand(), returning streamed log messages: + /// "docker login {registryUrl} {repository} {repoUsername} {repoPasswordToken}" + /// + /// ex: "registry.edgegap.com" + /// ex: "robot$mycompany-asdf+client-push" + /// Different from ApiToken; sometimes called "Container Registry Password" + /// Log stream + /// isSuccess + public static async Task LoginContainerRegistry( + string registryUrl, + string repoUsername, + string repoPasswordToken, + Action onStatusUpdate) + { + string error = null; + await RunCommand_DockerLogin(registryUrl, repoUsername, repoPasswordToken, onStatusUpdate, msg => error = msg); // MIRROR CHANGE + if (error.Contains("ERROR")) + { + Debug.LogError(error); + return false; + } + return true; + } + + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapBuildUtils.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapBuildUtils.cs.meta new file mode 100644 index 0000000000..33a0fdfc91 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapBuildUtils.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 97dadab2a073d8b47bf9a270401f0a8f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapBuildUtils.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapScriptEditor.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapScriptEditor.cs new file mode 100644 index 0000000000..a01f1c7195 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapScriptEditor.cs @@ -0,0 +1,25 @@ +using UnityEditor; +using UnityEngine.UIElements; +using Edgegap; + +[CustomEditor(typeof(EdgegapToolScript))] +public class EdgegapPluginScriptEditor : Editor +{ + VisualElement _serverDataContainer; + + private void OnEnable() + { + _serverDataContainer = EdgegapServerDataManager.GetServerDataVisualTree(); + EdgegapServerDataManager.RegisterServerDataContainer(_serverDataContainer); + } + + private void OnDisable() + { + EdgegapServerDataManager.DeregisterServerDataContainer(_serverDataContainer); + } + + public override VisualElement CreateInspectorGUI() + { + return _serverDataContainer; + } +} \ No newline at end of file diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapScriptEditor.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapScriptEditor.cs.meta new file mode 100644 index 0000000000..d3aaace540 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapScriptEditor.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: c4c676ae6dcca0e458c6a8f06571f8fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapScriptEditor.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerData.uss b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerData.uss new file mode 100644 index 0000000000..15cb5e3921 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerData.uss @@ -0,0 +1,81 @@ +.row__port-table { + padding: 2px 4px; + display: flex; + flex-direction: row; + align-items: center; + width: auto; + justify-content: space-around; + -unity-text-align: middle-left; +} + + .row__port-table > * { + width: 0px; + flex-grow: 1; + align-self: center; + margin: 0px; + padding: 0px; + } + +.focusable:hover { + background-color: rgba(0,0,0,0.2); + border-radius: 3px; +} + +.row__dns { + display: flex; + flex-direction: row; + align-items: center; + width: auto; + justify-content: space-between; + -unity-text-align: middle-left; +} + +.row__status { + display: flex; + flex-direction: row; + align-items: center; + width: auto; + justify-content: space-between; + -unity-text-align: middle-left; +} + +.label__header { + -unity-font-style: bold +} + +.label__status { + -unity-font-style: bold; + border-radius: 2px; + width: 100px; + color: #fff; + -unity-text-align: middle-center; +} + +.label__info-text { + padding: 8px; + margin: 4px; + border-radius: 3px; + -unity-text-align: middle-center; + white-space: normal; + background-color: rgba(42, 42, 42, 0.5); +} + +.container { + margin: 8px 0px; +} + +.bg--secondary { + background-color: #8a8a8a; +} + +.bg--success { + background-color: #90be6d; +} + +.bg--danger { + background-color: #f94144; +} + +.bg--warning { + background-color: #f9c74f; +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerData.uss.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerData.uss.meta new file mode 100644 index 0000000000..91658957e4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerData.uss.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: da5e3f58bd8cde14789f7c61df3f59f4 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} + disableValidation: 0 +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerData.uss + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerDataManager.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerDataManager.cs new file mode 100644 index 0000000000..7ed5c0e88a --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerDataManager.cs @@ -0,0 +1,240 @@ +using IO.Swagger.Model; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; +using UnityEngine.UIElements; + +namespace Edgegap +{ + static class EdgegapServerDataManagerUtils + { + public static Label GetHeader(string text) + { + Label header = new Label(text); + header.AddToClassList("label__header"); + + return header; + } + + public static VisualElement GetHeaderRow() + { + VisualElement row = new VisualElement(); + row.AddToClassList("row__port-table"); + row.AddToClassList("label__header"); + + row.Add(new Label("Name")); + row.Add(new Label("External")); + row.Add(new Label("Internal")); + row.Add(new Label("ProtocolStr")); + row.Add(new Label("Link")); + + return row; + } + + public static VisualElement GetRowFromPortResponse(PortMapping port) + { + VisualElement row = new VisualElement(); + row.AddToClassList("row__port-table"); + row.AddToClassList("focusable"); + + + row.Add(new Label(port.Name)); + row.Add(new Label(port.External.ToString())); + row.Add(new Label(port.Internal.ToString())); + row.Add(new Label(port.Protocol)); + row.Add(GetCopyButton("Copy", port.Link)); + + return row; + } + + public static Button GetCopyButton(string btnText, string copiedText) + { + Button copyBtn = new Button(); + copyBtn.text = btnText; + copyBtn.clickable.clicked += () => GUIUtility.systemCopyBuffer = copiedText; + + return copyBtn; + } + + public static Button GetLinkButton(string btnText, string targetUrl) + { + Button copyBtn = new Button(); + copyBtn.text = btnText; + copyBtn.clickable.clicked += () => UnityEngine.Application.OpenURL(targetUrl); + + return copyBtn; + } + public static Label GetInfoText(string innerText) + { + Label infoText = new Label(innerText); + infoText.AddToClassList("label__info-text"); + + return infoText; + } + } + + /// + /// Utility class to centrally manage the Edgegap server data, and create / update the elements displaying the server info. + /// + public static class EdgegapServerDataManager + { + internal static Status _serverData; + private static ApiEnvironment _apiEnvironment; + + // UI elements + private static readonly StyleSheet _serverDataStylesheet; + private static readonly List _serverDataContainers = new List(); + + public static Status GetServerStatus() => _serverData; + + static EdgegapServerDataManager() + { + _serverDataStylesheet = AssetDatabase.LoadAssetAtPath("Assets/Edgegap/Editor/EdgegapServerData.uss"); + } + public static void RegisterServerDataContainer(VisualElement serverDataContainer) + { + _serverDataContainers.Add(serverDataContainer); + } + public static void DeregisterServerDataContainer(VisualElement serverDataContainer) + { + _serverDataContainers.Remove(serverDataContainer); + } + public static void SetServerData(Status serverData, ApiEnvironment apiEnvironment) + { + _serverData = serverData; + _apiEnvironment = apiEnvironment; + RefreshServerDataContainers(); + } + + private static VisualElement GetStatusSection() + { + ServerStatus serverStatus = _serverData.GetServerStatus(); + string dashboardUrl = _apiEnvironment.GetDashboardUrl(); + string requestId = _serverData.RequestId; + string deploymentDashboardUrl = ""; + + if (!string.IsNullOrEmpty(requestId) && !string.IsNullOrEmpty(dashboardUrl)) + { + deploymentDashboardUrl = $"{dashboardUrl}/arbitrium/deployment/read/{requestId}/"; + } + + VisualElement container = new VisualElement(); + container.AddToClassList("container"); + + container.Add(EdgegapServerDataManagerUtils.GetHeader("Server Status")); + + VisualElement row = new VisualElement(); + row.AddToClassList("row__status"); + + // Status pill + Label statusLabel = new Label(serverStatus.GetLabelText()); + statusLabel.AddToClassList(serverStatus.GetStatusBgClass()); + statusLabel.AddToClassList("label__status"); + row.Add(statusLabel); + + // Link to dashboard + if (!string.IsNullOrEmpty(deploymentDashboardUrl)) + { + row.Add(EdgegapServerDataManagerUtils.GetLinkButton("See in the dashboard", deploymentDashboardUrl)); + } + else + { + row.Add(new Label("Could not resolve link to this deployment")); + } + + container.Add(row); + + return container; + } + + private static VisualElement GetDnsSection() + { + string serverDns = _serverData.Fqdn; + + VisualElement container = new VisualElement(); + container.AddToClassList("container"); + + container.Add(EdgegapServerDataManagerUtils.GetHeader("Server DNS")); + + VisualElement row = new VisualElement(); + row.AddToClassList("row__dns"); + row.AddToClassList("focusable"); + + row.Add(new Label(serverDns)); + row.Add(EdgegapServerDataManagerUtils.GetCopyButton("Copy", serverDns)); + + container.Add(row); + + return container; + } + + private static VisualElement GetPortsSection() + { + List serverPorts = _serverData.Ports.Values.ToList(); + + VisualElement container = new VisualElement(); + container.AddToClassList("container"); + + container.Add(EdgegapServerDataManagerUtils.GetHeader("Server PortsDict")); + container.Add(EdgegapServerDataManagerUtils.GetHeaderRow()); + + VisualElement portList = new VisualElement(); + + if (serverPorts.Count > 0) + { + foreach (PortMapping port in serverPorts) + { + portList.Add(EdgegapServerDataManagerUtils.GetRowFromPortResponse(port)); + } + } + else + { + portList.Add(new Label("No port configured for this app version.")); + } + + container.Add(portList); + + return container; + } + + public static VisualElement GetServerDataVisualTree() + { + VisualElement serverDataTree = new VisualElement(); + serverDataTree.styleSheets.Add(_serverDataStylesheet); + + bool hasServerData = _serverData != null; + bool isReady = hasServerData && _serverData.GetServerStatus().IsOneOf(ServerStatus.Ready, ServerStatus.Error); + + if (hasServerData) + { + serverDataTree.Add(GetStatusSection()); + + if (isReady) + { + serverDataTree.Add(GetDnsSection()); + serverDataTree.Add(GetPortsSection()); + } + else + { + serverDataTree.Add(EdgegapServerDataManagerUtils.GetInfoText("Additional information will be displayed when the server is ready.")); + } + } + else + { + serverDataTree.Add(EdgegapServerDataManagerUtils.GetInfoText("Server data will be displayed here when a server is running.")); + } + + return serverDataTree; + } + + private static void RefreshServerDataContainers() + { + foreach (VisualElement serverDataContainer in _serverDataContainers) + { + serverDataContainer.Clear(); + serverDataContainer.Add(GetServerDataVisualTree()); // Cannot reuse a same instance of VisualElement + } + } + } +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerDataManager.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerDataManager.cs.meta new file mode 100644 index 0000000000..b64af8c058 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerDataManager.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 39f5f27c13279a34eb116630a00e41c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapServerDataManager.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapToolScript.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapToolScript.cs new file mode 100644 index 0000000000..870190d23c --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapToolScript.cs @@ -0,0 +1,12 @@ +using UnityEngine; +using Edgegap; +using IO.Swagger.Model; + +/// +/// This script acts as an interface to display and use the necessary variables from the Edgegap tool. +/// The server info can be accessed from the tool window, as well as through the public script property. +/// +public class EdgegapToolScript : MonoBehaviour +{ + public Status ServerStatus => EdgegapServerDataManager.GetServerStatus(); +} diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapToolScript.cs.meta b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapToolScript.cs.meta new file mode 100644 index 0000000000..d69fa0f2bd --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapToolScript.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 5963202433da25448a22def99f5a598b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 129321 + packageName: Mirror + packageVersion: 89.0.0 + assetPath: Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapToolScript.cs + uploadId: 648641 diff --git a/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapWindow.cs b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapWindow.cs new file mode 100644 index 0000000000..6eccd48de4 --- /dev/null +++ b/Assets/ImportedAssets/Mirror/Hosting/Edgegap/Editor/EdgegapWindow.cs @@ -0,0 +1,986 @@ +// MIRROR CHANGE: disable this completely. otherwise InitUIElements can still throw NRE. +/* +using UnityEditor; +using UnityEngine; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Collections.Generic; +using Newtonsoft.Json; +using System.Net; +using System.Text; +using System; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using IO.Swagger.Model; +using UnityEditor.Build.Reporting; +using Application = UnityEngine.Application; + +namespace Edgegap +{ + public class EdgegapWindow : EditorWindow + { + // MIRROR CHANGE: create HTTPClient in-place to avoid InvalidOperationExceptions when reusing + // static readonly HttpClient _httpClient = new HttpClient(); + // END MIRROR CHANGE + + const string EditorDataSerializationName = "EdgegapSerializationData"; + const int ServerStatusCronjobIntervalMs = 10000; // Interval at which the server status is updated + + // MIRROR CHANGE + // get the path of this .cs file so we don't need to hardcode paths to + // the .uxml and .uss files: + // https://forum.unity.com/threads/too-many-hard-coded-paths-in-the-templates-and-documentation.728138/ + // this way users can move this folder without breaking UIToolkit paths. + internal string StylesheetPath => + Path.GetDirectoryName(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this))); + // END MIRROR CHANGE + + readonly System.Timers.Timer _updateServerStatusCronjob = new System.Timers.Timer(ServerStatusCronjobIntervalMs); + + [SerializeField] string _userExternalIp; + [SerializeField] string _apiKey; + [SerializeField] ApiEnvironment _apiEnvironment; + [SerializeField] string _appName; + [SerializeField] string _appVersionName; + [SerializeField] string _deploymentRequestId; + + [SerializeField] string _containerRegistry; + [SerializeField] string _containerImageRepo; + [SerializeField] string _containerImageTag; + [SerializeField] bool _autoIncrementTag = true; + + + VisualTreeAsset _visualTree; + bool _shouldUpdateServerStatus = false; + + // Interactable elements + EnumField _apiEnvironmentSelect; + TextField _apiKeyInput; + TextField _appNameInput; + TextField _appVersionNameInput; + TextField _containerRegistryInput; + TextField _containerImageRepoInput; + TextField _containerImageTagInput; + Toggle _autoIncrementTagInput; + Button _connectionButton; + Button _serverActionButton; + Button _documentationBtn; + Button _buildAndPushServerBtn; + + // Readonly elements + Label _connectionStatusLabel; + VisualElement _serverDataContainer; + + // server data manager + StyleSheet _serverDataStylesheet; + List _serverDataContainers = new List(); + + [Obsolete("See EdgegapWindowV2.ShowEdgegapToolWindow()")] + // [MenuItem("Edgegap/Server Management")] + public static void ShowEdgegapToolWindow() + { + EdgegapWindow window = GetWindow(); + window.titleContent = new GUIContent("Edgegap Hosting"); // MIRROR CHANGE + } + + protected void OnEnable() + { + // Set root VisualElement and style + // BEGIN MIRROR CHANGE + _visualTree = AssetDatabase.LoadAssetAtPath($"{StylesheetPath}/EdgegapWindow.uxml"); + StyleSheet styleSheet = AssetDatabase.LoadAssetAtPath($"{StylesheetPath}/EdgegapWindow.uss"); + _serverDataStylesheet = AssetDatabase.LoadAssetAtPath($"{StylesheetPath}/EdgegapServerData.uss"); + // END MIRROR CHANGE + rootVisualElement.styleSheets.Add(styleSheet); + + LoadToolData(); + + if (string.IsNullOrWhiteSpace(_userExternalIp)) + { + _userExternalIp = GetExternalIpAddress(); + } + } + + protected void Update() + { + if (_shouldUpdateServerStatus) + { + _shouldUpdateServerStatus = false; + UpdateServerStatus(); + } + } + + public void CreateGUI() + { + rootVisualElement.Clear(); + _visualTree.CloneTree(rootVisualElement); + + InitUIElements(); + SyncFormWithObject(); + + bool hasActiveDeployment = !string.IsNullOrEmpty(_deploymentRequestId); + + if (hasActiveDeployment) + { + RestoreActiveDeployment(); + } + else + { + DisconnectCallback(); + } + } + + protected void OnDestroy() + { + bool deploymentActive = !string.IsNullOrEmpty(_deploymentRequestId); + + if (deploymentActive) + { + EditorUtility.DisplayDialog( + "Warning", + $"You have an active deployment ({_deploymentRequestId}) that won't be stopped automatically.", + "Ok" + ); + } + } + + protected void OnDisable() + { + SyncObjectWithForm(); + SaveToolData(); + DeregisterServerDataContainer(_serverDataContainer); + } + + /// + /// Binds the form inputs to the associated variables and initializes the inputs as required. + /// Requires the VisualElements to be loaded before this call. Otherwise, the elements cannot be found. + /// + void InitUIElements() + { + _apiEnvironmentSelect = rootVisualElement.Q("environmentSelect"); + _apiKeyInput = rootVisualElement.Q("apiKey"); + _appNameInput = rootVisualElement.Q("appName"); + _appVersionNameInput = rootVisualElement.Q("appVersionName"); + + _containerRegistryInput = rootVisualElement.Q("containerRegistry"); + _containerImageRepoInput = rootVisualElement.Q("containerImageRepo"); + _containerImageTagInput = rootVisualElement.Q("tag"); + _autoIncrementTagInput = rootVisualElement.Q("autoIncrementTag"); + + _connectionButton = rootVisualElement.Q