diff --git a/Assets/Code/ActController.cs b/Assets/Code/ActController.cs index c606b22..572c631 100644 --- a/Assets/Code/ActController.cs +++ b/Assets/Code/ActController.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using UnityEngine; -using UnityEngine.UI; using UnityEngine.EventSystems; @@ -18,16 +16,6 @@ public abstract class ActController : MonoBehaviour public Canvas canvas = null; public EventSystem eventSystem = null; - [Serializable] - public class ActSettings { - public string type; - } - - [Serializable] - public class ActResults { - - }; - [Serializable] public class InvalidPhaseException : Exception { public readonly ActPhase currentPhase; @@ -40,15 +28,6 @@ public abstract class ActController : MonoBehaviour [Serializable] public class MissingSettingsException : Exception {}; - [Serializable] - public enum ActPhase { - NONE, - INIT, - START, - END, - CLEANUP - } - public ActPhase Phase { get; } /// diff --git a/Assets/Code/ActController.cs.meta b/Assets/Code/ActController.cs.meta index 4a78411..bf4e940 100644 --- a/Assets/Code/ActController.cs.meta +++ b/Assets/Code/ActController.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {fileID: 4422084297763085224, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/ActPhase.cs b/Assets/Code/ActPhase.cs new file mode 100644 index 0000000..800abbc --- /dev/null +++ b/Assets/Code/ActPhase.cs @@ -0,0 +1,11 @@ +using System; + + +[Serializable] +public enum ActPhase { + NONE, + INIT, + START, + END, + CLEANUP +} diff --git a/Assets/Code/ActPhase.cs.meta b/Assets/Code/ActPhase.cs.meta new file mode 100644 index 0000000..9717415 --- /dev/null +++ b/Assets/Code/ActPhase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7e1d130c18e44bc4fa2a106ff85bd45d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Code/ActResults.cs b/Assets/Code/ActResults.cs new file mode 100644 index 0000000..bb8bdf7 --- /dev/null +++ b/Assets/Code/ActResults.cs @@ -0,0 +1,5 @@ +using System; + + +[Serializable] +public class ActResults {}; diff --git a/Assets/Code/ActResults.cs.meta b/Assets/Code/ActResults.cs.meta new file mode 100644 index 0000000..300b82e --- /dev/null +++ b/Assets/Code/ActResults.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ff258aa9f24aa1b4d9c0c402166784d0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Code/ActSettings.cs b/Assets/Code/ActSettings.cs new file mode 100644 index 0000000..98a2d03 --- /dev/null +++ b/Assets/Code/ActSettings.cs @@ -0,0 +1,7 @@ +using System; + + +[Serializable] +public class ActSettings { + public string type; +} diff --git a/Assets/Code/ActSettings.cs.meta b/Assets/Code/ActSettings.cs.meta new file mode 100644 index 0000000..a190193 --- /dev/null +++ b/Assets/Code/ActSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb49ab9cfe218ab47bececca8851077c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Code/DrawTool.cs.meta b/Assets/Code/DrawTool.cs.meta index f43c100..d54d214 100644 --- a/Assets/Code/DrawTool.cs.meta +++ b/Assets/Code/DrawTool.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {fileID: 4422084297763085224, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/DrawableFrame.cs b/Assets/Code/DrawableFrame.cs index 00ffa0c..f47ef52 100644 --- a/Assets/Code/DrawableFrame.cs +++ b/Assets/Code/DrawableFrame.cs @@ -1,6 +1,5 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; +using UnityEngine; + public class DrawableFrame : MonoBehaviour { diff --git a/Assets/Code/DrawableFrame.cs.meta b/Assets/Code/DrawableFrame.cs.meta index 7562f18..849865c 100644 --- a/Assets/Code/DrawableFrame.cs.meta +++ b/Assets/Code/DrawableFrame.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: -50 - icon: {fileID: 4422084297763085224, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/DrawingController.cs b/Assets/Code/DrawingController.cs index 4bca034..d2fb17b 100644 --- a/Assets/Code/DrawingController.cs +++ b/Assets/Code/DrawingController.cs @@ -22,35 +22,6 @@ public class DrawingController : ActController protected Text actName; protected Text actDescription; protected Timer actTimer; - - [Serializable] - public class DrawingSettings : ActSettings { - public Color startingColor = Color.white; - public List palette = new List(); - public float timeLimit = 99f; - public string actName = "Untitled"; - public string actDescription = "This Act is missing a description."; - public string destinationPool = "default"; - - public DrawingSettings(Color startingColor, List palette, float timeLimit, string actName, string actDescription, string destinationPool) { - this.type = "Drawing"; - this.startingColor = startingColor; - this.palette = palette; - this.timeLimit = timeLimit; - this.actName = actName; - this.actDescription = actDescription; - this.destinationPool = destinationPool; - } - } - - [Serializable] - public class DrawingResults : ActResults { - public readonly byte[] pngBytes; - - public DrawingResults(byte[] pngBytes) { - this.pngBytes = pngBytes; - } - } public override void ActInit() { base.ActInit(); diff --git a/Assets/Code/DrawingController.cs.meta b/Assets/Code/DrawingController.cs.meta index 67663e4..a3be237 100644 --- a/Assets/Code/DrawingController.cs.meta +++ b/Assets/Code/DrawingController.cs.meta @@ -19,7 +19,7 @@ MonoImporter: - actTimerPrefab: {fileID: 8049216009855113645, guid: 2ecb10bfea7885e40ad4340fa7eaa265, type: 3} executionOrder: 0 - icon: {fileID: -5397416234189338067, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/DrawingResults.cs b/Assets/Code/DrawingResults.cs new file mode 100644 index 0000000..c0f3afc --- /dev/null +++ b/Assets/Code/DrawingResults.cs @@ -0,0 +1,11 @@ +using System; + + +[Serializable] +public class DrawingResults : ActResults { + public readonly byte[] pngBytes; + + public DrawingResults(byte[] pngBytes) { + this.pngBytes = pngBytes; + } +} \ No newline at end of file diff --git a/Assets/Code/DrawingResults.cs.meta b/Assets/Code/DrawingResults.cs.meta new file mode 100644 index 0000000..eb653e3 --- /dev/null +++ b/Assets/Code/DrawingResults.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c8c417ef78cbd61438bff61a5dda66de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Code/DrawingSettings.cs b/Assets/Code/DrawingSettings.cs new file mode 100644 index 0000000..e2a70a7 --- /dev/null +++ b/Assets/Code/DrawingSettings.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + + +[Serializable] +public class DrawingSettings : ActSettings { + public Color startingColor = Color.white; + public List palette = new List(); + public float timeLimit = 99f; + public string actName = "Untitled"; + public string actDescription = "This Act is missing a description."; + public string destinationPool = "default"; + + public DrawingSettings(Color startingColor, List palette, float timeLimit, string actName, string actDescription, string destinationPool) { + this.type = "Drawing"; + this.startingColor = startingColor; + this.palette = palette; + this.timeLimit = timeLimit; + this.actName = actName; + this.actDescription = actDescription; + this.destinationPool = destinationPool; + } +} \ No newline at end of file diff --git a/Assets/Code/DrawingSettings.cs.meta b/Assets/Code/DrawingSettings.cs.meta new file mode 100644 index 0000000..b938580 --- /dev/null +++ b/Assets/Code/DrawingSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b882786176f59d04b897dfa2cfbe3f95 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Code/NetworkMessages.cs b/Assets/Code/NetworkMessages.cs new file mode 100644 index 0000000..be89142 --- /dev/null +++ b/Assets/Code/NetworkMessages.cs @@ -0,0 +1,48 @@ +using System; +using Mirror; + + +namespace NetMessages { + + public class ErrorMessage : MessageBase + { + public string errorName; + public string errorDescription = ""; + } + + public class PlayerConnectionMessage : MessageBase + { + public string playerName; + public string gamePassword; + } + + public class ViewerConnectionMessage : MessageBase + { + public string gamePassword; + } + + public class ConnectionSuccessfulResponse : MessageBase + { + public string[] playersConnected; + } + + public class NewPlayerConnectedNotification : MessageBase + { + public string playerName; + } + + public class GameStartMessage : MessageBase + { + + } + + public class ActSettingsMessage : MessageBase + { + public ActSettings settings; + } + + public class ActResultsMessage : MessageBase + { + public ActResults results; + } +} \ No newline at end of file diff --git a/Assets/Code/NetworkMessages.cs.meta b/Assets/Code/NetworkMessages.cs.meta new file mode 100644 index 0000000..7470ddf --- /dev/null +++ b/Assets/Code/NetworkMessages.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 26964efd4b147744fb4bb183d75abaa6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Code/PaletteButton.cs.meta b/Assets/Code/PaletteButton.cs.meta index 54f24c2..35ba98a 100644 --- a/Assets/Code/PaletteButton.cs.meta +++ b/Assets/Code/PaletteButton.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {fileID: 4422084297763085224, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/PencilTool.cs.meta b/Assets/Code/PencilTool.cs.meta index af0edfd..987655e 100644 --- a/Assets/Code/PencilTool.cs.meta +++ b/Assets/Code/PencilTool.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {fileID: 4422084297763085224, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/PlayerMainController.cs b/Assets/Code/PlayerMainController.cs index b2ce6cb..c0368d2 100644 --- a/Assets/Code/PlayerMainController.cs +++ b/Assets/Code/PlayerMainController.cs @@ -1,6 +1,4 @@ using System; -using System.Collections; -using System.Collections.Generic; using UnityEngine; @@ -31,15 +29,15 @@ public class PlayerMainController : MonoBehaviour }; public void LoadAct(string jsonData) { - ActController.ActSettings unknownSettings = JsonUtility.FromJson(jsonData); + ActSettings unknownSettings = JsonUtility.FromJson(jsonData); if(unknownSettings.type == "Drawing") { currentAct = Instantiate(drawingControllerPrefab, transform).GetComponent(); - currentAct.settings = JsonUtility.FromJson(jsonData); + currentAct.settings = JsonUtility.FromJson(jsonData); } else if (unknownSettings.type == "Typing") { currentAct = Instantiate(typingControllerPrefab, transform).GetComponent(); - currentAct.settings = JsonUtility.FromJson(jsonData); + currentAct.settings = JsonUtility.FromJson(jsonData); } else { throw new InvalidJsonDataException(jsonData); diff --git a/Assets/Code/PlayerMainController.cs.meta b/Assets/Code/PlayerMainController.cs.meta index 54d6ef8..a365aea 100644 --- a/Assets/Code/PlayerMainController.cs.meta +++ b/Assets/Code/PlayerMainController.cs.meta @@ -10,7 +10,7 @@ MonoImporter: - typingControllerPrefab: {fileID: 2942172269146964315, guid: d91131f9599079b4d96bfefa29d77a3a, type: 3} executionOrder: 0 - icon: {fileID: -5397416234189338067, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/RadiusSlider.cs.meta b/Assets/Code/RadiusSlider.cs.meta index 0cad16a..737566e 100644 --- a/Assets/Code/RadiusSlider.cs.meta +++ b/Assets/Code/RadiusSlider.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {fileID: 4422084297763085224, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/ServerMainController.cs b/Assets/Code/ServerMainController.cs new file mode 100644 index 0000000..b56c04b --- /dev/null +++ b/Assets/Code/ServerMainController.cs @@ -0,0 +1,15 @@ +using UnityEngine; +using System.Collections.Generic; +using Mirror; + +public class ServerMainController : MonoBehaviour +{ + public const int MAX_CONNECTIONS = 32; + + public bool isListening = false; + + public void ServerStart() { + NetworkServer.Listen(MAX_CONNECTIONS); + isListening = true; + } +} diff --git a/Assets/Code/ServerMainController.cs.meta b/Assets/Code/ServerMainController.cs.meta new file mode 100644 index 0000000..313bd09 --- /dev/null +++ b/Assets/Code/ServerMainController.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 89fe2c8d614a60e42b42812f5bdcfb7f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Code/Submit.cs.meta b/Assets/Code/Submit.cs.meta index 85d733c..efe78ce 100644 --- a/Assets/Code/Submit.cs.meta +++ b/Assets/Code/Submit.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {fileID: 4422084297763085224, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/Timer.cs.meta b/Assets/Code/Timer.cs.meta index da882b0..465c084 100644 --- a/Assets/Code/Timer.cs.meta +++ b/Assets/Code/Timer.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {fileID: 4422084297763085224, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/TimerToText.cs.meta b/Assets/Code/TimerToText.cs.meta index 5b7747e..a753f2e 100644 --- a/Assets/Code/TimerToText.cs.meta +++ b/Assets/Code/TimerToText.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {fileID: 4422084297763085224, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/TypingController.cs b/Assets/Code/TypingController.cs index 789a639..f9c3902 100644 --- a/Assets/Code/TypingController.cs +++ b/Assets/Code/TypingController.cs @@ -25,31 +25,6 @@ public class TypingController : ActController protected Submit submit; protected Text submittedCount; - [Serializable] - public class TypingSettings : ActSettings { - public float timeLimit = 99f; - public string actName = "Untitled"; - public string actDescription = "This Act is missing a description."; - public string destinationPool = "default"; - - public TypingSettings(float timeLimit, string actName, string actDescription, string destinationPool) { - this.type = "Typing"; - this.timeLimit = timeLimit; - this.actName = actName; - this.actDescription = actDescription; - this.destinationPool = destinationPool; - } - } - - [Serializable] - public class TypingResults : ActResults { - public List submissions; - - public TypingResults(List submissions) { - this.submissions = submissions; - } - } - protected override void Start() { base.Start(); submissions = new List(); diff --git a/Assets/Code/TypingController.cs.meta b/Assets/Code/TypingController.cs.meta index 61420fc..a347043 100644 --- a/Assets/Code/TypingController.cs.meta +++ b/Assets/Code/TypingController.cs.meta @@ -19,7 +19,7 @@ MonoImporter: - submittedCountPrefab: {fileID: 3217623250842909506, guid: ea05f9737b8776c4faf05bf53c37b4b9, type: 3} executionOrder: 0 - icon: {fileID: -5397416234189338067, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Code/TypingResults.cs b/Assets/Code/TypingResults.cs new file mode 100644 index 0000000..da58766 --- /dev/null +++ b/Assets/Code/TypingResults.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; + + +[Serializable] +public class TypingResults : ActResults { + public List submissions; + + public TypingResults(List submissions) { + this.submissions = submissions; + } +} \ No newline at end of file diff --git a/Assets/Code/TypingResults.cs.meta b/Assets/Code/TypingResults.cs.meta new file mode 100644 index 0000000..2abf9a2 --- /dev/null +++ b/Assets/Code/TypingResults.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 400c8f3c2f7b6cf468dc2eb5fcccea62 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Code/TypingSettings.cs b/Assets/Code/TypingSettings.cs new file mode 100644 index 0000000..d897559 --- /dev/null +++ b/Assets/Code/TypingSettings.cs @@ -0,0 +1,18 @@ +using System; + + +[Serializable] +public class TypingSettings : ActSettings { + public float timeLimit = 99f; + public string actName = "Untitled"; + public string actDescription = "This Act is missing a description."; + public string destinationPool = "default"; + + public TypingSettings(float timeLimit, string actName, string actDescription, string destinationPool) { + this.type = "Typing"; + this.timeLimit = timeLimit; + this.actName = actName; + this.actDescription = actDescription; + this.destinationPool = destinationPool; + } +} \ No newline at end of file diff --git a/Assets/Code/TypingSettings.cs.meta b/Assets/Code/TypingSettings.cs.meta new file mode 100644 index 0000000..9d9000b --- /dev/null +++ b/Assets/Code/TypingSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f1b1ace24b994a418057ba3c7e97810 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Code/Utils.cs.meta b/Assets/Code/Utils.cs.meta index 3befb18..06d9c8d 100644 --- a/Assets/Code/Utils.cs.meta +++ b/Assets/Code/Utils.cs.meta @@ -5,7 +5,7 @@ MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 - icon: {fileID: 7866945982896999795, guid: 0000000000000000d000000000000000, type: 0} + icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Packages.meta b/Assets/Packages.meta new file mode 100644 index 0000000..b4e5532 --- /dev/null +++ b/Assets/Packages.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d2723bee01450514382d1e32aa01f968 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror.meta b/Assets/Packages/Mirror.meta new file mode 100644 index 0000000..a7a3dd0 --- /dev/null +++ b/Assets/Packages/Mirror.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5cf8eb36be0834b3da408c694a41cb88 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Components.meta b/Assets/Packages/Mirror/Components.meta new file mode 100644 index 0000000..c2771d9 --- /dev/null +++ b/Assets/Packages/Mirror/Components.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9bee879fbc8ef4b1a9a9f7088bfbf726 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Components/Mirror.Components.asmdef b/Assets/Packages/Mirror/Components/Mirror.Components.asmdef new file mode 100644 index 0000000..a61c7db --- /dev/null +++ b/Assets/Packages/Mirror/Components/Mirror.Components.asmdef @@ -0,0 +1,14 @@ +{ + "name": "Mirror.Components", + "references": [ + "Mirror" + ], + "optionalUnityReferences": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [] +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Components/Mirror.Components.asmdef.meta b/Assets/Packages/Mirror/Components/Mirror.Components.asmdef.meta new file mode 100644 index 0000000..263b6f0 --- /dev/null +++ b/Assets/Packages/Mirror/Components/Mirror.Components.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 72872094b21c16e48b631b2224833d49 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Components/NetworkAnimator.cs b/Assets/Packages/Mirror/Components/NetworkAnimator.cs new file mode 100644 index 0000000..e09c30c --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkAnimator.cs @@ -0,0 +1,427 @@ +using UnityEngine; +using UnityEngine.Serialization; + +namespace Mirror +{ + /// + /// A component to synchronize Mecanim animation states for networked objects. + /// + /// + /// 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 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 the animation parameters that are checked in the inspector view. 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. + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkAnimator")] + [RequireComponent(typeof(NetworkIdentity))] + [HelpURL("https://mirror-networking.com/xmldocs/articles/Components/NetworkAnimator.html")] + public class NetworkAnimator : NetworkBehaviour + { + /// + /// The animator component to synchronize. + /// + [FormerlySerializedAs("m_Animator")] + public Animator animator; + + // Note: not an object[] array because otherwise initialization is real annoying + int[] lastIntParameters; + float[] lastFloatParameters; + bool[] lastBoolParameters; + AnimatorControllerParameter[] parameters; + + int[] animationHash; // multiple layers + int[] transitionHash; + float sendTimer; + + bool sendMessagesAllowed + { + get + { + if (isServer) + { + if (!localPlayerAuthority) + return true; + + // This is a special case where we have localPlayerAuthority set + // on a NetworkIdentity but we have not assigned the client who has + // authority over it, no animator data will be sent over the network by the server. + // + // So we check here for a clientAuthorityOwner and if it is null we will + // let the server send animation data until we receive an owner. + if (netIdentity != null && netIdentity.clientAuthorityOwner == null) + return true; + } + + return hasAuthority; + } + } + + void Awake() + { + // 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 + parameters = animator.parameters; + lastIntParameters = new int[parameters.Length]; + lastFloatParameters = new float[parameters.Length]; + lastBoolParameters = new bool[parameters.Length]; + + animationHash = new int[animator.layerCount]; + transitionHash = new int[animator.layerCount]; + } + + void FixedUpdate() + { + if (!sendMessagesAllowed) + return; + + CheckSendRate(); + + for(int i = 0; i < animator.layerCount; i++) + { + int stateHash; + float normalizedTime; + if (!CheckAnimStateChanged(out stateHash, out normalizedTime, i)) + { + continue; + } + + NetworkWriter writer = new NetworkWriter(); + WriteParameters(writer); + + SendAnimationMessage(stateHash, normalizedTime, i, writer.ToArray()); + } + } + + bool CheckAnimStateChanged(out int stateHash, out float normalizedTime, int layerId) + { + stateHash = 0; + normalizedTime = 0; + + if (animator.IsInTransition(layerId)) + { + AnimatorTransitionInfo tt = animator.GetAnimatorTransitionInfo(layerId); + if (tt.fullPathHash != transitionHash[layerId]) + { + // first time in this transition + transitionHash[layerId] = tt.fullPathHash; + animationHash[layerId] = 0; + return true; + } + return false; + } + + AnimatorStateInfo st = animator.GetCurrentAnimatorStateInfo(layerId); + if (st.fullPathHash != animationHash[layerId]) + { + // first time in this animation state + if (animationHash[layerId] != 0) + { + // came from another animation directly - from Play() + stateHash = st.fullPathHash; + normalizedTime = st.normalizedTime; + } + transitionHash[layerId] = 0; + animationHash[layerId] = st.fullPathHash; + return true; + } + return false; + } + + void CheckSendRate() + { + if (sendMessagesAllowed && syncInterval != 0 && sendTimer < Time.time) + { + sendTimer = Time.time + syncInterval; + + NetworkWriter writer = new NetworkWriter(); + if (WriteParameters(writer)) + { + SendAnimationParametersMessage(writer.ToArray()); + } + } + } + + void SendAnimationMessage(int stateHash, float normalizedTime, int layerId, byte[] parameters) + { + if (isServer) + { + RpcOnAnimationClientMessage(stateHash, normalizedTime, layerId, parameters); + } + else if (ClientScene.readyConnection != null) + { + CmdOnAnimationServerMessage(stateHash, normalizedTime, layerId, parameters); + } + } + + void SendAnimationParametersMessage(byte[] parameters) + { + if (isServer) + { + RpcOnAnimationParametersClientMessage(parameters); + } + else if (ClientScene.readyConnection != null) + { + CmdOnAnimationParametersServerMessage(parameters); + } + } + + void HandleAnimMsg(int stateHash, float normalizedTime, int layerId, NetworkReader reader) + { + if (hasAuthority) + return; + + // usually transitions will be triggered by parameters, if not, play anims directly. + // NOTE: this plays "animations", not transitions, so any transitions will be skipped. + // NOTE: there is no API to play a transition(?) + if (stateHash != 0) + { + animator.Play(stateHash, layerId, normalizedTime); + } + + ReadParameters(reader); + } + + void HandleAnimParamsMsg(NetworkReader reader) + { + if (hasAuthority) + return; + + ReadParameters(reader); + } + + void HandleAnimTriggerMsg(int hash) + { + animator.SetTrigger(hash); + } + + ulong NextDirtyBits() + { + ulong dirtyBits = 0; + for (int i = 0; i < parameters.Length; i++) + { + AnimatorControllerParameter par = parameters[i]; + bool changed = false; + if (par.type == AnimatorControllerParameterType.Int) + { + int newIntValue = animator.GetInteger(par.nameHash); + changed = newIntValue != lastIntParameters[i]; + if (changed) + { + lastIntParameters[i] = newIntValue; + } + } + else if (par.type == AnimatorControllerParameterType.Float) + { + float newFloatValue = animator.GetFloat(par.nameHash); + changed = Mathf.Abs(newFloatValue - lastFloatParameters[i]) > 0.001f; + if (changed) + { + lastFloatParameters[i] = newFloatValue; + } + } + else if (par.type == AnimatorControllerParameterType.Bool) + { + bool newBoolValue = animator.GetBool(par.nameHash); + changed = newBoolValue != lastBoolParameters[i]; + if (changed) + { + lastBoolParameters[i] = newBoolValue; + } + } + if (changed) + { + dirtyBits |= 1ul << i; + } + } + return dirtyBits; + } + + bool WriteParameters(NetworkWriter writer) + { + ulong dirtyBits = NextDirtyBits(); + writer.WritePackedUInt64(dirtyBits); + for (int i = 0; i < parameters.Length; i++) + { + if ((dirtyBits & (1ul << i)) == 0) + continue; + + AnimatorControllerParameter par = parameters[i]; + if (par.type == AnimatorControllerParameterType.Int) + { + int newIntValue = animator.GetInteger(par.nameHash); + writer.WritePackedInt32(newIntValue); + } + else if (par.type == AnimatorControllerParameterType.Float) + { + float newFloatValue = animator.GetFloat(par.nameHash); + writer.WriteSingle(newFloatValue); + } + else if (par.type == AnimatorControllerParameterType.Bool) + { + bool newBoolValue = animator.GetBool(par.nameHash); + writer.WriteBoolean(newBoolValue); + } + } + return dirtyBits != 0; + } + + void ReadParameters(NetworkReader reader) + { + ulong dirtyBits = reader.ReadPackedUInt64(); + for (int i = 0; i < parameters.Length; i++) + { + if ((dirtyBits & (1ul << i)) == 0) + continue; + + AnimatorControllerParameter par = parameters[i]; + if (par.type == AnimatorControllerParameterType.Int) + { + int newIntValue = reader.ReadPackedInt32(); + animator.SetInteger(par.nameHash, newIntValue); + } + else if (par.type == AnimatorControllerParameterType.Float) + { + float newFloatValue = reader.ReadSingle(); + animator.SetFloat(par.nameHash, newFloatValue); + } + else if (par.type == AnimatorControllerParameterType.Bool) + { + bool newBoolValue = reader.ReadBoolean(); + animator.SetBool(par.nameHash, newBoolValue); + } + } + } + + /// + /// Custom Serialization + /// + /// + /// + /// + public override bool OnSerialize(NetworkWriter writer, bool forceAll) + { + if (forceAll) + { + for(int i = 0; i < animator.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); + } + } + WriteParameters(writer); + return true; + } + return false; + } + + /// + /// Custom Deserialization + /// + /// + /// + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + if (initialState) + { + for(int i = 0; i < animator.layerCount; i++) + { + int stateHash = reader.ReadInt32(); + float normalizedTime = reader.ReadSingle(); + animator.Play(stateHash, i, normalizedTime); + } + + ReadParameters(reader); + } + } + + /// + /// Causes an animation trigger to be invoked for a networked object. + /// If local authority is set, and this is called from the client, then the trigger will be invoked on the server and all clients. If not, then this is called on the server, and the trigger will be called on all clients. + /// + /// Name of trigger. + public void SetTrigger(string triggerName) + { + SetTrigger(Animator.StringToHash(triggerName)); + } + + /// + /// Causes an animation trigger to be invoked for a networked object. + /// + /// Hash id of trigger (from the Animator). + public void SetTrigger(int hash) + { + if (hasAuthority && localPlayerAuthority) + { + if (ClientScene.readyConnection != null) + { + CmdOnAnimationTriggerServerMessage(hash); + } + return; + } + + if (isServer && !localPlayerAuthority) + { + RpcOnAnimationTriggerClientMessage(hash); + } + } + + #region server message handlers + [Command] + void CmdOnAnimationServerMessage(int stateHash, float normalizedTime, int layerId, byte[] parameters) + { + if (LogFilter.Debug) Debug.Log("OnAnimationMessage for netId=" + netId); + + // handle and broadcast + HandleAnimMsg(stateHash, normalizedTime, layerId, new NetworkReader(parameters)); + RpcOnAnimationClientMessage(stateHash, normalizedTime, layerId, parameters); + } + + [Command] + void CmdOnAnimationParametersServerMessage(byte[] parameters) + { + // handle and broadcast + HandleAnimParamsMsg(new NetworkReader(parameters)); + RpcOnAnimationParametersClientMessage(parameters); + } + + [Command] + void CmdOnAnimationTriggerServerMessage(int hash) + { + // handle and broadcast + HandleAnimTriggerMsg(hash); + RpcOnAnimationTriggerClientMessage(hash); + } + #endregion + + #region client message handlers + [ClientRpc] + void RpcOnAnimationClientMessage(int stateHash, float normalizedTime, int layerId, byte[] parameters) + { + HandleAnimMsg(stateHash, normalizedTime, layerId, new NetworkReader(parameters)); + } + + [ClientRpc] + void RpcOnAnimationParametersClientMessage(byte[] parameters) + { + HandleAnimParamsMsg(new NetworkReader(parameters)); + } + + // server sends this to one client + [ClientRpc] + void RpcOnAnimationTriggerClientMessage(int hash) + { + HandleAnimTriggerMsg(hash); + } + #endregion + } +} diff --git a/Assets/Packages/Mirror/Components/NetworkAnimator.cs.meta b/Assets/Packages/Mirror/Components/NetworkAnimator.cs.meta new file mode 100644 index 0000000..5fb8576 --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkAnimator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f6f3bf89aa97405989c802ba270f815 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Components/NetworkLobbyManager.cs b/Assets/Packages/Mirror/Components/NetworkLobbyManager.cs new file mode 100644 index 0000000..69039ac --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkLobbyManager.cs @@ -0,0 +1,659 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.Serialization; + +namespace Mirror +{ + /// + /// This is a specialized NetworkManager that includes a networked lobby. + /// + /// + /// The lobby has slots that track the joined players, and a maximum player count that is enforced. It requires that the NetworkLobbyPlayer component be on the lobby player objects. + /// 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/xmldocs/articles/Components/NetworkLobbyManager.html")] + public class NetworkLobbyManager : NetworkManager + { + public struct PendingPlayer + { + public NetworkConnection conn; + public GameObject lobbyPlayer; + } + + [Header("Lobby Settings")] + + [FormerlySerializedAs("m_ShowLobbyGUI")] + [SerializeField] + internal bool showLobbyGUI = true; + + [FormerlySerializedAs("m_MinPlayers")] + [SerializeField] + int minPlayers = 1; + + [FormerlySerializedAs("m_LobbyPlayerPrefab")] + [SerializeField] + NetworkLobbyPlayer lobbyPlayerPrefab; + + /// + /// The scene to use for the lobby. This is similar to the offlineScene of the NetworkManager. + /// + [Scene] + public string LobbyScene; + + /// + /// The scene to use for the playing the game from the lobby. This is similar to the onlineScene of the NetworkManager. + /// + [Scene] + public string GameplayScene; + + /// + /// List of players that are in the Lobby + /// + [FormerlySerializedAs("m_PendingPlayers")] + public List pendingPlayers = new List(); + + /// + /// These slots track players that enter the lobby. + /// The slotId on players is global to the game - across all players. + /// + public List lobbySlots = new List(); + + /// + /// True when all players have submitted a Ready message + /// + public bool allPlayersReady; + + public override void OnValidate() + { + // always >= 0 + maxConnections = Mathf.Max(maxConnections, 0); + + // always <= maxConnections + minPlayers = Mathf.Min(minPlayers, maxConnections); + + // always >= 0 + minPlayers = Mathf.Max(minPlayers, 0); + + if (lobbyPlayerPrefab != null) + { + NetworkIdentity identity = lobbyPlayerPrefab.GetComponent(); + if (identity == null) + { + lobbyPlayerPrefab = null; + Debug.LogError("LobbyPlayer prefab must have a NetworkIdentity component."); + } + } + + base.OnValidate(); + } + + internal void ReadyStatusChanged() + { + int CurrentPlayers = 0; + int ReadyPlayers = 0; + + foreach (NetworkLobbyPlayer item in lobbySlots) + { + if (item != null) + { + CurrentPlayers++; + if (item.readyToBegin) + ReadyPlayers++; + } + } + + if (CurrentPlayers == ReadyPlayers) + CheckReadyToBegin(); + else + allPlayersReady = false; + } + + /// + /// + /// + /// Connection of the client + public override void OnServerReady(NetworkConnection conn) + { + if (LogFilter.Debug) Debug.Log("NetworkLobbyManager OnServerReady"); + base.OnServerReady(conn); + + if (conn != null && conn.playerController != null) + { + GameObject lobbyPlayer = conn.playerController.gameObject; + + // if null or not a lobby player, dont replace it + if (lobbyPlayer != null && lobbyPlayer.GetComponent() != null) + SceneLoadedForPlayer(conn, lobbyPlayer); + } + } + + void SceneLoadedForPlayer(NetworkConnection conn, GameObject lobbyPlayer) + { + if (LogFilter.Debug) Debug.LogFormat("NetworkLobby SceneLoadedForPlayer scene: {0} {1}", SceneManager.GetActiveScene().name, conn); + + if (SceneManager.GetActiveScene().name == LobbyScene) + { + // cant be ready in lobby, add to ready list + PendingPlayer pending; + pending.conn = conn; + pending.lobbyPlayer = lobbyPlayer; + pendingPlayers.Add(pending); + return; + } + + GameObject gamePlayer = OnLobbyServerCreateGamePlayer(conn); + if (gamePlayer == null) + { + // get start position from base class + Transform startPos = GetStartPosition(); + gamePlayer = startPos != null + ? Instantiate(playerPrefab, startPos.position, startPos.rotation) + : Instantiate(playerPrefab, Vector3.zero, Quaternion.identity); + gamePlayer.name = playerPrefab.name; + } + + if (!OnLobbyServerSceneLoadedForPlayer(lobbyPlayer, gamePlayer)) + return; + + // replace lobby player with game player + NetworkServer.ReplacePlayerForConnection(conn, gamePlayer); + } + + /// + /// CheckReadyToBegin checks all of the players in the lobby to see if their readyToBegin flag is set. + /// If all of the players are ready, then the server switches from the LobbyScene to the PlayScene - essentially starting the game. This is called automatically in response to NetworkLobbyPlayer.SendReadyToBeginMessage(). + /// + public void CheckReadyToBegin() + { + if (SceneManager.GetActiveScene().name != LobbyScene) return; + + if (minPlayers > 0 && NetworkServer.connections.Count(conn => conn.Value != null && conn.Value.playerController.gameObject.GetComponent().readyToBegin) < minPlayers) + { + allPlayersReady = false; + return; + } + + pendingPlayers.Clear(); + allPlayersReady = true; + OnLobbyServerPlayersReady(); + } + + void CallOnClientEnterLobby() + { + OnLobbyClientEnter(); + foreach (NetworkLobbyPlayer player in lobbySlots) + if (player != null) + { + player.OnClientEnterLobby(); + } + } + + void CallOnClientExitLobby() + { + OnLobbyClientExit(); + foreach (NetworkLobbyPlayer player in lobbySlots) + if (player != null) + { + player.OnClientExitLobby(); + } + } + + #region server handlers + + /// + /// + /// + /// Connection of the client + public override void OnServerConnect(NetworkConnection conn) + { + if (numPlayers >= maxConnections) + { + conn.Disconnect(); + return; + } + + // cannot join game in progress + if (SceneManager.GetActiveScene().name != LobbyScene) + { + conn.Disconnect(); + return; + } + + base.OnServerConnect(conn); + OnLobbyServerConnect(conn); + } + + /// + /// + /// + /// Connection of the client + public override void OnServerDisconnect(NetworkConnection conn) + { + if (conn.playerController != null) + { + NetworkLobbyPlayer player = conn.playerController.GetComponent(); + + if (player != null) + lobbySlots.Remove(player); + } + + allPlayersReady = false; + + foreach (NetworkLobbyPlayer player in lobbySlots) + { + if (player != null) + player.GetComponent().readyToBegin = false; + } + + if (SceneManager.GetActiveScene().name == LobbyScene) + RecalculateLobbyPlayerIndices(); + + base.OnServerDisconnect(conn); + OnLobbyServerDisconnect(conn); + } + + /// + /// + /// + /// Connection of the client + /// + public override void OnServerAddPlayer(NetworkConnection conn, AddPlayerMessage extraMessage) + { + if (SceneManager.GetActiveScene().name != LobbyScene) return; + + if (lobbySlots.Count == maxConnections) return; + + allPlayersReady = false; + + if (LogFilter.Debug) Debug.LogFormat("NetworkLobbyManager.OnServerAddPlayer playerPrefab:{0}", lobbyPlayerPrefab.name); + + GameObject newLobbyGameObject = OnLobbyServerCreateLobbyPlayer(conn); + if (newLobbyGameObject == null) + newLobbyGameObject = (GameObject)Instantiate(lobbyPlayerPrefab.gameObject, Vector3.zero, Quaternion.identity); + + NetworkLobbyPlayer newLobbyPlayer = newLobbyGameObject.GetComponent(); + + lobbySlots.Add(newLobbyPlayer); + + RecalculateLobbyPlayerIndices(); + + NetworkServer.AddPlayerForConnection(conn, newLobbyGameObject); + } + + void RecalculateLobbyPlayerIndices() + { + if (lobbySlots.Count > 0) + { + for (int i = 0; i < lobbySlots.Count; i++) + { + lobbySlots[i].index = i; + } + } + } + + /// + /// + /// + /// + public override void ServerChangeScene(string sceneName) + { + if (sceneName == LobbyScene) + { + foreach (NetworkLobbyPlayer lobbyPlayer in lobbySlots) + { + if (lobbyPlayer == null) continue; + + // find the game-player object for this connection, and destroy it + NetworkIdentity identity = lobbyPlayer.GetComponent(); + + NetworkIdentity playerController = identity.connectionToClient.playerController; + NetworkServer.Destroy(playerController.gameObject); + + if (NetworkServer.active) + { + // re-add the lobby object + lobbyPlayer.GetComponent().readyToBegin = false; + NetworkServer.ReplacePlayerForConnection(identity.connectionToClient, lobbyPlayer.gameObject); + } + } + } + else + { + if (dontDestroyOnLoad) + { + foreach (NetworkLobbyPlayer lobbyPlayer in lobbySlots) + { + if (lobbyPlayer != null) + { + lobbyPlayer.transform.SetParent(null); + DontDestroyOnLoad(lobbyPlayer); + } + } + } + } + + base.ServerChangeScene(sceneName); + } + + /// + /// + /// + /// + public override void OnServerSceneChanged(string sceneName) + { + if (sceneName != LobbyScene) + { + // call SceneLoadedForPlayer on any players that become ready while we were loading the scene. + foreach (PendingPlayer pending in pendingPlayers) + SceneLoadedForPlayer(pending.conn, pending.lobbyPlayer); + + pendingPlayers.Clear(); + } + + OnLobbyServerSceneChanged(sceneName); + } + + /// + /// + /// + public override void OnStartServer() + { + if (string.IsNullOrEmpty(LobbyScene)) + { + Debug.LogError("NetworkLobbyManager LobbyScene is empty. Set the LobbyScene in the inspector for the NetworkLobbyMangaer"); + return; + } + + if (string.IsNullOrEmpty(GameplayScene)) + { + Debug.LogError("NetworkLobbyManager PlayScene is empty. Set the PlayScene in the inspector for the NetworkLobbyMangaer"); + return; + } + + OnLobbyStartServer(); + } + + /// + /// + /// + public override void OnStartHost() + { + OnLobbyStartHost(); + } + + /// + /// + /// + public override void OnStopServer() + { + lobbySlots.Clear(); + base.OnStopServer(); + } + + /// + /// + /// + public override void OnStopHost() + { + OnLobbyStopHost(); + } + + #endregion + + #region client handlers + + /// + /// + /// + public override void OnStartClient() + { + if (lobbyPlayerPrefab == null || lobbyPlayerPrefab.gameObject == null) + Debug.LogError("NetworkLobbyManager no LobbyPlayer prefab is registered. Please add a LobbyPlayer prefab."); + else + ClientScene.RegisterPrefab(lobbyPlayerPrefab.gameObject); + + if (playerPrefab == null) + Debug.LogError("NetworkLobbyManager no GamePlayer prefab is registered. Please add a GamePlayer prefab."); + else + ClientScene.RegisterPrefab(playerPrefab); + + OnLobbyStartClient(); + } + + /// + /// + /// + /// Connection of the client + public override void OnClientConnect(NetworkConnection conn) + { + OnLobbyClientConnect(conn); + CallOnClientEnterLobby(); + base.OnClientConnect(conn); + } + + /// + /// + /// + /// Connection of the client + public override void OnClientDisconnect(NetworkConnection conn) + { + OnLobbyClientDisconnect(conn); + base.OnClientDisconnect(conn); + } + + /// + /// + /// + public override void OnStopClient() + { + OnLobbyStopClient(); + CallOnClientExitLobby(); + + if (!string.IsNullOrEmpty(offlineScene)) + { + // Move the LobbyManager from the virtual DontDestroyOnLoad scene to the Game scene. + // This let's it be destroyed when client changes to the Offline scene. + SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene()); + } + } + + /// + /// + /// + /// + public override void OnClientChangeScene(string newSceneName) + { + if (LogFilter.Debug) Debug.LogFormat("OnClientChangeScene from {0} to {1}", SceneManager.GetActiveScene().name, newSceneName); + + if (SceneManager.GetActiveScene().name == LobbyScene && newSceneName == GameplayScene && dontDestroyOnLoad && NetworkClient.isConnected) + { + if (NetworkClient.connection != null && NetworkClient.connection.playerController != null) + { + GameObject lobbyPlayer = NetworkClient.connection.playerController.gameObject; + if (lobbyPlayer != null) + { + lobbyPlayer.transform.SetParent(null); + DontDestroyOnLoad(lobbyPlayer); + } + else + Debug.LogWarningFormat("OnClientChangeScene: lobbyPlayer is null"); + } + } + else + if (LogFilter.Debug) Debug.LogFormat("OnClientChangeScene {0} {1}", dontDestroyOnLoad, NetworkClient.isConnected); + } + + /// + /// + /// + /// Connection of the client + public override void OnClientSceneChanged(NetworkConnection conn) + { + if (SceneManager.GetActiveScene().name == LobbyScene) + { + if (NetworkClient.isConnected) + CallOnClientEnterLobby(); + } + else + CallOnClientExitLobby(); + + base.OnClientSceneChanged(conn); + OnLobbyClientSceneChanged(conn); + } + + #endregion + + #region lobby server virtuals + + /// + /// This is called on the host when a host is started. + /// + public virtual void OnLobbyStartHost() { } + + /// + /// This is called on the host when the host is stopped. + /// + public virtual void OnLobbyStopHost() { } + + /// + /// This is called on the server when the server is started - including when a host is started. + /// + public virtual void OnLobbyStartServer() { } + + /// + /// This is called on the server when a new client connects to the server. + /// + /// The new connection. + public virtual void OnLobbyServerConnect(NetworkConnection conn) { } + + /// + /// This is called on the server when a client disconnects. + /// + /// The connection that disconnected. + public virtual void OnLobbyServerDisconnect(NetworkConnection conn) { } + + /// + /// This is called on the server when a networked scene finishes loading. + /// + /// Name of the new scene. + public virtual void OnLobbyServerSceneChanged(string sceneName) { } + + /// + /// This allows customization of the creation of the lobby-player object on the server. + /// By default the lobbyPlayerPrefab is used to create the lobby-player, but this function allows that behaviour to be customized. + /// + /// The connection the player object is for. + /// The new lobby-player object. + public virtual GameObject OnLobbyServerCreateLobbyPlayer(NetworkConnection conn) + { + return null; + } + + /// + /// This allows customization of the creation of the GamePlayer object on the server. + /// By default the gamePlayerPrefab is used to create the game-player, but this function allows that behaviour to be customized. The object returned from the function will be used to replace the lobby-player on the connection. + /// + /// The connection the player object is for. + /// A new GamePlayer object. + public virtual GameObject OnLobbyServerCreateGamePlayer(NetworkConnection conn) + { + return null; + } + + // for users to apply settings from their lobby 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 lobby scene to a game player scene. + /// When switching from the lobby, the lobby-player is replaced with a game-player object. This callback function gives an opportunity to apply state from the lobby-player to the game-player object. + /// + /// The lobby player object. + /// The game player object. + /// False to not allow this player to replace the lobby player. + public virtual bool OnLobbyServerSceneLoadedForPlayer(GameObject lobbyPlayer, GameObject gamePlayer) + { + return true; + } + + /// + /// This is called on the server when all the players in the lobby 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 lobby are ready, such as adding a countdown or a confirmation for a group leader. + /// + public virtual void OnLobbyServerPlayersReady() + { + // all players are readyToBegin, start the game + ServerChangeScene(GameplayScene); + } + + #endregion + + #region lobby client virtuals + + /// + /// This is a hook to allow custom behaviour when the game client enters the lobby. + /// + public virtual void OnLobbyClientEnter() { } + + /// + /// This is a hook to allow custom behaviour when the game client exits the lobby. + /// + public virtual void OnLobbyClientExit() { } + + /// + /// This is called on the client when it connects to server. + /// + /// The connection that connected. + public virtual void OnLobbyClientConnect(NetworkConnection conn) { } + + /// + /// This is called on the client when disconnected from a server. + /// + /// The connection that disconnected. + public virtual void OnLobbyClientDisconnect(NetworkConnection conn) { } + + /// + /// This is called on the client when a client is started. + /// + /// The connection for the lobby. + public virtual void OnLobbyStartClient() { } + + /// + /// This is called on the client when the client stops. + /// + public virtual void OnLobbyStopClient() { } + + /// + /// 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 OnLobbyClientSceneChanged(NetworkConnection conn) { } + + /// + /// Called on the client when adding a player to the lobby fails. + /// This could be because the lobby is full, or the connection is not allowed to have more players. + /// + public virtual void OnLobbyClientAddPlayerFailed() { } + + #endregion + + #region optional UI + + /// + /// virtual so inheriting classes can roll their own + /// + public virtual void OnGUI() + { + if (!showLobbyGUI) + return; + + if (SceneManager.GetActiveScene().name != LobbyScene) + return; + + GUI.Box(new Rect(10f, 180f, 520f, 150f), "PLAYERS"); + } + + #endregion + } +} diff --git a/Assets/Packages/Mirror/Components/NetworkLobbyManager.cs.meta b/Assets/Packages/Mirror/Components/NetworkLobbyManager.cs.meta new file mode 100644 index 0000000..35b6436 --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkLobbyManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 615e6c6589cf9e54cad646b5a11e0529 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Components/NetworkLobbyPlayer.cs b/Assets/Packages/Mirror/Components/NetworkLobbyPlayer.cs new file mode 100644 index 0000000..45231c1 --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkLobbyPlayer.cs @@ -0,0 +1,155 @@ +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace Mirror +{ + /// + /// This component works in conjunction with the NetworkLobbyManager to make up the multiplayer lobby system. + /// 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/xmldocs/articles/Components/NetworkLobbyPlayer.html")] + public class NetworkLobbyPlayer : NetworkBehaviour + { + /// + /// This flag controls whether the default UI is shown for the lobby player. + /// As this UI is rendered using the old GUI system, it is only recommended for testing purposes. + /// + public bool showLobbyGUI = true; + + /// + /// This is a flag that control whether this player is ready for the game to begin. + /// When all players are ready to begin, the game will start. This should not be set directly, the SendReadyToBeginMessage function should be called on the client to set it on the server. + /// + [SyncVar(hook = nameof(ReadyStateChanged))] + public bool readyToBegin; + + /// + /// Current index of the player, e.g. Player1, Player2, etc. + /// + [SyncVar] + public int index; + + #region Unity Callbacks + + /// + /// Do not use Start - Override OnStartrHost / OnStartClient instead! + /// + public void Start() + { + if (NetworkManager.singleton as NetworkLobbyManager) + OnClientEnterLobby(); + else + Debug.LogError("LobbyPlayer could not find a NetworkLobbyManager. The LobbyPlayer requires a NetworkLobbyManager object to function. Make sure that there is one in the scene."); + } + + #endregion + + #region Commands + + [Command] + public void CmdChangeReadyState(bool readyState) + { + readyToBegin = readyState; + NetworkLobbyManager lobby = NetworkManager.singleton as NetworkLobbyManager; + if (lobby != null) + { + lobby.ReadyStatusChanged(); + } + } + + #endregion + + #region SyncVar Hooks + + void ReadyStateChanged(bool newReadyState) + { + OnClientReady(readyToBegin); + } + + #endregion + + #region Lobby Client Virtuals + + /// + /// This is a hook that is invoked on all player objects when entering the lobby. + /// Note: isLocalPlayer is not guaranteed to be set until OnStartLocalPlayer is called. + /// + public virtual void OnClientEnterLobby() { } + + /// + /// This is a hook that is invoked on all player objects when exiting the lobby. + /// + public virtual void OnClientExitLobby() { } + + /// + /// This is a hook that is invoked on clients when a LobbyPlayer switches between ready or not ready. + /// This function is called when the a client player calls SendReadyToBeginMessage() or SendNotReadyToBeginMessage(). + /// + /// Whether the player is ready or not. + public virtual void OnClientReady(bool readyState) { } + + #endregion + + #region Optional UI + + /// + /// Render a UI for the lobby. Override to provide your on UI + /// + public virtual void OnGUI() + { + if (!showLobbyGUI) + return; + + NetworkLobbyManager lobby = NetworkManager.singleton as NetworkLobbyManager; + if (lobby) + { + if (!lobby.showLobbyGUI) + return; + + if (SceneManager.GetActiveScene().name != lobby.LobbyScene) + return; + + GUILayout.BeginArea(new Rect(20f + (index * 100), 200f, 90f, 130f)); + + GUILayout.Label($"Player [{index + 1}]"); + + if (readyToBegin) + GUILayout.Label("Ready"); + else + GUILayout.Label("Not Ready"); + + if (((isServer && index > 0) || isServerOnly) && GUILayout.Button("REMOVE")) + { + // This button only shows on the Host for all players other than the Host + // Host and Players can't remove themselves (stop the client instead) + // Host can kick a Player this way. + GetComponent().connectionToClient.Disconnect(); + } + + GUILayout.EndArea(); + + if (NetworkClient.active && isLocalPlayer) + { + GUILayout.BeginArea(new Rect(20f, 300f, 120f, 20f)); + + if (readyToBegin) + { + if (GUILayout.Button("Cancel")) + CmdChangeReadyState(false); + } + else + { + if (GUILayout.Button("Ready")) + CmdChangeReadyState(true); + } + + GUILayout.EndArea(); + } + } + } + + #endregion + } +} diff --git a/Assets/Packages/Mirror/Components/NetworkLobbyPlayer.cs.meta b/Assets/Packages/Mirror/Components/NetworkLobbyPlayer.cs.meta new file mode 100644 index 0000000..3062e0e --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkLobbyPlayer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79874ac94d5b1314788ecf0e86bd23fd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Components/NetworkProximityChecker.cs b/Assets/Packages/Mirror/Components/NetworkProximityChecker.cs new file mode 100644 index 0000000..97c4bbf --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkProximityChecker.cs @@ -0,0 +1,171 @@ +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/xmldocs/articles/Components/NetworkProximityChecker.html")] + public class NetworkProximityChecker : NetworkBehaviour + { + /// + /// Enumeration of methods to use to check proximity. + /// + public enum CheckMethod + { + Physics3D, + Physics2D + } + + /// + /// 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; + + /// + /// Which method to use for checking proximity of players. + /// Physics3D uses 3D physics to determine proximity. + /// Physics2D uses 2D physics to determine proximity. + /// + [Tooltip("Which method to use for checking proximity of players.\n\nPhysics3D uses 3D physics to determine proximity.\nPhysics2D uses 2D physics to determine proximity.")] + public CheckMethod checkMethod = CheckMethod.Physics3D; + + /// + /// 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; + + // Layers are used anyway, might as well expose them to the user. + /// + /// Select only the Player's layer to avoid unnecessary SphereCasts against the Terrain, etc. + /// ~0 means 'Everything'. + /// + [Tooltip("Select only the Player's layer to avoid unnecessary SphereCasts against the Terrain, etc.")] + public LayerMask castLayers = ~0; + + float lastUpdateTime; + + // OverlapSphereNonAlloc array to avoid allocations. + // -> static so we don't create one per component + // -> this is worth it because proximity checking happens for just about + // every entity on the server! + // -> should be big enough to work in just about all cases + static Collider[] hitsBuffer3D = new Collider[10000]; + static Collider2D[] hitsBuffer2D = new Collider2D[10000]; + + void Update() + { + if (!NetworkServer.active) + return; + + if (Time.time - lastUpdateTime > visUpdateInterval) + { + netIdentity.RebuildObservers(false); + lastUpdateTime = Time.time; + } + } + + /// + /// Called when a new player enters + /// + /// + /// + public override bool OnCheckObserver(NetworkConnection newObserver) + { + if (forceHidden) + return false; + + return Vector3.Distance(newObserver.playerController.transform.position, transform.position) < visRange; + } + + /// + /// Called when a new player enters, and when scene changes occur + /// + /// List of players to be updated. Modify this set with all the players that can see this object + /// True if this is the first time the method is called for this object + /// True if this component calculated the list of observers + public override bool OnRebuildObservers(HashSet observers, bool initial) + { + // if force hidden then return without adding any observers. + if (forceHidden) + // always return true when overwriting OnRebuildObservers so that + // Mirror knows not to use the built in rebuild method. + return true; + + // find players within range + switch (checkMethod) + { + case CheckMethod.Physics3D: + { + // cast without allocating GC for maximum performance + int hitCount = Physics.OverlapSphereNonAlloc(transform.position, visRange, hitsBuffer3D, castLayers); + if (hitCount == hitsBuffer3D.Length) Debug.LogWarning("NetworkProximityChecker's OverlapSphere test for " + name + " has filled the whole buffer(" + hitsBuffer3D.Length + "). Some results might have been omitted. Consider increasing buffer size."); + + for (int i = 0; i < hitCount; i++) + { + Collider hit = hitsBuffer3D[i]; + // collider might be on pelvis, often the NetworkIdentity is in a parent + // (looks in the object itself and then parents) + NetworkIdentity identity = hit.GetComponentInParent(); + // (if an object has a connectionToClient, it is a player) + if (identity != null && identity.connectionToClient != null) + { + observers.Add(identity.connectionToClient); + } + } + break; + } + + case CheckMethod.Physics2D: + { + // cast without allocating GC for maximum performance + int hitCount = Physics2D.OverlapCircleNonAlloc(transform.position, visRange, hitsBuffer2D, castLayers); + if (hitCount == hitsBuffer2D.Length) Debug.LogWarning("NetworkProximityChecker's OverlapCircle test for " + name + " has filled the whole buffer(" + hitsBuffer2D.Length + "). Some results might have been omitted. Consider increasing buffer size."); + + for (int i = 0; i < hitCount; i++) + { + Collider2D hit = hitsBuffer2D[i]; + // collider might be on pelvis, often the NetworkIdentity is in a parent + // (looks in the object itself and then parents) + NetworkIdentity identity = hit.GetComponentInParent(); + // (if an object has a connectionToClient, it is a player) + if (identity != null && identity.connectionToClient != null) + { + observers.Add(identity.connectionToClient); + } + } + break; + } + } + + // always return true when overwriting OnRebuildObservers so that + // Mirror knows not to use the built in rebuild method. + return true; + } + + /// + /// Called when hiding and showing objects on the host + /// + /// + public override void OnSetLocalVisibility(bool visible) + { + foreach (Renderer rend in GetComponentsInChildren()) + { + rend.enabled = visible; + } + } + } +} diff --git a/Assets/Packages/Mirror/Components/NetworkProximityChecker.cs.meta b/Assets/Packages/Mirror/Components/NetworkProximityChecker.cs.meta new file mode 100644 index 0000000..79e50e8 --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkProximityChecker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1731d8de2d0c84333b08ebe1e79f4118 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Components/NetworkTransform.cs b/Assets/Packages/Mirror/Components/NetworkTransform.cs new file mode 100644 index 0000000..d55e26d --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkTransform.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkTransform")] + [HelpURL("https://mirror-networking.com/xmldocs/articles/Components/NetworkTransform.html")] + public class NetworkTransform : NetworkTransformBase + { + protected override Transform targetComponent => transform; + } +} diff --git a/Assets/Packages/Mirror/Components/NetworkTransform.cs.meta b/Assets/Packages/Mirror/Components/NetworkTransform.cs.meta new file mode 100644 index 0000000..d1af9ec --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkTransform.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2f74aedd71d9a4f55b3ce499326d45fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Components/NetworkTransformBase.cs b/Assets/Packages/Mirror/Components/NetworkTransformBase.cs new file mode 100644 index 0000000..4ed5ad9 --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkTransformBase.cs @@ -0,0 +1,447 @@ +// 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 UnityEngine; + +namespace Mirror +{ + public abstract class NetworkTransformBase : NetworkBehaviour + { + // rotation compression. not public so that other scripts can't modify + // it at runtime. alternatively we could send 1 extra byte for the mode + // each time so clients know how to decompress, but the whole point was + // to save bandwidth in the first place. + // -> can still be modified in the Inspector while the game is running, + // but would cause errors immediately and be pretty obvious. + [Tooltip("Compresses 16 Byte Quaternion into None=12, Much=3, Lots=2 Byte")] + [SerializeField] Compression compressRotation = Compression.Much; + public enum Compression { None, Much, Lots, NoRotation }; // easily understandable and funny + + // server + Vector3 lastPosition; + Quaternion lastRotation; + private 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; + + // target transform to sync. can be on a child. + protected abstract Transform targetComponent { get; } + + // serialization is needed by OnSerialize and by manual sending from authority + static void SerializeIntoWriter(NetworkWriter writer, Vector3 position, Quaternion rotation, Compression compressRotation, Vector3 scale) + { + // serialize position + writer.WriteVector3(position); + + // serialize rotation + // writing quaternion = 16 byte + // writing euler angles = 12 byte + // -> quaternion->euler->quaternion always works. + // -> gimbal lock only occurs when adding. + Vector3 euler = rotation.eulerAngles; + if (compressRotation == Compression.None) + { + // write 3 floats = 12 byte + writer.WriteSingle(euler.x); + writer.WriteSingle(euler.y); + writer.WriteSingle(euler.z); + } + else if (compressRotation == Compression.Much) + { + // write 3 byte. scaling [0,360] to [0,255] + writer.WriteByte(FloatBytePacker.ScaleFloatToByte(euler.x, 0, 360, byte.MinValue, byte.MaxValue)); + writer.WriteByte(FloatBytePacker.ScaleFloatToByte(euler.y, 0, 360, byte.MinValue, byte.MaxValue)); + writer.WriteByte(FloatBytePacker.ScaleFloatToByte(euler.z, 0, 360, byte.MinValue, byte.MaxValue)); + } + else if (compressRotation == Compression.Lots) + { + // write 2 byte, 5 bits for each float + writer.WriteUInt16(FloatBytePacker.PackThreeFloatsIntoUShort(euler.x, euler.y, euler.z, 0, 360)); + } + + // serialize scale + 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, compressRotation, 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; + return elapsed > 0 ? delta.magnitude / elapsed : 0; // avoid NaN + } + + // 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 + if (compressRotation == Compression.None) + { + // read 3 floats = 16 byte + float x = reader.ReadSingle(); + float y = reader.ReadSingle(); + float z = reader.ReadSingle(); + temp.localRotation = Quaternion.Euler(x, y, z); + } + else if (compressRotation == Compression.Much) + { + // read 3 byte. scaling [0,255] to [0,360] + float x = FloatBytePacker.ScaleByteToFloat(reader.ReadByte(), byte.MinValue, byte.MaxValue, 0, 360); + float y = FloatBytePacker.ScaleByteToFloat(reader.ReadByte(), byte.MinValue, byte.MaxValue, 0, 360); + float z = FloatBytePacker.ScaleByteToFloat(reader.ReadByte(), byte.MinValue, byte.MaxValue, 0, 360); + temp.localRotation = Quaternion.Euler(x, y, z); + } + else if (compressRotation == Compression.Lots) + { + // read 2 byte, 5 bits per float + Vector3 xyz = FloatBytePacker.UnpackUShortIntoThreeFloats(reader.ReadUInt16(), 0, 360); + temp.localRotation = Quaternion.Euler(xyz.x, xyz.y, xyz.z); + } + + 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) + { + // deserialize payload + NetworkReader reader = new NetworkReader(payload); + DeserializeFromReader(reader); + + // 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; + return difference > 0 ? elapsed / difference : 0; // avoid NaN + } + 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 = lastPosition != targetComponent.transform.localPosition; + bool rotated = lastRotation != targetComponent.transform.localRotation; + bool scaled = lastScale != targetComponent.transform.localScale; + + // 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; + if (Compression.NoRotation != compressRotation) + { + 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 && hasAuthority) + { + // check only each 'syncInterval' + if (Time.time - lastClientSendTime >= syncInterval) + { + if (HasEitherMovedRotatedScaled()) + { + // serialize + // local position/rotation for VR support + NetworkWriter writer = new NetworkWriter(); + SerializeIntoWriter(writer, targetComponent.transform.localPosition, targetComponent.transform.localRotation, compressRotation, 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 (!hasAuthority) + { + // 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); + } + 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 + Gizmos.color = Color.blue; // like unity move tool + Gizmos.DrawRay(data.localPosition + offset, data.localRotation * Vector3.forward); + + Gizmos.color = Color.green; // like unity move tool + 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/Packages/Mirror/Components/NetworkTransformBase.cs.meta b/Assets/Packages/Mirror/Components/NetworkTransformBase.cs.meta new file mode 100644 index 0000000..2c3c3e1 --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkTransformBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2e77294d8ccbc4e7cb8ca2bd0d3e99ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Components/NetworkTransformChild.cs b/Assets/Packages/Mirror/Components/NetworkTransformChild.cs new file mode 100644 index 0000000..03a364f --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkTransformChild.cs @@ -0,0 +1,16 @@ +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/xmldocs/articles/Components/NetworkTransformChild.html")] + public class NetworkTransformChild : NetworkTransformBase + { + public Transform target; + protected override Transform targetComponent => target; + } +} diff --git a/Assets/Packages/Mirror/Components/NetworkTransformChild.cs.meta b/Assets/Packages/Mirror/Components/NetworkTransformChild.cs.meta new file mode 100644 index 0000000..9c068f2 --- /dev/null +++ b/Assets/Packages/Mirror/Components/NetworkTransformChild.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 734b48bea0b204338958ee3d885e11f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor.meta b/Assets/Packages/Mirror/Editor.meta new file mode 100644 index 0000000..f679511 --- /dev/null +++ b/Assets/Packages/Mirror/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2539267b6934a4026a505690a1e1eda2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Mirror.Editor.asmdef b/Assets/Packages/Mirror/Editor/Mirror.Editor.asmdef new file mode 100644 index 0000000..d18558b --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Mirror.Editor.asmdef @@ -0,0 +1,16 @@ +{ + "name": "Mirror.Editor", + "references": [ + "Mirror" + ], + "optionalUnityReferences": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [] +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Editor/Mirror.Editor.asmdef.meta b/Assets/Packages/Mirror/Editor/Mirror.Editor.asmdef.meta new file mode 100644 index 0000000..e2e6f2a --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Mirror.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1c7c33eb5480dd24c9e29a8250c1a775 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/NetworkAnimatorEditor.cs b/Assets/Packages/Mirror/Editor/NetworkAnimatorEditor.cs new file mode 100644 index 0000000..20db50b --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkAnimatorEditor.cs @@ -0,0 +1,5 @@ +// 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/Packages/Mirror/Editor/NetworkAnimatorEditor.cs.meta b/Assets/Packages/Mirror/Editor/NetworkAnimatorEditor.cs.meta new file mode 100644 index 0000000..1b537bc --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkAnimatorEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9589e903d4e98490fb1157762a307fd7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/NetworkBehaviourInspector.cs b/Assets/Packages/Mirror/Editor/NetworkBehaviourInspector.cs new file mode 100644 index 0000000..44d55f5 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkBehaviourInspector.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + [CustomEditor(typeof(NetworkBehaviour), true)] + [CanEditMultipleObjects] + public class NetworkBehaviourInspector : Editor + { + bool initialized; + protected List syncVarNames = new List(); + bool syncsAnything; + bool[] showSyncLists; + + readonly GUIContent syncVarIndicatorContent = new GUIContent("SyncVar", "This variable has been marked with the [SyncVar] attribute."); + + internal virtual bool HideScriptField => false; + + // does this type sync anything? otherwise we don't need to show syncInterval + bool SyncsAnything(Type scriptClass) + { + // has OnSerialize that is not in NetworkBehaviour? + // then it either has a syncvar or custom OnSerialize. either way + // this means we have something to sync. + MethodInfo method = scriptClass.GetMethod("OnSerialize"); + if (method != null && method.DeclaringType != typeof(NetworkBehaviour)) + { + return true; + } + + // SyncObjects are serialized in NetworkBehaviour.OnSerialize, which + // is always there even if we don't use SyncObjects. so we need to + // search for SyncObjects manually. + // (look for 'Mirror.Sync'. not '.SyncObject' because we'd have to + // check base type for that again) + foreach (FieldInfo field in scriptClass.GetFields()) + { + if (field.FieldType.BaseType != null && + field.FieldType.BaseType.FullName != null && + field.FieldType.BaseType.FullName.Contains("Mirror.Sync")) + { + return true; + } + } + + return false; + } + + void Init(MonoScript script) + { + initialized = true; + Type scriptClass = script.GetClass(); + + // find public SyncVars to show (user doesn't want protected ones to be shown in inspector) + foreach (FieldInfo field in scriptClass.GetFields(BindingFlags.Public | BindingFlags.Instance)) + { + Attribute[] fieldMarkers = (Attribute[])field.GetCustomAttributes(typeof(SyncVarAttribute), true); + if (fieldMarkers.Length > 0) + { + syncVarNames.Add(field.Name); + } + } + + int numSyncLists = scriptClass.GetFields().Count( + field => field.FieldType.BaseType != null && + field.FieldType.BaseType.Name.Contains("SyncList")); + if (numSyncLists > 0) + { + showSyncLists = new bool[numSyncLists]; + } + + syncsAnything = SyncsAnything(scriptClass); + } + + public override void OnInspectorGUI() + { + if (!initialized) + { + serializedObject.Update(); + SerializedProperty scriptProperty = serializedObject.FindProperty("m_Script"); + if (scriptProperty == null) + return; + + MonoScript targetScript = scriptProperty.objectReferenceValue as MonoScript; + Init(targetScript); + } + + EditorGUI.BeginChangeCheck(); + serializedObject.Update(); + + // Loop through properties and create one field (including children) for each top level property. + SerializedProperty property = serializedObject.GetIterator(); + bool expanded = true; + while (property.NextVisible(expanded)) + { + bool isSyncVar = syncVarNames.Contains(property.name); + if (property.propertyType == SerializedPropertyType.ObjectReference) + { + if (property.name == "m_Script") + { + if (HideScriptField) + { + continue; + } + + EditorGUI.BeginDisabledGroup(true); + } + + EditorGUILayout.PropertyField(property, true); + + if (isSyncVar) + { + GUILayout.Label(syncVarIndicatorContent, EditorStyles.miniLabel, GUILayout.Width(EditorStyles.miniLabel.CalcSize(syncVarIndicatorContent).x)); + } + + if (property.name == "m_Script") + { + EditorGUI.EndDisabledGroup(); + } + } + else + { + EditorGUILayout.BeginHorizontal(); + + EditorGUILayout.PropertyField(property, true); + + if (isSyncVar) + { + GUILayout.Label(syncVarIndicatorContent, EditorStyles.miniLabel, GUILayout.Width(EditorStyles.miniLabel.CalcSize(syncVarIndicatorContent).x)); + } + + EditorGUILayout.EndHorizontal(); + } + expanded = false; + } + serializedObject.ApplyModifiedProperties(); + EditorGUI.EndChangeCheck(); + + // find SyncLists.. they are not properties. + int syncListIndex = 0; + foreach (FieldInfo field in serializedObject.targetObject.GetType().GetFields()) + { + if (field.FieldType.BaseType != null && field.FieldType.BaseType.Name.Contains("SyncList")) + { + showSyncLists[syncListIndex] = EditorGUILayout.Foldout(showSyncLists[syncListIndex], "SyncList " + field.Name + " [" + field.FieldType.Name + "]"); + if (showSyncLists[syncListIndex]) + { + EditorGUI.indentLevel += 1; + if (field.GetValue(serializedObject.targetObject) is IEnumerable synclist) + { + int index = 0; + IEnumerator enu = synclist.GetEnumerator(); + while (enu.MoveNext()) + { + if (enu.Current != null) + { + EditorGUILayout.LabelField("Item:" + index, enu.Current.ToString()); + } + index += 1; + } + } + EditorGUI.indentLevel -= 1; + } + syncListIndex += 1; + } + } + + // does it sync anything? then show extra properties + // (no need to show it if the class only has Cmds/Rpcs and no sync) + if (syncsAnything) + { + NetworkBehaviour networkBehaviour = target as NetworkBehaviour; + if (networkBehaviour != null) + { + // syncMode + serializedObject.FindProperty("syncMode").enumValueIndex = (int)(SyncMode) + EditorGUILayout.EnumPopup("Network Sync Mode", networkBehaviour.syncMode); + + // syncInterval + // [0,2] should be enough. anything >2s is too laggy anyway. + serializedObject.FindProperty("syncInterval").floatValue = EditorGUILayout.Slider( + new GUIContent("Network Sync Interval", + "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.)"), + networkBehaviour.syncInterval, 0, 2); + + // apply + serializedObject.ApplyModifiedProperties(); + } + } + } + } +} //namespace diff --git a/Assets/Packages/Mirror/Editor/NetworkBehaviourInspector.cs.meta b/Assets/Packages/Mirror/Editor/NetworkBehaviourInspector.cs.meta new file mode 100644 index 0000000..78d9fa8 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkBehaviourInspector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f02853db46b6346e4866594a96c3b0e7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/NetworkIdentityEditor.cs b/Assets/Packages/Mirror/Editor/NetworkIdentityEditor.cs new file mode 100644 index 0000000..3a79340 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkIdentityEditor.cs @@ -0,0 +1,106 @@ +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + [CustomEditor(typeof(NetworkIdentity), true)] + [CanEditMultipleObjects] + public class NetworkIdentityEditor : Editor + { + SerializedProperty serverOnlyProperty; + SerializedProperty localPlayerAuthorityProperty; + + readonly GUIContent serverOnlyLabel = new GUIContent("Server Only", "True if the object should only exist on the server."); + readonly GUIContent localPlayerAuthorityLabel = new GUIContent("Local Player Authority", "True if this object will be controlled by a player on a client."); + readonly GUIContent spawnLabel = new GUIContent("Spawn Object", "This causes an unspawned server object to be spawned on clients"); + + NetworkIdentity networkIdentity; + bool initialized; + bool showObservers; + + void Init() + { + if (initialized) + { + return; + } + initialized = true; + networkIdentity = target as NetworkIdentity; + + serverOnlyProperty = serializedObject.FindProperty("serverOnly"); + localPlayerAuthorityProperty = serializedObject.FindProperty("localPlayerAuthority"); + } + + public override void OnInspectorGUI() + { + if (serverOnlyProperty == null) + { + initialized = false; + } + + Init(); + + serializedObject.Update(); + + if (serverOnlyProperty.boolValue) + { + EditorGUILayout.PropertyField(serverOnlyProperty, serverOnlyLabel); + EditorGUILayout.LabelField("Local Player Authority cannot be set for server-only objects"); + } + else if (localPlayerAuthorityProperty.boolValue) + { + EditorGUILayout.LabelField("Server Only cannot be set for Local Player Authority objects"); + EditorGUILayout.PropertyField(localPlayerAuthorityProperty, localPlayerAuthorityLabel); + } + else + { + EditorGUILayout.PropertyField(serverOnlyProperty, serverOnlyLabel); + EditorGUILayout.PropertyField(localPlayerAuthorityProperty, localPlayerAuthorityLabel); + } + + serializedObject.ApplyModifiedProperties(); + + if (!Application.isPlaying) + { + return; + } + + // Runtime actions below here + + EditorGUILayout.Separator(); + + if (networkIdentity.observers != null && networkIdentity.observers.Count > 0) + { + showObservers = EditorGUILayout.Foldout(showObservers, "Observers"); + if (showObservers) + { + EditorGUI.indentLevel += 1; + foreach (KeyValuePair kvp in networkIdentity.observers) + { + if (kvp.Value.playerController != null) + EditorGUILayout.ObjectField("Connection " + kvp.Value.connectionId, kvp.Value.playerController.gameObject, typeof(GameObject), false); + else + EditorGUILayout.TextField("Connection " + kvp.Value.connectionId); + } + EditorGUI.indentLevel -= 1; + } + } + + if (PrefabUtility.IsPartOfPrefabAsset(networkIdentity.gameObject)) + return; + + if (networkIdentity.gameObject.activeSelf && networkIdentity.netId == 0 && NetworkServer.active) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(spawnLabel); + if (GUILayout.Toggle(false, "Spawn", EditorStyles.miniButtonLeft)) + { + NetworkServer.Spawn(networkIdentity.gameObject); + EditorUtility.SetDirty(target); // preview window STILL doens't update immediately.. + } + EditorGUILayout.EndHorizontal(); + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/NetworkIdentityEditor.cs.meta b/Assets/Packages/Mirror/Editor/NetworkIdentityEditor.cs.meta new file mode 100644 index 0000000..cb4a5cf --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkIdentityEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b6e3680cc14b4769bff378e5dbc3544 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/NetworkInformationPreview.cs b/Assets/Packages/Mirror/Editor/NetworkInformationPreview.cs new file mode 100644 index 0000000..9699f6d --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkInformationPreview.cs @@ -0,0 +1,280 @@ +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +using UnityObject = UnityEngine.Object; + +namespace Mirror +{ + [CustomPreview(typeof(GameObject))] + class NetworkInformationPreview : ObjectPreview + { + class NetworkIdentityInfo + { + public GUIContent name; + public GUIContent value; + } + + class NetworkBehaviourInfo + { + // This is here just so we can check if it's enabled/disabled + public NetworkBehaviour behaviour; + public GUIContent name; + } + + class Styles + { + public GUIStyle labelStyle = new GUIStyle(EditorStyles.label); + public GUIStyle componentName = new GUIStyle(EditorStyles.boldLabel); + public GUIStyle disabledName = new GUIStyle(EditorStyles.miniLabel); + + public Styles() + { + Color fontColor = new Color(0.7f, 0.7f, 0.7f); + labelStyle.padding.right += 20; + labelStyle.normal.textColor = fontColor; + labelStyle.active.textColor = fontColor; + labelStyle.focused.textColor = fontColor; + labelStyle.hover.textColor = fontColor; + labelStyle.onNormal.textColor = fontColor; + labelStyle.onActive.textColor = fontColor; + labelStyle.onFocused.textColor = fontColor; + labelStyle.onHover.textColor = fontColor; + + componentName.normal.textColor = fontColor; + componentName.active.textColor = fontColor; + componentName.focused.textColor = fontColor; + componentName.hover.textColor = fontColor; + componentName.onNormal.textColor = fontColor; + componentName.onActive.textColor = fontColor; + componentName.onFocused.textColor = fontColor; + componentName.onHover.textColor = fontColor; + + disabledName.normal.textColor = fontColor; + disabledName.active.textColor = fontColor; + disabledName.focused.textColor = fontColor; + disabledName.hover.textColor = fontColor; + disabledName.onNormal.textColor = fontColor; + disabledName.onActive.textColor = fontColor; + disabledName.onFocused.textColor = fontColor; + disabledName.onHover.textColor = fontColor; + } + } + + List info; + List behavioursInfo; + NetworkIdentity identity; + GUIContent title; + Styles styles = new Styles(); + + public override void Initialize(UnityObject[] targets) + { + base.Initialize(targets); + GetNetworkInformation(target as GameObject); + } + + public override GUIContent GetPreviewTitle() + { + if (title == null) + { + title = new GUIContent("Network Information"); + } + return title; + } + + public override bool HasPreviewGUI() + { + return info != null && info.Count > 0; + } + + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (Event.current.type != EventType.Repaint) + return; + + if (info == null || info.Count == 0) + return; + + if (styles == null) + styles = new Styles(); + + // Get required label size for the names of the information values we're going to show + // There are two columns, one with label for the name of the info and the next for the value + Vector2 maxNameLabelSize = new Vector2(140, 16); + Vector2 maxValueLabelSize = GetMaxNameLabelSize(); + + //Apply padding + RectOffset previewPadding = new RectOffset(-5, -5, -5, -5); + Rect paddedr = previewPadding.Add(r); + + //Centering + float initialX = paddedr.x + 10; + float initialY = paddedr.y + 10; + + Rect labelRect = new Rect(initialX, initialY, maxNameLabelSize.x, maxNameLabelSize.y); + Rect idLabelRect = new Rect(maxNameLabelSize.x, initialY, maxValueLabelSize.x, maxValueLabelSize.y); + + foreach (NetworkIdentityInfo info in info) + { + GUI.Label(labelRect, info.name, styles.labelStyle); + GUI.Label(idLabelRect, info.value, styles.componentName); + labelRect.y += labelRect.height; + labelRect.x = initialX; + idLabelRect.y += idLabelRect.height; + } + + // Show behaviours list in a different way than the name/value pairs above + float lastY = labelRect.y; + if (behavioursInfo != null && behavioursInfo.Count > 0) + { + Vector2 maxBehaviourLabelSize = GetMaxBehaviourLabelSize(); + Rect behaviourRect = new Rect(initialX, labelRect.y + 10, maxBehaviourLabelSize.x, maxBehaviourLabelSize.y); + + GUI.Label(behaviourRect, new GUIContent("Network Behaviours"), styles.labelStyle); + behaviourRect.x += 20; // indent names + behaviourRect.y += behaviourRect.height; + + foreach (NetworkBehaviourInfo info in behavioursInfo) + { + if (info.behaviour == null) + { + // could be the case in the editor after existing play mode. + continue; + } + + GUI.Label(behaviourRect, info.name, info.behaviour.enabled ? styles.componentName : styles.disabledName); + behaviourRect.y += behaviourRect.height; + lastY = behaviourRect.y; + } + + if (identity.observers != null && identity.observers.Count > 0) + { + Rect observerRect = new Rect(initialX, lastY + 10, 200, 20); + + GUI.Label(observerRect, new GUIContent("Network observers"), styles.labelStyle); + observerRect.x += 20; // indent names + observerRect.y += observerRect.height; + + foreach (KeyValuePair kvp in identity.observers) + { + GUI.Label(observerRect, kvp.Value.address + ":" + kvp.Value.connectionId, styles.componentName); + observerRect.y += observerRect.height; + lastY = observerRect.y; + } + } + + if (identity.clientAuthorityOwner != null) + { + Rect ownerRect = new Rect(initialX, lastY + 10, 400, 20); + GUI.Label(ownerRect, new GUIContent("Client Authority: " + identity.clientAuthorityOwner), styles.labelStyle); + } + } + } + + // Get the maximum size used by the value of information items + Vector2 GetMaxNameLabelSize() + { + Vector2 maxLabelSize = Vector2.zero; + foreach (NetworkIdentityInfo info in info) + { + Vector2 labelSize = styles.labelStyle.CalcSize(info.value); + if (maxLabelSize.x < labelSize.x) + { + maxLabelSize.x = labelSize.x; + } + if (maxLabelSize.y < labelSize.y) + { + maxLabelSize.y = labelSize.y; + } + } + return maxLabelSize; + } + + Vector2 GetMaxBehaviourLabelSize() + { + Vector2 maxLabelSize = Vector2.zero; + foreach (NetworkBehaviourInfo behaviour in behavioursInfo) + { + Vector2 labelSize = styles.labelStyle.CalcSize(behaviour.name); + if (maxLabelSize.x < labelSize.x) + { + maxLabelSize.x = labelSize.x; + } + if (maxLabelSize.y < labelSize.y) + { + maxLabelSize.y = labelSize.y; + } + } + return maxLabelSize; + } + + void GetNetworkInformation(GameObject gameObject) + { + identity = gameObject.GetComponent(); + if (identity != null) + { + info = new List + { + GetAssetId(), + GetString("Scene ID", identity.sceneId.ToString("X")) + }; + + if (!Application.isPlaying) + { + return; + } + + info.Add(GetString("Network ID", identity.netId.ToString())); + + info.Add(GetBoolean("Is Client", identity.isClient)); + info.Add(GetBoolean("Is Server", identity.isServer)); + info.Add(GetBoolean("Has Authority", identity.hasAuthority)); + info.Add(GetBoolean("Is Local Player", identity.isLocalPlayer)); + + NetworkBehaviour[] behaviours = gameObject.GetComponents(); + if (behaviours.Length > 0) + { + behavioursInfo = new List(); + foreach (NetworkBehaviour behaviour in behaviours) + { + NetworkBehaviourInfo info = new NetworkBehaviourInfo + { + name = new GUIContent(behaviour.GetType().FullName), + behaviour = behaviour + }; + behavioursInfo.Add(info); + } + } + } + } + + NetworkIdentityInfo GetAssetId() + { + string assetId = identity.assetId.ToString(); + if (string.IsNullOrEmpty(assetId)) + { + assetId = ""; + } + return GetString("Asset ID", assetId); + } + + static NetworkIdentityInfo GetString(string name, string value) + { + NetworkIdentityInfo info = new NetworkIdentityInfo + { + name = new GUIContent(name), + value = new GUIContent(value) + }; + return info; + } + + static NetworkIdentityInfo GetBoolean(string name, bool value) + { + NetworkIdentityInfo info = new NetworkIdentityInfo + { + name = new GUIContent(name), + value = new GUIContent((value ? "Yes" : "No")) + }; + return info; + } + } +} diff --git a/Assets/Packages/Mirror/Editor/NetworkInformationPreview.cs.meta b/Assets/Packages/Mirror/Editor/NetworkInformationPreview.cs.meta new file mode 100644 index 0000000..9bf2de4 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkInformationPreview.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 51a99294efe134232932c34606737356 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/NetworkManagerEditor.cs b/Assets/Packages/Mirror/Editor/NetworkManagerEditor.cs new file mode 100644 index 0000000..0552cfa --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkManagerEditor.cs @@ -0,0 +1,112 @@ +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; + +namespace Mirror +{ + [CustomEditor(typeof(NetworkManager), true)] + [CanEditMultipleObjects] + 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, + drawElementCallback = DrawChild, + onReorderCallback = Changed, + onRemoveCallback = RemoveButton, + onChangedCallback = Changed, + onAddCallback = AddButton, + elementHeight = 16 // this uses a 16x16 icon. other sizes make it stretch. + }; + } + } + + public override void OnInspectorGUI() + { + Init(); + DrawDefaultInspector(); + EditorGUI.BeginChangeCheck(); + spawnList.DoLayoutList(); + if (EditorGUI.EndChangeCheck()) + { + serializedObject.ApplyModifiedProperties(); + } + } + + static void DrawHeader(Rect headerRect) + { + GUI.Label(headerRect, "Registered Spawnable Prefabs:"); + } + + internal void DrawChild(Rect r, int index, bool isActive, bool isFocused) + { + SerializedProperty prefab = spawnListProperty.GetArrayElementAtIndex(index); + GameObject go = (GameObject)prefab.objectReferenceValue; + + GUIContent label; + if (go == null) + { + label = new GUIContent("Empty", "Drag a prefab with a NetworkIdentity here"); + } + else + { + NetworkIdentity identity = go.GetComponent(); + label = new GUIContent(go.name, identity != null ? "AssetId: [" + identity.assetId + "]" : "No Network Identity"); + } + + GameObject newGameObject = (GameObject)EditorGUI.ObjectField(r, label, go, typeof(GameObject), false); + + if (newGameObject != go) + { + if (newGameObject != null && !newGameObject.GetComponent()) + { + Debug.LogError("Prefab " + newGameObject + " cannot be added as spawnable as it doesn't have a NetworkIdentity."); + return; + } + prefab.objectReferenceValue = newGameObject; + } + } + + internal void Changed(ReorderableList list) + { + EditorUtility.SetDirty(target); + } + + internal void AddButton(ReorderableList list) + { + spawnListProperty.arraySize += 1; + list.index = spawnListProperty.arraySize - 1; + + SerializedProperty obj = spawnListProperty.GetArrayElementAtIndex(spawnListProperty.arraySize - 1); + obj.objectReferenceValue = null; + + spawnList.index = spawnList.count - 1; + + Changed(list); + } + + internal void RemoveButton(ReorderableList list) + { + spawnListProperty.DeleteArrayElementAtIndex(spawnList.index); + if (list.index >= spawnListProperty.arraySize) + { + list.index = spawnListProperty.arraySize - 1; + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/NetworkManagerEditor.cs.meta b/Assets/Packages/Mirror/Editor/NetworkManagerEditor.cs.meta new file mode 100644 index 0000000..7fe8dbc --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkManagerEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 519712eb07f7a44039df57664811c2c5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/NetworkScenePostProcess.cs b/Assets/Packages/Mirror/Editor/NetworkScenePostProcess.cs new file mode 100644 index 0000000..866a50b --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkScenePostProcess.cs @@ -0,0 +1,90 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEditor.Callbacks; +using UnityEngine; + +namespace Mirror +{ + public class NetworkScenePostProcess : MonoBehaviour + { + [PostProcessScene] + public static void OnPostProcessScene() + { + // find all NetworkIdentities in all scenes + // => can't limit it to GetActiveScene() because that wouldn't work + // for additive scene loads (the additively loaded scene is never + // the active scene) + // => ignore DontDestroyOnLoad scene! this avoids weird situations + // like in NetworkZones when we destroy the local player and + // load another scene afterwards, yet the local player is still + // in the FindObjectsOfType result with scene=DontDestroyOnLoad + // for some reason + // => OfTypeAll so disabled objects are included too + // => Unity 2019 returns prefabs here too, so filter them out. + IEnumerable identities = Resources.FindObjectsOfTypeAll() + .Where(identity => identity.gameObject.hideFlags != HideFlags.NotEditable && + identity.gameObject.hideFlags != HideFlags.HideAndDontSave && + identity.gameObject.scene.name != "DontDestroyOnLoad" && + !PrefabUtility.IsPartOfPrefabAsset(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, + // and we don't want to set main scene's objects inactive again + if (!identity.isClient && !identity.isServer) + { + // valid scene object? + // otherwise it might be an unopened scene that still has null + // sceneIds. builds are interrupted if they contain 0 sceneIds, + // but it's still possible that we call LoadScene in Editor + // for a previously unopened scene. + // (and only do SetActive if this was actually a scene object) + if (identity.sceneId != 0) + { + // set scene hash + identity.SetSceneIdSceneHashPartInternal(); + + // disable it + // 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) as GameObject; + #else + GameObject prefabGO = PrefabUtility.GetPrefabParent(identity.gameObject) as 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) + { + if (prefabRootGO.GetComponentsInChildren().Length > 1) + { + Debug.LogWarningFormat("Prefab '{0}' has several NetworkIdentity components attached to itself or its children, this is not supported.", prefabRootGO.name); + } + } + } + } + // 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."); + } + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/NetworkScenePostProcess.cs.meta b/Assets/Packages/Mirror/Editor/NetworkScenePostProcess.cs.meta new file mode 100644 index 0000000..b567cc9 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/NetworkScenePostProcess.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a3ec1c414d821444a9e77f18a2c130ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/PreprocessorDefine.cs b/Assets/Packages/Mirror/Editor/PreprocessorDefine.cs new file mode 100644 index 0000000..dd55178 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/PreprocessorDefine.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using UnityEditor; + +namespace Mirror +{ + static class PreprocessorDefine + { + /// + /// Add define symbols as soon as Unity gets done compiling. + /// + [InitializeOnLoadMethod] + static void AddDefineSymbols() + { + HashSet defines = new HashSet(PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup).Split(';')) + { + "MIRROR", + "MIRROR_1726_OR_NEWER", + "MIRROR_3_0_OR_NEWER", + "MIRROR_3_12_OR_NEWER" + }; + PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(";", defines)); + } + } +} diff --git a/Assets/Packages/Mirror/Editor/PreprocessorDefine.cs.meta b/Assets/Packages/Mirror/Editor/PreprocessorDefine.cs.meta new file mode 100644 index 0000000..30806d0 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/PreprocessorDefine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1d66fe74ec6f42dd974cba37d25d453 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/SceneDrawer.cs b/Assets/Packages/Mirror/Editor/SceneDrawer.cs new file mode 100644 index 0000000..b6c04f4 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/SceneDrawer.cs @@ -0,0 +1,56 @@ +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + + [CustomPropertyDrawer(typeof(SceneAttribute))] + public class SceneDrawer : PropertyDrawer + { + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + + if (property.propertyType == SerializedPropertyType.String) + { + SceneAsset sceneObject = GetSceneObject(property.stringValue); + SceneAsset scene = (SceneAsset)EditorGUI.ObjectField(position, label, sceneObject, typeof(SceneAsset), true); + if (scene == null) + { + property.stringValue = ""; + } + else if (scene.name != property.stringValue) + { + SceneAsset sceneObj = GetSceneObject(scene.name); + if (sceneObj == null) + { + Debug.LogWarning("The scene " + scene.name + " cannot be used. To use this scene add it to the build settings for the project"); + } + else + { + property.stringValue = scene.name; + } + } + } + else + EditorGUI.LabelField(position, label.text, "Use [Scene] with strings."); + } + protected SceneAsset GetSceneObject(string sceneObjectName) + { + if (string.IsNullOrEmpty(sceneObjectName)) + { + return null; + } + + foreach (EditorBuildSettingsScene editorScene in EditorBuildSettings.scenes) + { + if (editorScene.path.IndexOf(sceneObjectName) != -1) + { + return AssetDatabase.LoadAssetAtPath(editorScene.path, typeof(SceneAsset)) as SceneAsset; + } + } + Debug.LogWarning("Scene [" + sceneObjectName + "] cannot be used. Add this scene to the 'Scenes in the Build' in build settings."); + return null; + } + } +} diff --git a/Assets/Packages/Mirror/Editor/SceneDrawer.cs.meta b/Assets/Packages/Mirror/Editor/SceneDrawer.cs.meta new file mode 100644 index 0000000..6a996dc --- /dev/null +++ b/Assets/Packages/Mirror/Editor/SceneDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b24704a46211b4ea294aba8f58715cea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver.meta b/Assets/Packages/Mirror/Editor/Weaver.meta new file mode 100644 index 0000000..121fbf4 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d9f8e6274119b4ce29e498cfb8aca8a4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/CompilationFinishedHook.cs b/Assets/Packages/Mirror/Editor/Weaver/CompilationFinishedHook.cs new file mode 100644 index 0000000..501d378 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/CompilationFinishedHook.cs @@ -0,0 +1,141 @@ +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"; + + public static Action OnWeaverMessage; // delegate for subscription to Weaver debug messages + public static Action OnWeaverWarning; // delegate for subscription to Weaver warning messages + public static Action OnWeaverError; // delete for subscription to Weaver error messages + + public static bool WeaverEnabled { get; set; } // controls whether we weave any assemblies when CompilationPipeline delegates are invoked + public static bool UnityLogEnabled = true; // controls weather Weaver errors are reported direct to the Unity console (tests enable this) + public static bool WeaveFailed { get; private set; } // holds the result status of our latest Weave operation + + // debug message handler that also calls OnMessageMethod delegate + static void HandleMessage(string msg) + { + if (UnityLogEnabled) Debug.Log(msg); + if (OnWeaverMessage != null) OnWeaverMessage.Invoke(msg); + } + + // 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] + static void OnInitializeOnLoad() + { + CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished; + } + + 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; + } + + // 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)); + } + } + + // passing null in the outputDirectory param will do an in-place update of the assembly + if (Program.Process(unityEngineCoreModuleDLL, mirrorRuntimeDll, null, new[] { assemblyPath }, dependencyPaths.ToArray(), HandleWarning, HandleError)) + { + WeaveFailed = false; + //Debug.Log("Weaving succeeded for: " + assemblyPath); + } + else + { + WeaveFailed = true; + if (UnityLogEnabled) Debug.LogError("Weaving failed for: " + assemblyPath); + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/CompilationFinishedHook.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/CompilationFinishedHook.cs.meta new file mode 100644 index 0000000..ed537ab --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/CompilationFinishedHook.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de2aeb2e8068f421a9a1febe408f7051 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Extensions.cs b/Assets/Packages/Mirror/Editor/Weaver/Extensions.cs new file mode 100644 index 0000000..f2fad51 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Extensions.cs @@ -0,0 +1,151 @@ +using System; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + public static class Extensions + { + public static bool IsDerivedFrom(this TypeDefinition td, TypeReference baseClass) + { + 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 + int index = parentName.IndexOf('<'); + if (index != -1) + { + parentName = parentName.Substring(0, index); + } + + if (parentName == baseClass.FullName) + { + return true; + } + try + { + parent = parent.Resolve().BaseType; + } + catch (AssemblyResolutionException) + { + // this can happen for plugins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + return false; + } + + public static TypeReference GetEnumUnderlyingType(this TypeDefinition td) + { + foreach (FieldDefinition field in td.Fields) + { + if (!field.IsStatic) + return field.FieldType; + } + throw new ArgumentException($"Invalid enum {td.FullName}"); + } + + public static bool ImplementsInterface(this TypeDefinition td, TypeReference baseInterface) + { + TypeDefinition typedef = td; + while (typedef != null) + { + foreach (InterfaceImplementation iface in typedef.Interfaces) + { + if (iface.InterfaceType.FullName == baseInterface.FullName) + return true; + } + + try + { + TypeReference parent = typedef.BaseType; + typedef = parent?.Resolve(); + } + catch (AssemblyResolutionException) + { + // this can happen for pluins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + + return false; + } + + public static bool IsArrayType(this TypeReference tr) + { + if ((tr.IsArray && ((ArrayType)tr).ElementType.IsArray) || // jagged array + (tr.IsArray && ((ArrayType)tr).Rank > 1)) // multidimensional array + return false; + return true; + } + + public static bool CanBeResolved(this TypeReference parent) + { + while (parent != null) + { + if (parent.Scope.Name == "Windows") + { + return false; + } + + if (parent.Scope.Name == "mscorlib") + { + TypeDefinition resolved = parent.Resolve(); + return resolved != null; + } + + try + { + parent = parent.Resolve().BaseType; + } + catch + { + return false; + } + } + return true; + } + + + // Given a method of a generic class such as ArraySegment.get_Count, + // and a generic instance such as ArraySegment + // Creates a reference to the specialized method ArraySegment.get_Count; + // Note that calling ArraySegment.get_Count directly gives an invalid IL error + public static MethodReference MakeHostInstanceGeneric(this MethodReference self, GenericInstanceType instanceType) + { + + MethodReference reference = new MethodReference(self.Name, self.ReturnType, instanceType) + { + CallingConvention = self.CallingConvention, + HasThis = self.HasThis, + ExplicitThis = self.ExplicitThis + }; + + foreach (ParameterDefinition parameter in self.Parameters) + reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType)); + + foreach (GenericParameter generic_parameter in self.GenericParameters) + reference.GenericParameters.Add(new GenericParameter(generic_parameter.Name, reference)); + + return Weaver.CurrentAssembly.MainModule.ImportReference(reference); + } + + public static CustomAttribute GetCustomAttribute(this MethodDefinition method, string attributeName) + { + foreach (CustomAttribute ca in method.CustomAttributes) + { + if (ca.AttributeType.FullName == attributeName) + return ca; + } + return null; + } + + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Extensions.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Extensions.cs.meta new file mode 100644 index 0000000..78660f9 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Extensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 562a5cf0254cc45738e9aa549a7100b2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Helpers.cs b/Assets/Packages/Mirror/Editor/Weaver/Helpers.cs new file mode 100644 index 0000000..a776954 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Helpers.cs @@ -0,0 +1,124 @@ +using System; +using System.Linq; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using Mono.CecilX; +using Mono.CecilX.Cil; +using Mono.CecilX.Mdb; +using Mono.CecilX.Pdb; + +namespace Mirror.Weaver +{ + class Helpers + { + // This code is taken from SerializationWeaver + + class AddSearchDirectoryHelper + { + delegate void AddSearchDirectoryDelegate(string directory); + readonly AddSearchDirectoryDelegate _addSearchDirectory; + + public AddSearchDirectoryHelper(IAssemblyResolver assemblyResolver) + { + // reflection is used because IAssemblyResolver doesn't implement AddSearchDirectory but both DefaultAssemblyResolver and NuGetAssemblyResolver do + MethodInfo addSearchDirectory = assemblyResolver.GetType().GetMethod("AddSearchDirectory", BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(string) }, null); + if (addSearchDirectory == null) + throw new Exception("Assembly resolver doesn't implement AddSearchDirectory method."); + _addSearchDirectory = (AddSearchDirectoryDelegate)Delegate.CreateDelegate(typeof(AddSearchDirectoryDelegate), assemblyResolver, addSearchDirectory); + } + + public void AddSearchDirectory(string directory) + { + _addSearchDirectory(directory); + } + } + + public static string UnityEngineDLLDirectoryName() + { + string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); + return directoryName?.Replace(@"file:\", ""); + } + + public static ISymbolReaderProvider GetSymbolReaderProvider(string inputFile) + { + string nakedFileName = inputFile.Substring(0, inputFile.Length - 4); + if (File.Exists(nakedFileName + ".pdb")) + { + Console.WriteLine("Symbols will be read from " + nakedFileName + ".pdb"); + return new PdbReaderProvider(); + } + if (File.Exists(nakedFileName + ".dll.mdb")) + { + Console.WriteLine("Symbols will be read from " + nakedFileName + ".dll.mdb"); + return new MdbReaderProvider(); + } + Console.WriteLine("No symbols for " + inputFile); + return null; + } + + public static string DestinationFileFor(string outputDir, string assemblyPath) + { + string fileName = Path.GetFileName(assemblyPath); + Debug.Assert(fileName != null, "fileName != null"); + + return Path.Combine(outputDir, fileName); + } + + public static string PrettyPrintType(TypeReference type) + { + // generic instances, such as List + if (type.IsGenericInstance) + { + GenericInstanceType giType = (GenericInstanceType)type; + return giType.Name.Substring(0, giType.Name.Length - 2) + "<" + string.Join(", ", giType.GenericArguments.Select(PrettyPrintType).ToArray()) + ">"; + } + + // generic types, such as List + if (type.HasGenericParameters) + { + return type.Name.Substring(0, type.Name.Length - 2) + "<" + string.Join(", ", type.GenericParameters.Select(x => x.Name).ToArray()) + ">"; + } + + // non-generic type such as Int + return type.Name; + } + + public static ReaderParameters ReaderParameters(string assemblyPath, IEnumerable extraPaths, IAssemblyResolver assemblyResolver, string unityEngineDLLPath, string mirrorNetDLLPath) + { + ReaderParameters parameters = new ReaderParameters {ReadWrite = true}; + if (assemblyResolver == null) + assemblyResolver = new DefaultAssemblyResolver(); + AddSearchDirectoryHelper helper = new AddSearchDirectoryHelper(assemblyResolver); + helper.AddSearchDirectory(Path.GetDirectoryName(assemblyPath)); + helper.AddSearchDirectory(UnityEngineDLLDirectoryName()); + helper.AddSearchDirectory(Path.GetDirectoryName(unityEngineDLLPath)); + helper.AddSearchDirectory(Path.GetDirectoryName(mirrorNetDLLPath)); + if (extraPaths != null) + { + foreach (string path in extraPaths) + helper.AddSearchDirectory(path); + } + parameters.AssemblyResolver = assemblyResolver; + parameters.SymbolReaderProvider = GetSymbolReaderProvider(assemblyPath); + return parameters; + } + + public static WriterParameters GetWriterParameters(ReaderParameters readParams) + { + WriterParameters writeParams = new WriterParameters(); + if (readParams.SymbolReaderProvider is PdbReaderProvider) + { + //Log("Will export symbols of pdb format"); + writeParams.SymbolWriterProvider = new PdbWriterProvider(); + } + else if (readParams.SymbolReaderProvider is MdbReaderProvider) + { + //Log("Will export symbols of mdb format"); + writeParams.SymbolWriterProvider = new MdbWriterProvider(); + } + return writeParams; + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Helpers.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Helpers.cs.meta new file mode 100644 index 0000000..231f539 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Helpers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c4ed76daf48547c5abb7c58f8d20886 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Mirror.Weaver.asmdef b/Assets/Packages/Mirror/Editor/Weaver/Mirror.Weaver.asmdef new file mode 100644 index 0000000..5122428 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Mirror.Weaver.asmdef @@ -0,0 +1,14 @@ +{ + "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/Packages/Mirror/Editor/Weaver/Mirror.Weaver.asmdef.meta b/Assets/Packages/Mirror/Editor/Weaver/Mirror.Weaver.asmdef.meta new file mode 100644 index 0000000..b65a0cd --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Mirror.Weaver.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1d0b9d21c3ff546a4aa32399dfd33474 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors.meta new file mode 100644 index 0000000..eb719b4 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e538d627280d2471b8c72fdea822ca49 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/CommandProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/CommandProcessor.cs new file mode 100644 index 0000000..2a1688f --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/CommandProcessor.cs @@ -0,0 +1,153 @@ +// all the [Command] code from NetworkBehaviourProcessor in one place +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class CommandProcessor + { + const string CmdPrefix = "InvokeCmd"; + + /* + // generates code like: + public void CallCmdThrust(float thrusting, int spin) + { + if (isServer) + { + // we are ON the server, invoke directly + CmdThrust(thrusting, spin); + return; + } + + NetworkWriter networkWriter = new NetworkWriter(); + networkWriter.Write(thrusting); + networkWriter.WritePackedUInt32((uint)spin); + base.SendCommandInternal(cmdName, networkWriter, cmdName); + } + */ + public static MethodDefinition ProcessCommandCall(TypeDefinition td, MethodDefinition md, CustomAttribute ca) + { + MethodDefinition cmd = new MethodDefinition("Call" + md.Name, + MethodAttributes.Public | MethodAttributes.HideBySig, + Weaver.voidType); + + // add parameters + foreach (ParameterDefinition pd in md.Parameters) + { + cmd.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); + } + + ILProcessor cmdWorker = cmd.Body.GetILProcessor(); + + NetworkBehaviourProcessor.WriteSetupLocals(cmdWorker); + + if (Weaver.GenerateLogErrors) + { + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldstr, "Call Command function " + md.Name)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, Weaver.logErrorReference)); + } + + // local client check + Instruction localClientLabel = cmdWorker.Create(OpCodes.Nop); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, Weaver.getBehaviourIsServer)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Brfalse, localClientLabel)); + + // call the cmd function directly. + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + for (int i = 0; i < md.Parameters.Count; i++) + { + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg, i + 1)); + } + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, md)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + cmdWorker.Append(localClientLabel); + + // NetworkWriter writer = new NetworkWriter(); + NetworkBehaviourProcessor.WriteCreateWriter(cmdWorker); + + // write all the arguments that the user passed to the Cmd call + if (!NetworkBehaviourProcessor.WriteArguments(cmdWorker, md, false)) + return null; + + string cmdName = md.Name; + int index = cmdName.IndexOf(CmdPrefix); + if (index > -1) + { + cmdName = cmdName.Substring(CmdPrefix.Length); + } + + // invoke internal send and return + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); // load 'base.' to call the SendCommand function with + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldtoken, td)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, Weaver.getTypeFromHandleReference)); // invokerClass + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldstr, cmdName)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldloc_0)); // writer + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldc_I4, NetworkBehaviourProcessor.GetChannelId(ca))); + cmdWorker.Append(cmdWorker.Create(OpCodes.Call, Weaver.sendCommandInternal)); + + NetworkBehaviourProcessor.WriteRecycleWriter(cmdWorker); + + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + + return cmd; + } + + /* + // generates code like: + protected static void InvokeCmdCmdThrust(NetworkBehaviour obj, NetworkReader reader) + { + if (!NetworkServer.active) + { + return; + } + ((ShipControl)obj).CmdThrust(reader.ReadSingle(), (int)reader.ReadPackedUInt32()); + } + */ + public static MethodDefinition ProcessCommandInvoke(TypeDefinition td, MethodDefinition md) + { + MethodDefinition cmd = new MethodDefinition(CmdPrefix + md.Name, + MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig, + Weaver.voidType); + + ILProcessor cmdWorker = cmd.Body.GetILProcessor(); + Instruction label = cmdWorker.Create(OpCodes.Nop); + + NetworkBehaviourProcessor.WriteServerActiveCheck(cmdWorker, md.Name, label, "Command"); + + // setup for reader + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Castclass, td)); + + if (!NetworkBehaviourProcessor.ProcessNetworkReaderParameters(md, cmdWorker, false)) + return null; + + // invoke actual command function + cmdWorker.Append(cmdWorker.Create(OpCodes.Callvirt, md)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + + NetworkBehaviourProcessor.AddInvokeParameters(cmd.Parameters); + + return cmd; + } + + public static bool ProcessMethodsValidateCommand(MethodDefinition md, CustomAttribute ca) + { + if (!md.Name.StartsWith("Cmd")) + { + Weaver.Error($"{md} must start with Cmd. Consider renaming it to Cmd{md.Name}"); + return false; + } + + if (md.IsStatic) + { + Weaver.Error($"{md} cannot be static"); + return false; + } + + // validate + return NetworkBehaviourProcessor.ProcessMethodsValidateFunction(md) && + NetworkBehaviourProcessor.ProcessMethodsValidateParameters(md, ca); + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta new file mode 100644 index 0000000..20c3e15 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 73f6c9cdbb9e54f65b3a0a35cc8e55c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs new file mode 100644 index 0000000..131a6a5 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs @@ -0,0 +1,135 @@ +// this class generates OnSerialize/OnDeserialize when inheriting from MessageBase +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + static class MessageClassProcessor + { + 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"); + foreach (MethodDefinition m in td.Methods) + { + if (m.Name == "Serialize") + 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} has field ${field} that references itself"); + return; + } + } + + MethodDefinition serializeFunc = new MethodDefinition("Serialize", + MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, + Weaver.voidType); + + serializeFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); + ILProcessor serWorker = serializeFunc.Body.GetILProcessor(); + + foreach (FieldDefinition field in td.Fields) + { + if (field.IsStatic || field.IsPrivate || field.IsSpecialName) + continue; + + if (field.FieldType.Resolve().HasGenericParameters && !field.FieldType.FullName.StartsWith("System.ArraySegment`1", System.StringComparison.Ordinal)) + { + Weaver.Error($"{field} cannot have generic type {field.FieldType}. Consider creating a class that derives the generic type"); + return; + } + + if (field.FieldType.Resolve().IsInterface) + { + Weaver.Error($"{field} has unsupported type. Use a concrete class instead of interface {field.FieldType}"); + return; + } + + MethodReference writeFunc = Writers.GetWriteFunc(field.FieldType); + if (writeFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldfld, field)); + serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc)); + } + else + { + Weaver.Error($"{field} has unsupported type"); + return; + } + } + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + td.Methods.Add(serializeFunc); + } + + static void GenerateDeSerialization(TypeDefinition td) + { + Weaver.DLog(td, " GenerateDeserialization"); + foreach (MethodDefinition m in td.Methods) + { + if (m.Name == "Deserialize") + return; + } + + if (td.Fields.Count == 0) + { + return; + } + + MethodDefinition serializeFunc = new MethodDefinition("Deserialize", + MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, + Weaver.voidType); + + serializeFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkReaderType))); + ILProcessor serWorker = serializeFunc.Body.GetILProcessor(); + + foreach (FieldDefinition field in td.Fields) + { + if (field.IsStatic || field.IsPrivate || field.IsSpecialName) + continue; + + MethodReference readerFunc = Readers.GetReadFunc(field.FieldType); + if (readerFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, readerFunc)); + serWorker.Append(serWorker.Create(OpCodes.Stfld, field)); + } + else + { + Weaver.Error($"{field} has unsupported type"); + return; + } + } + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + td.Methods.Add(serializeFunc); + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs.meta new file mode 100644 index 0000000..875cf9a --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/MessageClassProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3544c9f00f6e5443ea3c30873c5a06ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs new file mode 100644 index 0000000..c5f880e --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs @@ -0,0 +1,77 @@ +// this class only shows warnings in case we use SyncVars etc. for MonoBehaviour. +using Mono.CecilX; + +namespace Mirror.Weaver +{ + static class MonoBehaviourProcessor + { + public static void Process(TypeDefinition td) + { + ProcessSyncVars(td); + ProcessMethods(td); + } + + static void ProcessSyncVars(TypeDefinition td) + { + // find syncvars + foreach (FieldDefinition fd in td.Fields) + { + foreach (CustomAttribute ca in fd.CustomAttributes) + { + if (ca.AttributeType.FullName == Weaver.SyncVarType.FullName) + { + Weaver.Error($"[SyncVar] {fd} must be inside a NetworkBehaviour. {td} is not a NetworkBehaviour"); + } + } + + if (SyncObjectInitializer.ImplementsSyncObject(fd.FieldType)) + { + Weaver.Error($"{fd} is a SyncObject and must be inside a NetworkBehaviour. {td} is not a NetworkBehaviour"); + } + } + } + + static void ProcessMethods(TypeDefinition td) + { + // find command and RPC functions + foreach (MethodDefinition md in td.Methods) + { + foreach (CustomAttribute ca in md.CustomAttributes) + { + if (ca.AttributeType.FullName == Weaver.CommandType.FullName) + { + Weaver.Error($"[Command] {md} must be declared inside a NetworkBehaviour"); + } + + if (ca.AttributeType.FullName == Weaver.ClientRpcType.FullName) + { + Weaver.Error($"[ClienRpc] {md} must be declared inside a NetworkBehaviour"); + } + + if (ca.AttributeType.FullName == Weaver.TargetRpcType.FullName) + { + Weaver.Error($"[TargetRpc] {md} must be declared inside a NetworkBehaviour"); + } + + string attributeName = ca.Constructor.DeclaringType.ToString(); + + switch (attributeName) + { + case "Mirror.ServerAttribute": + Weaver.Error($"[Server] {md} must be declared inside a NetworkBehaviour"); + break; + case "Mirror.ServerCallbackAttribute": + Weaver.Error($"[ServerCallback] {md} must be declared inside a NetworkBehaviour"); + break; + case "Mirror.ClientAttribute": + Weaver.Error($"[Client] {md} must be declared inside a NetworkBehaviour"); + break; + case "Mirror.ClientCallbackAttribute": + Weaver.Error($"[ClientCallback] {md} must be declared inside a NetworkBehaviour"); + break; + } + } + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta new file mode 100644 index 0000000..ef3f5f4 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35c16722912b64af894e4f6668f2e54c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs new file mode 100644 index 0000000..0b12e03 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs @@ -0,0 +1,858 @@ +// this class processes SyncVars, Cmds, Rpcs, etc. of NetworkBehaviours +using System; +using System.Linq; +using System.Collections.Generic; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + class NetworkBehaviourProcessor + { + readonly List syncVars = new List(); + readonly List syncObjects = new List(); + readonly Dictionary syncVarNetIds = 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 List commandCallFuncs = new List(); + readonly List clientRpcCallFuncs = new List(); + readonly List targetRpcCallFuncs = new List(); + + readonly TypeDefinition netBehaviourSubclass; + + public NetworkBehaviourProcessor(TypeDefinition td) + { + Weaver.DLog(td, "NetworkBehaviourProcessor"); + netBehaviourSubclass = td; + } + + public void Process() + { + if (netBehaviourSubclass.HasGenericParameters) + { + Weaver.Error($"{netBehaviourSubclass} cannot have generic parameters"); + return; + } + Weaver.DLog(netBehaviourSubclass, "Process Start"); + MarkAsProcessed(netBehaviourSubclass); + SyncVarProcessor.ProcessSyncVars(netBehaviourSubclass, syncVars, syncObjects, syncVarNetIds); + + ProcessMethods(); + + SyncEventProcessor.ProcessEvents(netBehaviourSubclass, eventRpcs, eventRpcInvocationFuncs); + if (Weaver.WeavingFailed) + { + return; + } + GenerateConstants(); + + GenerateSerialization(); + if (Weaver.WeavingFailed) + { + return; + } + + GenerateDeSerialization(); + Weaver.DLog(netBehaviourSubclass, "Process Done"); + } + + /* + generates code like: + if (!NetworkClient.active) + Debug.LogError((object) "Command function CmdRespawn called on server."); + + which is used in InvokeCmd, InvokeRpc, etc. + */ + public static void WriteClientActiveCheck(ILProcessor worker, string mdName, Instruction label, string errString) + { + // client active check + worker.Append(worker.Create(OpCodes.Call, Weaver.NetworkClientGetActive)); + worker.Append(worker.Create(OpCodes.Brtrue, label)); + + worker.Append(worker.Create(OpCodes.Ldstr, errString + " " + mdName + " called on server.")); + worker.Append(worker.Create(OpCodes.Call, Weaver.logErrorReference)); + worker.Append(worker.Create(OpCodes.Ret)); + worker.Append(label); + } + /* + generates code like: + if (!NetworkServer.active) + Debug.LogError((object) "Command CmdMsgWhisper called on client."); + */ + public static void WriteServerActiveCheck(ILProcessor worker, string mdName, Instruction label, string errString) + { + // server active check + worker.Append(worker.Create(OpCodes.Call, Weaver.NetworkServerGetActive)); + worker.Append(worker.Create(OpCodes.Brtrue, label)); + + worker.Append(worker.Create(OpCodes.Ldstr, errString + " " + mdName + " called on client.")); + worker.Append(worker.Create(OpCodes.Call, Weaver.logErrorReference)); + worker.Append(worker.Create(OpCodes.Ret)); + worker.Append(label); + } + + public static void WriteSetupLocals(ILProcessor worker) + { + worker.Body.InitLocals = true; + worker.Body.Variables.Add(new VariableDefinition(Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); + } + + public static void WriteCreateWriter(ILProcessor worker) + { + // create writer + worker.Append(worker.Create(OpCodes.Call, Weaver.GetPooledWriterReference)); + worker.Append(worker.Create(OpCodes.Stloc_0)); + } + + public static void WriteRecycleWriter(ILProcessor worker) + { + // NetworkWriterPool.Recycle(writer); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Call, Weaver.RecycleWriterReference)); + } + + public static bool WriteArguments(ILProcessor worker, MethodDefinition md, bool skipFirst) + { + // write each argument + short argNum = 1; + foreach (ParameterDefinition pd in md.Parameters) + { + if (argNum == 1 && skipFirst) + { + argNum += 1; + continue; + } + + MethodReference writeFunc = Writers.GetWriteFunc(pd.ParameterType); + if (writeFunc == null) + { + Weaver.Error($"{md} has invalid parameter {pd}" ); + return false; + } + // use built-in writer func on writer object + worker.Append(worker.Create(OpCodes.Ldloc_0)); // writer object + worker.Append(worker.Create(OpCodes.Ldarg, argNum)); // argument + worker.Append(worker.Create(OpCodes.Call, writeFunc)); // call writer func on writer object + argNum += 1; + } + return true; + } + + #region mark / check type as processed + public const string ProcessedFunctionName = "MirrorProcessed"; + + // by adding an empty MirrorProcessed() function + public static bool WasProcessed(TypeDefinition td) + { + return td.Methods.Any(method => method.Name == ProcessedFunctionName); + } + + public static void MarkAsProcessed(TypeDefinition td) + { + if (!WasProcessed(td)) + { + MethodDefinition versionMethod = new MethodDefinition(ProcessedFunctionName, MethodAttributes.Private, Weaver.voidType); + ILProcessor worker = versionMethod.Body.GetILProcessor(); + worker.Append(worker.Create(OpCodes.Ret)); + td.Methods.Add(versionMethod); + } + } + #endregion + + void GenerateConstants() + { + if (commands.Count == 0 && clientRpcs.Count == 0 && targetRpcs.Count == 0 && eventRpcs.Count == 0 && syncObjects.Count == 0) + return; + + Weaver.DLog(netBehaviourSubclass, " GenerateConstants "); + + // find static constructor + MethodDefinition cctor = null; + bool cctorFound = false; + foreach (MethodDefinition md in netBehaviourSubclass.Methods) + { + if (md.Name == ".cctor") + { + cctor = md; + cctorFound = true; + } + } + if (cctor != null) + { + // remove the return opcode from end of function. will add our own later. + if (cctor.Body.Instructions.Count != 0) + { + Instruction ret = cctor.Body.Instructions[cctor.Body.Instructions.Count - 1]; + if (ret.OpCode == OpCodes.Ret) + { + cctor.Body.Instructions.RemoveAt(cctor.Body.Instructions.Count - 1); + } + else + { + Weaver.Error($"{netBehaviourSubclass} has invalid class constructor"); + return; + } + } + } + else + { + // make one! + cctor = new MethodDefinition(".cctor", MethodAttributes.Private | + MethodAttributes.HideBySig | + MethodAttributes.SpecialName | + MethodAttributes.RTSpecialName | + MethodAttributes.Static, + Weaver.voidType); + } + + // find instance constructor + MethodDefinition ctor = null; + + foreach (MethodDefinition md in netBehaviourSubclass.Methods) + { + if (md.Name == ".ctor") + { + ctor = md; + + 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} has invalid constructor"); + return; + } + + break; + } + } + + if (ctor == null) + { + Weaver.Error($"{netBehaviourSubclass} has invalid constructor"); + return; + } + + ILProcessor ctorWorker = ctor.Body.GetILProcessor(); + ILProcessor cctorWorker = cctor.Body.GetILProcessor(); + + for (int i = 0; i < commands.Count; ++i) + { + GenerateRegisterCommandDelegate(cctorWorker, Weaver.registerCommandDelegateReference, commandInvocationFuncs[i], commands[i].Name); + } + + for (int i = 0; i < clientRpcs.Count; ++i) + { + GenerateRegisterCommandDelegate(cctorWorker, Weaver.registerRpcDelegateReference, clientRpcInvocationFuncs[i], clientRpcs[i].Name); + } + + for (int i = 0; i < targetRpcs.Count; ++i) + { + GenerateRegisterCommandDelegate(cctorWorker, Weaver.registerRpcDelegateReference, targetRpcInvocationFuncs[i], targetRpcs[i].Name); + } + + for (int i = 0; i < eventRpcs.Count; ++i) + { + GenerateRegisterCommandDelegate(cctorWorker, Weaver.registerEventDelegateReference, eventRpcInvocationFuncs[i], eventRpcs[i].Name); + } + + foreach (FieldDefinition fd in syncObjects) + { + SyncObjectInitializer.GenerateSyncObjectInitializer(ctorWorker, fd); + } + + cctorWorker.Append(cctorWorker.Create(OpCodes.Ret)); + if (!cctorFound) + { + netBehaviourSubclass.Methods.Add(cctor); + } + + // finish 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 GenerateRegisterCommandDelegate(ILProcessor awakeWorker, MethodReference registerMethod, MethodDefinition func, string cmdName) + { + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldtoken, netBehaviourSubclass)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Call, Weaver.getTypeFromHandleReference)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldstr, cmdName)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldnull)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Ldftn, func)); + + awakeWorker.Append(awakeWorker.Create(OpCodes.Newobj, Weaver.CmdDelegateConstructor)); + awakeWorker.Append(awakeWorker.Create(OpCodes.Call, registerMethod)); + } + + void GenerateSerialization() + { + Weaver.DLog(netBehaviourSubclass, " GenerateSerialization"); + + foreach (MethodDefinition m in netBehaviourSubclass.Methods) + { + if (m.Name == "OnSerialize") + return; + } + + if (syncVars.Count == 0) + { + // no synvars, no need for custom OnSerialize + return; + } + + MethodDefinition serialize = new MethodDefinition("OnSerialize", + MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, + Weaver.boolType); + + serialize.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); + serialize.Parameters.Add(new ParameterDefinition("forceAll", ParameterAttributes.None, Weaver.boolType)); + ILProcessor serWorker = serialize.Body.GetILProcessor(); + + serialize.Body.InitLocals = true; + + // loc_0, this local variable is to determine if any variable was dirty + VariableDefinition dirtyLocal = new VariableDefinition(Weaver.boolType); + serialize.Body.Variables.Add(dirtyLocal); + + MethodReference baseSerialize = Resolvers.ResolveMethodInParents(netBehaviourSubclass.BaseType, Weaver.CurrentAssembly, "OnSerialize"); + if (baseSerialize != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // base + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); // writer + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); // forceAll + serWorker.Append(serWorker.Create(OpCodes.Call, baseSerialize)); + serWorker.Append(serWorker.Create(OpCodes.Stloc_0)); // set dirtyLocal to result of base.OnSerialize() + } + + // Generates: if (forceAll); + Instruction initialStateLabel = serWorker.Create(OpCodes.Nop); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); // forceAll + serWorker.Append(serWorker.Create(OpCodes.Brfalse, initialStateLabel)); + + foreach (FieldDefinition syncVar in syncVars) + { + // Generates a writer call for each sync variable + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); // writer + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // this + serWorker.Append(serWorker.Create(OpCodes.Ldfld, syncVar)); + MethodReference writeFunc = Writers.GetWriteFunc(syncVar.FieldType); + if (writeFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc)); + } + else + { + Weaver.Error($"{syncVar} has unsupported type. Use a supported Mirror type instead"); + return; + } + } + + // always return true if forceAll + + // Generates: return true + serWorker.Append(serWorker.Create(OpCodes.Ldc_I4_1)); + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + // Generates: end if (forceAll); + serWorker.Append(initialStateLabel); + + // write dirty bits before the data fields + // Generates: writer.WritePackedUInt64 (base.get_syncVarDirtyBits ()); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); // writer + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // base + serWorker.Append(serWorker.Create(OpCodes.Call, Weaver.NetworkBehaviourDirtyBitsReference)); + serWorker.Append(serWorker.Create(OpCodes.Call, Writers.GetWriteFunc(Weaver.uint64Type))); + + // 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) + { + Instruction varLabel = serWorker.Create(OpCodes.Nop); + + // Generates: if ((base.get_syncVarDirtyBits() & 1uL) != 0uL) + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // base + serWorker.Append(serWorker.Create(OpCodes.Call, Weaver.NetworkBehaviourDirtyBitsReference)); + serWorker.Append(serWorker.Create(OpCodes.Ldc_I8, 1L << dirtyBit)); // 8 bytes = long + serWorker.Append(serWorker.Create(OpCodes.And)); + serWorker.Append(serWorker.Create(OpCodes.Brfalse, varLabel)); + + // Generates a call to the writer for that field + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); // writer + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // base + serWorker.Append(serWorker.Create(OpCodes.Ldfld, syncVar)); + + MethodReference writeFunc = Writers.GetWriteFunc(syncVar.FieldType); + if (writeFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc)); + } + else + { + Weaver.Error($"{syncVar} has unsupported type. Use a supported Mirror type instead"); + return; + } + + // something was dirty + serWorker.Append(serWorker.Create(OpCodes.Ldc_I4_1)); + serWorker.Append(serWorker.Create(OpCodes.Stloc_0)); // set dirtyLocal to true + + serWorker.Append(varLabel); + dirtyBit += 1; + } + + if (Weaver.GenerateLogErrors) + { + serWorker.Append(serWorker.Create(OpCodes.Ldstr, "Injected Serialize " + netBehaviourSubclass.Name)); + serWorker.Append(serWorker.Create(OpCodes.Call, Weaver.logErrorReference)); + } + + // generate: return dirtyLocal + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + serWorker.Append(serWorker.Create(OpCodes.Ret)); + netBehaviourSubclass.Methods.Add(serialize); + } + + public static int GetChannelId(CustomAttribute ca) + { + foreach (CustomAttributeNamedArgument customField in ca.Fields) + { + if (customField.Name == "channel") + { + return (int)customField.Argument.Value; + } + } + + return 0; + } + + void DeserializeField(FieldDefinition syncVar, ILProcessor serWorker, MethodDefinition deserialize) + { + // check for Hook function + if (!SyncVarProcessor.CheckForHookFunction(netBehaviourSubclass, syncVar, out MethodDefinition foundMethod)) + { + return; + } + + if (syncVar.FieldType.FullName == Weaver.gameObjectType.FullName || + syncVar.FieldType.FullName == Weaver.NetworkIdentityType.FullName) + { + // 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]; + + VariableDefinition tmpValue = new VariableDefinition(Weaver.uint32Type); + deserialize.Body.Variables.Add(tmpValue); + + // read id and store in a local variable + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, Readers.GetReadFunc(Weaver.uint32Type))); + serWorker.Append(serWorker.Create(OpCodes.Stloc, tmpValue)); + + if (foundMethod != null) + { + // call Hook(this.GetSyncVarGameObject/NetworkIdentity(reader.ReadPackedUInt32())) + // because we send/receive the netID, not the GameObject/NetworkIdentity + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // this. + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldloc, tmpValue)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldflda, syncVar)); + if (syncVar.FieldType.FullName == Weaver.gameObjectType.FullName) + serWorker.Append(serWorker.Create(OpCodes.Callvirt, Weaver.getSyncVarGameObjectReference)); + else if (syncVar.FieldType.FullName == Weaver.NetworkIdentityType.FullName) + serWorker.Append(serWorker.Create(OpCodes.Callvirt, Weaver.getSyncVarNetworkIdentityReference)); + serWorker.Append(serWorker.Create(OpCodes.Call, foundMethod)); + } + // set the netid field + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldloc, tmpValue)); + serWorker.Append(serWorker.Create(OpCodes.Stfld, netIdField)); + } + else + { + MethodReference readFunc = Readers.GetReadFunc(syncVar.FieldType); + if (readFunc == null) + { + Weaver.Error($"{syncVar} has unsupported type. Use a supported Mirror type instead"); + return; + } + VariableDefinition tmpValue = new VariableDefinition(syncVar.FieldType); + deserialize.Body.Variables.Add(tmpValue); + + // read value and put it in a local variable + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, readFunc)); + serWorker.Append(serWorker.Create(OpCodes.Stloc, tmpValue)); + + if (foundMethod != null) + { + // call hook + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldloc, tmpValue)); + serWorker.Append(serWorker.Create(OpCodes.Call, foundMethod)); + } + // set the property + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldloc, tmpValue)); + serWorker.Append(serWorker.Create(OpCodes.Stfld, syncVar)); + } + + } + + void GenerateDeSerialization() + { + Weaver.DLog(netBehaviourSubclass, " GenerateDeSerialization"); + + foreach (MethodDefinition m in netBehaviourSubclass.Methods) + { + if (m.Name == "OnDeserialize") + return; + } + + if (syncVars.Count == 0) + { + // no synvars, no need for custom OnDeserialize + return; + } + + MethodDefinition serialize = new MethodDefinition("OnDeserialize", + MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, + Weaver.voidType); + + serialize.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkReaderType))); + serialize.Parameters.Add(new ParameterDefinition("initialState", ParameterAttributes.None, Weaver.boolType)); + ILProcessor serWorker = serialize.Body.GetILProcessor(); + // setup local for dirty bits + serialize.Body.InitLocals = true; + VariableDefinition dirtyBitsLocal = new VariableDefinition(Weaver.int64Type); + serialize.Body.Variables.Add(dirtyBitsLocal); + + MethodReference baseDeserialize = Resolvers.ResolveMethodInParents(netBehaviourSubclass.BaseType, Weaver.CurrentAssembly, "OnDeserialize"); + if (baseDeserialize != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); // base + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); // reader + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); // initialState + serWorker.Append(serWorker.Create(OpCodes.Call, baseDeserialize)); + } + + // Generates: if (initialState); + Instruction initialStateLabel = serWorker.Create(OpCodes.Nop); + + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); + serWorker.Append(serWorker.Create(OpCodes.Brfalse, initialStateLabel)); + + foreach (FieldDefinition syncVar in syncVars) + { + DeserializeField(syncVar, serWorker, serialize); + } + + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + // Generates: end if (initialState); + serWorker.Append(initialStateLabel); + + + // get dirty bits + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, Readers.GetReadFunc(Weaver.uint64Type))); + serWorker.Append(serWorker.Create(OpCodes.Stloc_0)); + + // conditionally read each syncvar + int dirtyBit = Weaver.GetSyncVarStart(netBehaviourSubclass.BaseType.FullName); // start at number of syncvars in parent + foreach (FieldDefinition syncVar in syncVars) + { + Instruction varLabel = serWorker.Create(OpCodes.Nop); + + // check if dirty bit is set + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldc_I8, 1L << dirtyBit)); + serWorker.Append(serWorker.Create(OpCodes.And)); + serWorker.Append(serWorker.Create(OpCodes.Brfalse, varLabel)); + + DeserializeField(syncVar, serWorker, serialize); + + serWorker.Append(varLabel); + dirtyBit += 1; + } + + if (Weaver.GenerateLogErrors) + { + serWorker.Append(serWorker.Create(OpCodes.Ldstr, "Injected Deserialize " + netBehaviourSubclass.Name)); + serWorker.Append(serWorker.Create(OpCodes.Call, Weaver.logErrorReference)); + } + + serWorker.Append(serWorker.Create(OpCodes.Ret)); + netBehaviourSubclass.Methods.Add(serialize); + } + + public static bool ProcessNetworkReaderParameters(MethodDefinition md, ILProcessor worker, bool skipFirst) + { + int count = 0; + + // read cmd args from NetworkReader + foreach (ParameterDefinition arg in md.Parameters) + { + if (count++ == 0 && skipFirst) + { + continue; + } + MethodReference readFunc = Readers.GetReadFunc(arg.ParameterType); //? + + if (readFunc != null) + { + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Call, readFunc)); + + // conversion.. is this needed? + if (arg.ParameterType.FullName == Weaver.singleType.FullName) + { + worker.Append(worker.Create(OpCodes.Conv_R4)); + } + else if (arg.ParameterType.FullName == Weaver.doubleType.FullName) + { + worker.Append(worker.Create(OpCodes.Conv_R8)); + } + } + else + { + Weaver.Error($"{md} has invalid parameter {arg}. Unsupported type {arg.ParameterType}, use a supported Mirror type instead"); + return false; + } + } + return true; + } + + public static void AddInvokeParameters(ICollection collection) + { + collection.Add(new ParameterDefinition("obj", ParameterAttributes.None, Weaver.NetworkBehaviourType2)); + collection.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkReaderType))); + } + + public static bool ProcessMethodsValidateFunction(MethodReference md) + { + if (md.ReturnType.FullName == Weaver.IEnumeratorType.FullName) + { + Weaver.Error($"{md} cannot be a coroutine"); + return false; + } + if (md.ReturnType.FullName != Weaver.voidType.FullName) + { + Weaver.Error($"{md} cannot return a value. Make it void instead"); + return false; + } + if (md.HasGenericParameters) + { + Weaver.Error($"{md} cannot have generic parameters"); + return false; + } + return true; + } + + public static bool ProcessMethodsValidateParameters(MethodReference md, CustomAttribute ca) + { + for (int i = 0; i < md.Parameters.Count; ++i) + { + ParameterDefinition p = md.Parameters[i]; + if (p.IsOut) + { + Weaver.Error($"{md} cannot have out parameters"); + return false; + } + if (p.IsOptional) + { + Weaver.Error($"{md} cannot have optional parameters"); + return false; + } + if (p.ParameterType.Resolve().IsAbstract) + { + Weaver.Error($"{md} has invalid parameter {p}. Use concrete type instead of abstract type {p.ParameterType}"); + return false; + } + if (p.ParameterType.IsByReference) + { + Weaver.Error($"{md} has invalid parameter {p}. Use supported type instead of reference type {p.ParameterType}"); + return false; + } + // TargetRPC is an exception to this rule and can have a NetworkConnection as first parameter + if (p.ParameterType.FullName == Weaver.NetworkConnectionType.FullName && + !(ca.AttributeType.FullName == Weaver.TargetRpcType.FullName && i == 0)) + { + Weaver.Error($"{md} has invalid parameer {p}. Cannot pass NeworkConnections"); + return false; + } + if (p.ParameterType.Resolve().IsDerivedFrom(Weaver.ComponentType)) + { + if (p.ParameterType.FullName != Weaver.NetworkIdentityType.FullName) + { + Weaver.Error($"{md} has invalid parameter {p}. Cannot pass components in remote method calls"); + return false; + } + } + } + return true; + } + + void ProcessMethods() + { + HashSet names = new HashSet(); + + // find command and RPC functions + foreach (MethodDefinition md in netBehaviourSubclass.Methods) + { + foreach (CustomAttribute ca in md.CustomAttributes) + { + if (ca.AttributeType.FullName == Weaver.CommandType.FullName) + { + ProcessCommand(names, md, ca); + break; + } + + if (ca.AttributeType.FullName == Weaver.TargetRpcType.FullName) + { + ProcessTargetRpc(names, md, ca); + break; + } + + if (ca.AttributeType.FullName == Weaver.ClientRpcType.FullName) + { + ProcessClientRpc(names, md, ca); + break; + } + } + } + + // cmds + foreach (MethodDefinition md in commandInvocationFuncs) + { + netBehaviourSubclass.Methods.Add(md); + } + foreach (MethodDefinition md in commandCallFuncs) + { + netBehaviourSubclass.Methods.Add(md); + } + + // rpcs + foreach (MethodDefinition md in clientRpcInvocationFuncs) + { + netBehaviourSubclass.Methods.Add(md); + } + foreach (MethodDefinition md in targetRpcInvocationFuncs) + { + netBehaviourSubclass.Methods.Add(md); + } + foreach (MethodDefinition md in clientRpcCallFuncs) + { + netBehaviourSubclass.Methods.Add(md); + } + foreach (MethodDefinition md in targetRpcCallFuncs) + { + netBehaviourSubclass.Methods.Add(md); + } + } + + void ProcessClientRpc(HashSet names, MethodDefinition md, CustomAttribute ca) + { + if (!RpcProcessor.ProcessMethodsValidateRpc(md, ca)) + { + return; + } + + if (names.Contains(md.Name)) + { + Weaver.Error("Duplicate ClientRpc name [" + netBehaviourSubclass.FullName + ":" + md.Name + "]"); + return; + } + names.Add(md.Name); + clientRpcs.Add(md); + + MethodDefinition rpcFunc = RpcProcessor.ProcessRpcInvoke(netBehaviourSubclass, md); + if (rpcFunc != null) + { + clientRpcInvocationFuncs.Add(rpcFunc); + } + + MethodDefinition rpcCallFunc = RpcProcessor.ProcessRpcCall(netBehaviourSubclass, md, ca); + if (rpcCallFunc != null) + { + clientRpcCallFuncs.Add(rpcCallFunc); + Weaver.WeaveLists.replaceMethods[md.FullName] = rpcCallFunc; + } + } + + void ProcessTargetRpc(HashSet names, MethodDefinition md, CustomAttribute ca) + { + if (!TargetRpcProcessor.ProcessMethodsValidateTargetRpc(md, ca)) + return; + + if (names.Contains(md.Name)) + { + Weaver.Error("Duplicate Target Rpc name [" + netBehaviourSubclass.FullName + ":" + md.Name + "]"); + return; + } + names.Add(md.Name); + targetRpcs.Add(md); + + MethodDefinition rpcFunc = TargetRpcProcessor.ProcessTargetRpcInvoke(netBehaviourSubclass, md); + if (rpcFunc != null) + { + targetRpcInvocationFuncs.Add(rpcFunc); + } + + MethodDefinition rpcCallFunc = TargetRpcProcessor.ProcessTargetRpcCall(netBehaviourSubclass, md, ca); + if (rpcCallFunc != null) + { + targetRpcCallFuncs.Add(rpcCallFunc); + Weaver.WeaveLists.replaceMethods[md.FullName] = rpcCallFunc; + } + } + + void ProcessCommand(HashSet names, MethodDefinition md, CustomAttribute ca) + { + if (!CommandProcessor.ProcessMethodsValidateCommand(md, ca)) + return; + + if (names.Contains(md.Name)) + { + Weaver.Error("Duplicate Command name [" + netBehaviourSubclass.FullName + ":" + md.Name + "]"); + return; + } + + names.Add(md.Name); + commands.Add(md); + + MethodDefinition cmdFunc = CommandProcessor.ProcessCommandInvoke(netBehaviourSubclass, md); + if (cmdFunc != null) + { + commandInvocationFuncs.Add(cmdFunc); + } + + MethodDefinition cmdCallFunc = CommandProcessor.ProcessCommandCall(netBehaviourSubclass, md, ca); + if (cmdCallFunc != null) + { + commandCallFuncs.Add(cmdCallFunc); + Weaver.WeaveLists.replaceMethods[md.FullName] = cmdCallFunc; + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta new file mode 100644 index 0000000..67c27dc --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8118d606be3214e5d99943ec39530dd8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs new file mode 100644 index 0000000..b45e724 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs @@ -0,0 +1,356 @@ +using System; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class PropertySiteProcessor + { + public static void ProcessSitesModule(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); + Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.WeaveLists.generateContainerClass); + + foreach (MethodDefinition f in Weaver.WeaveLists.generatedReadFunctions) + { + Weaver.CurrentAssembly.MainModule.ImportReference(f); + } + + foreach (MethodDefinition f in Weaver.WeaveLists.generatedWriteFunctions) + { + Weaver.CurrentAssembly.MainModule.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(td, md); + } + + foreach (TypeDefinition nested in td.NestedTypes) + { + ProcessSiteClass(nested); + } + } + + static void ProcessSiteMethod(TypeDefinition td, 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("CallCmd") || + md.Name.StartsWith("InvokeCmd") || + md.Name.StartsWith("InvokeRpc") || + md.Name.StartsWith("InvokeSyn")) + return; + + if (md.Body != null && md.Body.Instructions != null) + { + // TODO move this to NetworkBehaviourProcessor + foreach (CustomAttribute attr in md.CustomAttributes) + { + switch (attr.Constructor.DeclaringType.ToString()) + { + case "Mirror.ServerAttribute": + InjectServerGuard(td, md, true); + break; + case "Mirror.ServerCallbackAttribute": + InjectServerGuard(td, md, false); + break; + case "Mirror.ClientAttribute": + InjectClientGuard(td, md, true); + break; + case "Mirror.ClientCallbackAttribute": + InjectClientGuard(td, md, false); + break; + } + } + + for (int iCount= 0; iCount < md.Body.Instructions.Count;) + { + Instruction instr = md.Body.Instructions[iCount]; + iCount += ProcessInstruction(md, instr, iCount); + } + } + } + + static void InjectServerGuard(TypeDefinition td, MethodDefinition md, bool logWarning) + { + if (!Weaver.IsNetworkBehaviour(td)) + { + Weaver.Error($"[Server] {md} must be declared in a NetworkBehaviour"); + return; + } + ILProcessor worker = md.Body.GetILProcessor(); + Instruction top = md.Body.Instructions[0]; + + worker.InsertBefore(top, worker.Create(OpCodes.Call, Weaver.NetworkServerGetActive)); + worker.InsertBefore(top, worker.Create(OpCodes.Brtrue, top)); + if (logWarning) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldstr, "[Server] function '" + md.FullName + "' called on client")); + worker.InsertBefore(top, worker.Create(OpCodes.Call, Weaver.logWarningReference)); + } + InjectGuardParameters(md, worker, top); + InjectGuardReturnValue(md, worker, top); + worker.InsertBefore(top, worker.Create(OpCodes.Ret)); + } + + static void InjectClientGuard(TypeDefinition td, MethodDefinition md, bool logWarning) + { + if (!Weaver.IsNetworkBehaviour(td)) + { + Weaver.Error($"[Client] {md} must be declared in a NetworkBehaviour"); + return; + } + ILProcessor worker = md.Body.GetILProcessor(); + Instruction top = md.Body.Instructions[0]; + + worker.InsertBefore(top, worker.Create(OpCodes.Call, Weaver.NetworkClientGetActive)); + worker.InsertBefore(top, worker.Create(OpCodes.Brtrue, top)); + if (logWarning) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldstr, "[Client] function '" + md.FullName + "' called on server")); + worker.InsertBefore(top, worker.Create(OpCodes.Call, Weaver.logWarningReference)); + } + + InjectGuardParameters(md, worker, top); + InjectGuardReturnValue(md, worker, top); + worker.InsertBefore(top, worker.Create(OpCodes.Ret)); + } + + // 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) + { + if (instr.Operand is MethodReference opMethod) + { + ProcessInstructionMethod(md, instr, opMethod, iCount); + } + } + + if (instr.OpCode == OpCodes.Stfld) + { + // this instruction sets the value of a field. cache the field reference. + if (instr.Operand is FieldDefinition opField) + { + ProcessInstructionSetterField(md, instr, opField); + } + } + + if (instr.OpCode == OpCodes.Ldfld) + { + // this instruction gets the value of a field. cache the field reference. + if (instr.Operand is FieldDefinition opField) + { + ProcessInstructionGetterField(md, instr, opField); + } + } + + if (instr.OpCode == OpCodes.Ldflda) + { + // loading a field by reference, watch out for initobj instruction + // see https://github.com/vis2k/Mirror/issues/696 + + if (instr.Operand is FieldDefinition opField) + { + return ProcessInstructionLoadAddress(md, instr, opField, 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) + { + //DLog(td, "ProcessInstructionMethod " + opMethod.Name); + if (opMethodRef.Name == "Invoke") + { + // 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 + bool found = false; + while (iCount > 0 && !found) + { + 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.Name, out MethodDefinition replacement)) + { + instr.Operand = replacement; + inst.OpCode = OpCodes.Nop; + found = true; + } + } + } + } + else + { + // should it be replaced? + // NOTE: original weaver compared .FullName, not just the MethodDefinition, + // that's why we use dict. + if (Weaver.WeaveLists.replaceMethods.TryGetValue(opMethodRef.FullName, out MethodDefinition replacement)) + { + //DLog(td, " replacing " + md.Name + ":" + i); + instr.Operand = replacement; + //DLog(td, " replaced " + md.Name + ":" + i); + } + } + } + + + // this is required to early-out from a function with "ref" or "out" parameters + static void InjectGuardParameters(MethodDefinition md, ILProcessor worker, Instruction top) + { + int offset = md.Resolve().IsStatic ? 0 : 1; + for (int index = 0; index < md.Parameters.Count; index++) + { + ParameterDefinition param = md.Parameters[index]; + if (param.IsOut) + { + TypeReference elementType = param.ParameterType.GetElementType(); + if (elementType.IsPrimitive) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldarg, index + offset)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldc_I4_0)); + worker.InsertBefore(top, worker.Create(OpCodes.Stind_I4)); + } + else + { + md.Body.Variables.Add(new VariableDefinition(elementType)); + md.Body.InitLocals = true; + + worker.InsertBefore(top, worker.Create(OpCodes.Ldarg, index + offset)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldloca_S, (byte)(md.Body.Variables.Count - 1))); + worker.InsertBefore(top, worker.Create(OpCodes.Initobj, elementType)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldloc, md.Body.Variables.Count - 1)); + worker.InsertBefore(top, worker.Create(OpCodes.Stobj, elementType)); + } + } + } + } + + // 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 != Weaver.voidType.FullName) + { + if (md.ReturnType.IsPrimitive) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldc_I4_0)); + } + else + { + md.Body.Variables.Add(new VariableDefinition(md.ReturnType)); + md.Body.InitLocals = true; + + worker.InsertBefore(top, worker.Create(OpCodes.Ldloca_S, (byte)(md.Body.Variables.Count - 1))); + worker.InsertBefore(top, worker.Create(OpCodes.Initobj, md.ReturnType)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldloc, md.Body.Variables.Count - 1)); + } + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs.meta new file mode 100644 index 0000000..e8c2500 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/PropertySiteProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d48f1ab125e9940a995603796bccc59e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs new file mode 100644 index 0000000..d87bf22 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs @@ -0,0 +1,98 @@ +using System; +using Mono.CecilX; +using UnityEditor.Compilation; +using System.Linq; +using System.Collections.Generic; +using System.IO; + +namespace Mirror.Weaver +{ + public static class ReaderWriterProcessor + { + // find all readers and writers and register them + public static void ProcessReadersAndWriters(AssemblyDefinition CurrentAssembly) + { + Readers.Init(); + Writers.Init(); + + foreach (Assembly unityAsm in CompilationPipeline.GetAssemblies()) + { + if (unityAsm.name != CurrentAssembly.Name.Name) + { + 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, CurrentAssembly); + } + + static void ProcessAssemblyClasses(AssemblyDefinition CurrentAssembly, AssemblyDefinition assembly) + { + 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); + } + } + } + + static void LoadWriters(AssemblyDefinition currentAssembly, TypeDefinition klass) + { + // register all the writers in this class. Skip the ones with wrong signature + foreach (MethodDefinition method in klass.Methods) + { + if (method.Parameters.Count != 2) + continue; + + if (method.Parameters[0].ParameterType.FullName != "Mirror.NetworkWriter") + continue; + + if (method.ReturnType.FullName != "System.Void") + continue; + + if (method.GetCustomAttribute("System.Runtime.CompilerServices.ExtensionAttribute") == null) + continue; + + TypeReference dataType = method.Parameters[1].ParameterType; + Writers.Register(dataType, currentAssembly.MainModule.ImportReference(method)); + } + } + + static void LoadReaders(AssemblyDefinition currentAssembly, TypeDefinition klass) + { + // register all the reader in this class. Skip the ones with wrong signature + foreach (MethodDefinition method in klass.Methods) + { + if (method.Parameters.Count != 1) + continue; + + if (method.Parameters[0].ParameterType.FullName != "Mirror.NetworkReader") + continue; + + if (method.ReturnType.FullName == "System.Void") + continue; + + if (method.GetCustomAttribute("System.Runtime.CompilerServices.ExtensionAttribute") == null) + continue; + + Readers.Register(method.ReturnType, currentAssembly.MainModule.ImportReference(method)); + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta new file mode 100644 index 0000000..c14d6fa --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f3263602f0a374ecd8d08588b1fc2f76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/RpcProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/RpcProcessor.cs new file mode 100644 index 0000000..947742e --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/RpcProcessor.cs @@ -0,0 +1,110 @@ +// all the [Rpc] code from NetworkBehaviourProcessor in one place +using Mono.CecilX; +using Mono.CecilX.Cil; +namespace Mirror.Weaver +{ + public static class RpcProcessor + { + public const string RpcPrefix = "InvokeRpc"; + + public static MethodDefinition ProcessRpcInvoke(TypeDefinition td, MethodDefinition md) + { + MethodDefinition rpc = new MethodDefinition( + RpcPrefix + md.Name, + MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig, + Weaver.voidType); + + ILProcessor rpcWorker = rpc.Body.GetILProcessor(); + Instruction label = rpcWorker.Create(OpCodes.Nop); + + NetworkBehaviourProcessor.WriteClientActiveCheck(rpcWorker, md.Name, label, "RPC"); + + // setup for reader + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Castclass, td)); + + if (!NetworkBehaviourProcessor.ProcessNetworkReaderParameters(md, rpcWorker, false)) + return null; + + // invoke actual command function + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, md)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ret)); + + NetworkBehaviourProcessor.AddInvokeParameters(rpc.Parameters); + + return rpc; + } + + /* generates code like: + public void CallRpcTest (int param) + { + NetworkWriter writer = new NetworkWriter (); + writer.WritePackedUInt32((uint)param); + base.SendRPCInternal(typeof(class),"RpcTest", writer, 0); + } + */ + public static MethodDefinition ProcessRpcCall(TypeDefinition td, MethodDefinition md, CustomAttribute ca) + { + MethodDefinition rpc = new MethodDefinition("Call" + md.Name, MethodAttributes.Public | + MethodAttributes.HideBySig, + Weaver.voidType); + + // add paramters + foreach (ParameterDefinition pd in md.Parameters) + { + rpc.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); + } + + ILProcessor rpcWorker = rpc.Body.GetILProcessor(); + + NetworkBehaviourProcessor.WriteSetupLocals(rpcWorker); + + NetworkBehaviourProcessor.WriteCreateWriter(rpcWorker); + + // write all the arguments that the user passed to the Rpc call + if (!NetworkBehaviourProcessor.WriteArguments(rpcWorker, md, false)) + return null; + + string rpcName = md.Name; + int index = rpcName.IndexOf(RpcPrefix); + if (index > -1) + { + rpcName = rpcName.Substring(RpcPrefix.Length); + } + + // invoke SendInternal and return + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); // this + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldtoken, td)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Call, Weaver.getTypeFromHandleReference)); // invokerClass + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldstr, rpcName)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldloc_0)); // writer + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldc_I4, NetworkBehaviourProcessor.GetChannelId(ca))); + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, Weaver.sendRpcInternal)); + + NetworkBehaviourProcessor.WriteRecycleWriter(rpcWorker); + + rpcWorker.Append(rpcWorker.Create(OpCodes.Ret)); + + return rpc; + } + + public static bool ProcessMethodsValidateRpc(MethodDefinition md, CustomAttribute ca) + { + if (!md.Name.StartsWith("Rpc")) + { + Weaver.Error($"{md} must start with Rpc. Consider renaming it to Rpc{md.Name}"); + return false; + } + + if (md.IsStatic) + { + Weaver.Error($"{md} must not be static"); + return false; + } + + // validate + return NetworkBehaviourProcessor.ProcessMethodsValidateFunction(md) && + NetworkBehaviourProcessor.ProcessMethodsValidateParameters(md, ca); + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta new file mode 100644 index 0000000..22375ba --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a3cb7051ff41947e59bba58bdd2b73fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs new file mode 100644 index 0000000..a095967 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs @@ -0,0 +1,19 @@ +// this class generates OnSerialize/OnDeserialize for SyncLists +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + static class SyncDictionaryProcessor + { + /// + /// Generates serialization methods for synclists + /// + /// The synclist class + public static void Process(TypeDefinition td) + { + SyncObjectProcessor.GenerateSerialization(td, 0, "SerializeKey", "DeserializeKey"); + SyncObjectProcessor.GenerateSerialization(td, 1, "SerializeItem", "DeserializeItem"); + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs.meta new file mode 100644 index 0000000..0a7c2aa --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncDictionaryProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 29e4a45f69822462ab0b15adda962a29 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs new file mode 100644 index 0000000..3a4e36f --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs @@ -0,0 +1,152 @@ +// all the SyncEvent code from NetworkBehaviourProcessor in one place +using System.Collections.Generic; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + 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($"{td} not found. Did you declare the event?"); + return null; + } + + MethodDefinition cmd = new MethodDefinition("InvokeSyncEvent" + ed.Name, MethodAttributes.Family | + MethodAttributes.Static | + MethodAttributes.HideBySig, + Weaver.voidType); + + ILProcessor cmdWorker = cmd.Body.GetILProcessor(); + Instruction label1 = cmdWorker.Create(OpCodes.Nop); + Instruction label2 = cmdWorker.Create(OpCodes.Nop); + + NetworkBehaviourProcessor.WriteClientActiveCheck(cmdWorker, ed.Name, label1, "Event"); + + // null event check + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Castclass, td)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldfld, eventField)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Brtrue, label2)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + cmdWorker.Append(label2); + + // setup reader + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldarg_0)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Castclass, td)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ldfld, eventField)); + + // read the event arguments + MethodReference invoke = Resolvers.ResolveMethod(eventField.FieldType, Weaver.CurrentAssembly, "Invoke"); + if (!NetworkBehaviourProcessor.ProcessNetworkReaderParameters(invoke.Resolve(), cmdWorker, false)) + return null; + + // invoke actual event delegate function + cmdWorker.Append(cmdWorker.Create(OpCodes.Callvirt, invoke)); + cmdWorker.Append(cmdWorker.Create(OpCodes.Ret)); + + NetworkBehaviourProcessor.AddInvokeParameters(cmd.Parameters); + + return cmd; + } + + public static MethodDefinition ProcessEventCall(TypeDefinition td, EventDefinition ed, CustomAttribute ca) + { + MethodReference invoke = Resolvers.ResolveMethod(ed.EventType, Weaver.CurrentAssembly, "Invoke"); + MethodDefinition evt = new MethodDefinition("Call" + ed.Name, MethodAttributes.Public | + MethodAttributes.HideBySig, + Weaver.voidType); + // add paramters + foreach (ParameterDefinition pd in invoke.Parameters) + { + evt.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); + } + + ILProcessor evtWorker = evt.Body.GetILProcessor(); + Instruction label = evtWorker.Create(OpCodes.Nop); + + NetworkBehaviourProcessor.WriteSetupLocals(evtWorker); + + NetworkBehaviourProcessor.WriteServerActiveCheck(evtWorker, ed.Name, label, "Event"); + + NetworkBehaviourProcessor.WriteCreateWriter(evtWorker); + + // write all the arguments that the user passed to the syncevent + if (!NetworkBehaviourProcessor.WriteArguments(evtWorker, invoke.Resolve(), false)) + return null; + + // invoke interal send and return + evtWorker.Append(evtWorker.Create(OpCodes.Ldarg_0)); // this + evtWorker.Append(evtWorker.Create(OpCodes.Ldtoken, td)); + evtWorker.Append(evtWorker.Create(OpCodes.Call, Weaver.getTypeFromHandleReference)); // invokerClass + evtWorker.Append(evtWorker.Create(OpCodes.Ldstr, ed.Name)); + evtWorker.Append(evtWorker.Create(OpCodes.Ldloc_0)); // writer + evtWorker.Append(evtWorker.Create(OpCodes.Ldc_I4, NetworkBehaviourProcessor.GetChannelId(ca))); + evtWorker.Append(evtWorker.Create(OpCodes.Call, Weaver.sendEventInternal)); + + NetworkBehaviourProcessor.WriteRecycleWriter(evtWorker); + + evtWorker.Append(evtWorker.Create(OpCodes.Ret)); + + return evt; + } + + public static void ProcessEvents(TypeDefinition td, List events, List eventInvocationFuncs) + { + // find events + foreach (EventDefinition ed in td.Events) + { + foreach (CustomAttribute ca in ed.CustomAttributes) + { + if (ca.AttributeType.FullName == Weaver.SyncEventType.FullName) + { + if (!ed.Name.StartsWith("Event")) + { + Weaver.Error($"{ed} must start with Event. Consider renaming it to Event{ed.Name}"); + return; + } + + if (ed.EventType.Resolve().HasGenericParameters) + { + Weaver.Error($"{ed} must not have generic parameters. Consider creating a new class that inherits from {ed.EventType} instead"); + 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, ca); + td.Methods.Add(eventCallFunc); + + Weaver.WeaveLists.replaceEvents[ed.Name] = eventCallFunc; // original weaver compares .Name, not EventDefinition. + + Weaver.DLog(td, " Event: " + ed.Name); + break; + } + } + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs.meta new file mode 100644 index 0000000..81b9576 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncEventProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5d8b25543a624384944b599e5a832a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs new file mode 100644 index 0000000..20db50b --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs @@ -0,0 +1,5 @@ +// 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/Packages/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs.meta new file mode 100644 index 0000000..d3f5278 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListInitializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 97068e5d8cc14490b85933feb119d827 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs new file mode 100644 index 0000000..0da1746 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs @@ -0,0 +1,18 @@ +// this class generates OnSerialize/OnDeserialize for SyncLists +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + static class SyncListProcessor + { + /// + /// Generates serialization methods for synclists + /// + /// The synclist class + public static void Process(TypeDefinition td) + { + SyncObjectProcessor.GenerateSerialization(td, 0, "SerializeItem", "DeserializeItem"); + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs.meta new file mode 100644 index 0000000..b73b047 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f3445268e45d437fac325837aff3246 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs new file mode 100644 index 0000000..20db50b --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs @@ -0,0 +1,5 @@ +// 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/Packages/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs.meta new file mode 100644 index 0000000..8f234cd --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncListStructProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28fb192f6a9bc1247b90aa4710f6d34f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs new file mode 100644 index 0000000..14e27f6 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs @@ -0,0 +1,89 @@ +// SyncObject code +using System; +using System.Linq; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class SyncObjectInitializer + { + public static void GenerateSyncObjectInitializer(ILProcessor methodWorker, FieldDefinition fd) + { + // call syncobject constructor + GenerateSyncObjectInstanceInitializer(methodWorker, fd); + + // register syncobject in network behaviour + GenerateSyncObjectRegistration(methodWorker, fd); + } + + // generates 'syncListInt = new SyncListInt()' if user didn't do that yet + static void GenerateSyncObjectInstanceInitializer(ILProcessor ctorWorker, FieldDefinition fd) + { + // check the ctor's instructions for an Stfld op-code for this specific sync list field. + foreach (Instruction ins in ctorWorker.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; + MethodReference objectConstructor; + try + { + objectConstructor = Weaver.CurrentAssembly.MainModule.ImportReference(fd.FieldType.Resolve().Methods.First(x => x.Name == ".ctor" && !x.HasParameters)); + } + catch (Exception) + { + Weaver.Error($"{fd} does not have a default constructor"); + return; + } + + ctorWorker.Append(ctorWorker.Create(OpCodes.Ldarg_0)); + ctorWorker.Append(ctorWorker.Create(OpCodes.Newobj, objectConstructor)); + ctorWorker.Append(ctorWorker.Create(OpCodes.Stfld, fd)); + } + + public static bool ImplementsSyncObject(TypeReference typeRef) + { + try + { + // value types cant inherit from SyncObject + if (typeRef.IsValueType) + { + return false; + } + + return typeRef.Resolve().ImplementsInterface(Weaver.SyncObjectType); + } + catch + { + // sometimes this will fail if we reference a weird library that can't be resolved, so we just swallow that exception and return false + } + + return false; + } + + /* + // generates code like: + this.InitSyncObject(m_sizes); + */ + static void GenerateSyncObjectRegistration(ILProcessor methodWorker, FieldDefinition fd) + { + methodWorker.Append(methodWorker.Create(OpCodes.Ldarg_0)); + methodWorker.Append(methodWorker.Create(OpCodes.Ldarg_0)); + methodWorker.Append(methodWorker.Create(OpCodes.Ldfld, fd)); + + methodWorker.Append(methodWorker.Create(OpCodes.Call, Weaver.InitSyncObjectReference)); + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta new file mode 100644 index 0000000..22f976e --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d02219b00b3674e59a2151f41e791688 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs new file mode 100644 index 0000000..9eb7494 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs @@ -0,0 +1,123 @@ +using System; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class SyncObjectProcessor + { + /// + /// Generates the serialization and deserialization methods for a specified generic argument + /// + /// The type of the class that needs serialization methods + /// Which generic argument to serialize, 0 is the first one + /// The name of the serialize method + /// The name of the deserialize method + public static void GenerateSerialization(TypeDefinition td, int genericArgument, string serializeMethod, string deserializeMethod) + { + // find item type + GenericInstanceType gt = (GenericInstanceType)td.BaseType; + if (gt.GenericArguments.Count <= genericArgument) + { + Weaver.Error($"{td} should have {genericArgument} generic arguments"); + return; + } + TypeReference itemType = Weaver.CurrentAssembly.MainModule.ImportReference(gt.GenericArguments[genericArgument]); + + Weaver.DLog(td, "SyncObjectProcessor Start item:" + itemType.FullName); + + MethodReference writeItemFunc = GenerateSerialization(serializeMethod, td, itemType); + if (Weaver.WeavingFailed) + { + return; + } + + MethodReference readItemFunc = GenerateDeserialization(deserializeMethod, td, itemType); + + if (readItemFunc == null || writeItemFunc == null) + return; + + Weaver.DLog(td, "SyncObjectProcessor Done"); + } + + // serialization of individual element + static MethodReference GenerateSerialization(string methodName, TypeDefinition td, TypeReference itemType) + { + Weaver.DLog(td, " GenerateSerialization"); + foreach (MethodDefinition m in td.Methods) + { + if (m.Name == methodName) + return m; + } + + MethodDefinition serializeFunc = new MethodDefinition(methodName, MethodAttributes.Public | + MethodAttributes.Virtual | + MethodAttributes.Public | + MethodAttributes.HideBySig, + Weaver.voidType); + + serializeFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); + serializeFunc.Parameters.Add(new ParameterDefinition("item", ParameterAttributes.None, itemType)); + ILProcessor serWorker = serializeFunc.Body.GetILProcessor(); + + if (itemType.IsGenericInstance) + { + Weaver.Error($"{td} cannot have generic elements {itemType}"); + return null; + } + + MethodReference writeFunc = Writers.GetWriteFunc(itemType); + if (writeFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); + serWorker.Append(serWorker.Create(OpCodes.Call, writeFunc)); + } + else + { + Weaver.Error($"{td} cannot have item of type {itemType}. Use a type supported by mirror instead"); + return null; + } + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + td.Methods.Add(serializeFunc); + return serializeFunc; + } + + static MethodReference GenerateDeserialization(string methodName, TypeDefinition td, TypeReference itemType) + { + Weaver.DLog(td, " GenerateDeserialization"); + foreach (MethodDefinition m in td.Methods) + { + if (m.Name == methodName) + return m; + } + + 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(Weaver.NetworkReaderType))); + + ILProcessor serWorker = deserializeFunction.Body.GetILProcessor(); + + MethodReference readerFunc = Readers.GetReadFunc(itemType); + if (readerFunc != null) + { + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, readerFunc)); + serWorker.Append(serWorker.Create(OpCodes.Ret)); + } + else + { + Weaver.Error($"{td} cannot have item of type {itemType}. Use a type supported by mirror instead"); + return null; + } + + td.Methods.Add(deserializeFunction); + return deserializeFunction; + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta new file mode 100644 index 0000000..0efe434 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 78f71efc83cde4917b7d21efa90bcc9a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs new file mode 100644 index 0000000..86be11c --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs @@ -0,0 +1,335 @@ +// all the [SyncVar] code from NetworkBehaviourProcessor in one place +using System.Collections.Generic; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class SyncVarProcessor + { + const int SyncVarLimit = 64; // ulong = 64 bytes + + // returns false for error, not for no-hook-exists + public static bool CheckForHookFunction(TypeDefinition td, FieldDefinition syncVar, out MethodDefinition foundMethod) + { + foundMethod = null; + foreach (CustomAttribute ca in syncVar.CustomAttributes) + { + if (ca.AttributeType.FullName == Weaver.SyncVarType.FullName) + { + foreach (CustomAttributeNamedArgument customField in ca.Fields) + { + if (customField.Name == "hook") + { + string hookFunctionName = customField.Argument.Value as string; + + foreach (MethodDefinition m in td.Methods) + { + if (m.Name == hookFunctionName) + { + if (m.Parameters.Count == 1) + { + if (m.Parameters[0].ParameterType != syncVar.FieldType) + { + Weaver.Error($"{m} should have signature:\npublic void {hookFunctionName}({syncVar.FieldType} value) {{ }}"); + return false; + } + foundMethod = m; + return true; + } + Weaver.Error($"{m} should have signature:\npublic void {hookFunctionName}({syncVar.FieldType} value) {{ }}"); + return false; + } + } + Weaver.Error($"No hook implementation found for {syncVar}. Add this method to your class:\npublic void {hookFunctionName}({syncVar.FieldType} value) {{ }}" ); + return false; + } + } + } + } + return true; + } + + 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 getWorker = get.Body.GetILProcessor(); + + // [SyncVar] GameObject? + if (fd.FieldType.FullName == Weaver.gameObjectType.FullName) + { + // return this.GetSyncVarGameObject(ref field, uint netId); + getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); // this. + getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); + getWorker.Append(getWorker.Create(OpCodes.Ldfld, netFieldId)); + getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); + getWorker.Append(getWorker.Create(OpCodes.Ldflda, fd)); + getWorker.Append(getWorker.Create(OpCodes.Call, Weaver.getSyncVarGameObjectReference)); + getWorker.Append(getWorker.Create(OpCodes.Ret)); + } + // [SyncVar] NetworkIdentity? + else if (fd.FieldType.FullName == Weaver.NetworkIdentityType.FullName) + { + // return this.GetSyncVarNetworkIdentity(ref field, uint netId); + getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); // this. + getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); + getWorker.Append(getWorker.Create(OpCodes.Ldfld, netFieldId)); + getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); + getWorker.Append(getWorker.Create(OpCodes.Ldflda, fd)); + getWorker.Append(getWorker.Create(OpCodes.Call, Weaver.getSyncVarNetworkIdentityReference)); + getWorker.Append(getWorker.Create(OpCodes.Ret)); + } + // [SyncVar] int, string, etc. + else + { + getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); + getWorker.Append(getWorker.Create(OpCodes.Ldfld, fd)); + getWorker.Append(getWorker.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, + Weaver.voidType); + + ILProcessor setWorker = set.Body.GetILProcessor(); + + CheckForHookFunction(td, fd, out MethodDefinition hookFunctionMethod); + + if (hookFunctionMethod != null) + { + //if (NetworkServer.localClientActive && !getSyncVarHookGuard(dirtyBit)) + Instruction label = setWorker.Create(OpCodes.Nop); + setWorker.Append(setWorker.Create(OpCodes.Call, Weaver.NetworkServerGetLocalClientActive)); + setWorker.Append(setWorker.Create(OpCodes.Brfalse, label)); + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldc_I8, dirtyBit)); + setWorker.Append(setWorker.Create(OpCodes.Call, Weaver.getSyncVarHookGuard)); + setWorker.Append(setWorker.Create(OpCodes.Brtrue, label)); + + // setSyncVarHookGuard(dirtyBit, true); + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldc_I8, dirtyBit)); + setWorker.Append(setWorker.Create(OpCodes.Ldc_I4_1)); + setWorker.Append(setWorker.Create(OpCodes.Call, Weaver.setSyncVarHookGuard)); + + // call hook + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldarg_1)); + setWorker.Append(setWorker.Create(OpCodes.Call, hookFunctionMethod)); + + // setSyncVarHookGuard(dirtyBit, false); + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldc_I8, dirtyBit)); + setWorker.Append(setWorker.Create(OpCodes.Ldc_I4_0)); + setWorker.Append(setWorker.Create(OpCodes.Call, Weaver.setSyncVarHookGuard)); + + setWorker.Append(label); + } + + // this + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + + // new value to set + setWorker.Append(setWorker.Create(OpCodes.Ldarg_1)); + + // reference to field to set + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldflda, fd)); + + // dirty bit + setWorker.Append(setWorker.Create(OpCodes.Ldc_I8, dirtyBit)); // 8 byte integer aka long + + + if (fd.FieldType.FullName == Weaver.gameObjectType.FullName) + { + // reference to netId Field to set + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldflda, netFieldId)); + + setWorker.Append(setWorker.Create(OpCodes.Call, Weaver.setSyncVarGameObjectReference)); + } + else if (fd.FieldType.FullName == Weaver.NetworkIdentityType.FullName) + { + // reference to netId Field to set + setWorker.Append(setWorker.Create(OpCodes.Ldarg_0)); + setWorker.Append(setWorker.Create(OpCodes.Ldflda, netFieldId)); + + setWorker.Append(setWorker.Create(OpCodes.Call, Weaver.setSyncVarNetworkIdentityReference)); + } + else + { + // make generic version of SetSyncVar with field type + GenericInstanceMethod gm = new GenericInstanceMethod(Weaver.setSyncVarReference); + gm.GenericArguments.Add(fd.FieldType); + + // invoke SetSyncVar + setWorker.Append(setWorker.Create(OpCodes.Call, gm)); + } + + setWorker.Append(setWorker.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 + " " + Weaver.gameObjectType); + + // GameObject/NetworkIdentity SyncVars have a new field for netId + FieldDefinition netIdField = null; + if (fd.FieldType.FullName == Weaver.gameObjectType.FullName || + fd.FieldType.FullName == Weaver.NetworkIdentityType.FullName) + { + netIdField = new FieldDefinition("___" + fd.Name + "NetId", + FieldAttributes.Private, + Weaver.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 == Weaver.gameObjectType.FullName || + fd.FieldType.FullName == Weaver.NetworkIdentityType.FullName) + { + Weaver.WeaveLists.replacementGetterProperties[fd] = get; + } + } + + public static void ProcessSyncVars(TypeDefinition td, List syncVars, List syncObjects, Dictionary syncVarNetIds) + { + int numSyncVars = 0; + + // 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); + + syncVarNetIds.Clear(); + + // find syncvars + foreach (FieldDefinition fd in td.Fields) + { + foreach (CustomAttribute ca in fd.CustomAttributes) + { + if (ca.AttributeType.FullName == Weaver.SyncVarType.FullName) + { + TypeDefinition resolvedField = fd.FieldType.Resolve(); + + if (resolvedField.IsDerivedFrom(Weaver.NetworkBehaviourType)) + { + Weaver.Error($"{fd} has invalid type. SyncVars cannot be NetworkBehaviours"); + return; + } + + if (resolvedField.IsDerivedFrom(Weaver.ScriptableObjectType)) + { + Weaver.Error($"{fd} has invalid type. SyncVars cannot be scriptable objects"); + return; + } + + if ((fd.Attributes & FieldAttributes.Static) != 0) + { + Weaver.Error($"{fd} cannot be static"); + return; + } + + if (resolvedField.HasGenericParameters) + { + Weaver.Error($"{fd} has invalid type. SyncVars cannot have generic parameters"); + return; + } + + if (resolvedField.IsInterface) + { + Weaver.Error($"{fd} has invalid type. Use a concrete type instead of interface {fd.FieldType}"); + return; + } + + if (fd.FieldType.IsArray) + { + Weaver.Error($"{fd} has invalid type. Use SyncLists instead of arrays"); + return; + } + + if (SyncObjectInitializer.ImplementsSyncObject(fd.FieldType)) + { + Log.Warning($"{fd} has [SyncVar] attribute. SyncLists should not be marked with SyncVar"); + break; + } + + syncVars.Add(fd); + + ProcessSyncVar(td, fd, syncVarNetIds, 1L << dirtyBitCounter); + dirtyBitCounter += 1; + numSyncVars += 1; + + if (dirtyBitCounter == SyncVarLimit) + { + Weaver.Error($"{td} has too many SyncVars. Consider refactoring your class into multiple components"); + return; + } + break; + } + } + + if (fd.FieldType.Resolve().ImplementsInterface(Weaver.SyncObjectType)) + { + if (fd.IsStatic) + { + Weaver.Error($"{fd} cannot be static"); + return; + } + + syncObjects.Add(fd); + } + } + + // add all the new SyncVar __netId fields + foreach (FieldDefinition fd in syncVarNetIds.Values) + { + td.Fields.Add(fd); + } + + Weaver.SetNumSyncVars(td.FullName, numSyncVars); + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs.meta new file mode 100644 index 0000000..982f768 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/SyncVarProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f52c39bddd95d42b88f9cd554dfd9198 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs b/Assets/Packages/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs new file mode 100644 index 0000000..e20b2c9 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs @@ -0,0 +1,151 @@ +// all the [TargetRpc] code from NetworkBehaviourProcessor in one place +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class TargetRpcProcessor + { + const string TargetRpcPrefix = "InvokeTargetRpc"; + + // 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 == Weaver.NetworkConnectionType.FullName; + } + + public static MethodDefinition ProcessTargetRpcInvoke(TypeDefinition td, MethodDefinition md) + { + MethodDefinition rpc = new MethodDefinition(RpcProcessor.RpcPrefix + md.Name, MethodAttributes.Family | + MethodAttributes.Static | + MethodAttributes.HideBySig, + Weaver.voidType); + + ILProcessor rpcWorker = rpc.Body.GetILProcessor(); + Instruction label = rpcWorker.Create(OpCodes.Nop); + + NetworkBehaviourProcessor.WriteClientActiveCheck(rpcWorker, md.Name, label, "TargetRPC"); + + // setup for reader + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Castclass, td)); + + // NetworkConnection parameter is optional + bool hasNetworkConnection = HasNetworkConnectionParameter(md); + if (hasNetworkConnection) + { + //ClientScene.readyconnection + rpcWorker.Append(rpcWorker.Create(OpCodes.Call, Weaver.ReadyConnectionReference)); + } + + // process reader parameters and skip first one if first one is NetworkConnection + if (!NetworkBehaviourProcessor.ProcessNetworkReaderParameters(md, rpcWorker, hasNetworkConnection)) + return null; + + // invoke actual command function + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, md)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ret)); + + NetworkBehaviourProcessor.AddInvokeParameters(rpc.Parameters); + + return rpc; + } + + /* generates code like: + public void CallTargetTest (NetworkConnection conn, int param) + { + NetworkWriter writer = new NetworkWriter (); + writer.WritePackedUInt32 ((uint)param); + base.SendTargetRPCInternal (conn, typeof(class), "TargetTest", val); + } + + or if optional: + public void CallTargetTest (int param) + { + NetworkWriter writer = new NetworkWriter (); + writer.WritePackedUInt32 ((uint)param); + base.SendTargetRPCInternal (null, typeof(class), "TargetTest", val); + } + */ + public static MethodDefinition ProcessTargetRpcCall(TypeDefinition td, MethodDefinition md, CustomAttribute ca) + { + MethodDefinition rpc = new MethodDefinition("Call" + md.Name, MethodAttributes.Public | + MethodAttributes.HideBySig, + Weaver.voidType); + + // add parameters + foreach (ParameterDefinition pd in md.Parameters) + { + rpc.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); + } + + ILProcessor rpcWorker = rpc.Body.GetILProcessor(); + + NetworkBehaviourProcessor.WriteSetupLocals(rpcWorker); + + NetworkBehaviourProcessor.WriteCreateWriter(rpcWorker); + + // NetworkConnection parameter is optional + bool hasNetworkConnection = HasNetworkConnectionParameter(md); + + // write all the arguments that the user passed to the TargetRpc call + // (skip first one if first one is NetworkConnection) + if (!NetworkBehaviourProcessor.WriteArguments(rpcWorker, md, hasNetworkConnection)) + return null; + + string rpcName = md.Name; + int index = rpcName.IndexOf(TargetRpcPrefix); + if (index > -1) + { + rpcName = rpcName.Substring(TargetRpcPrefix.Length); + } + + // invoke SendInternal and return + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_0)); // this + if (HasNetworkConnectionParameter(md)) + { + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldarg_1)); // connection + } + else + { + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldnull)); // null + } + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldtoken, td)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Call, Weaver.getTypeFromHandleReference)); // invokerClass + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldstr, rpcName)); + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldloc_0)); // writer + rpcWorker.Append(rpcWorker.Create(OpCodes.Ldc_I4, NetworkBehaviourProcessor.GetChannelId(ca))); + rpcWorker.Append(rpcWorker.Create(OpCodes.Callvirt, Weaver.sendTargetRpcInternal)); + + NetworkBehaviourProcessor.WriteRecycleWriter(rpcWorker); + + rpcWorker.Append(rpcWorker.Create(OpCodes.Ret)); + + return rpc; + } + + public static bool ProcessMethodsValidateTargetRpc(MethodDefinition md, CustomAttribute ca) + { + if (!md.Name.StartsWith("Target")) + { + Weaver.Error($"{md} must start with Target. Consider renaming it to Target{md.Name}"); + return false; + } + + if (md.IsStatic) + { + Weaver.Error($"{md} must not be static"); + return false; + } + + if (!NetworkBehaviourProcessor.ProcessMethodsValidateFunction(md)) + { + return false; + } + + // validate + return NetworkBehaviourProcessor.ProcessMethodsValidateParameters(md, ca); + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta new file mode 100644 index 0000000..0ff7cc5 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb3ce6c6f3f2942ae88178b86f5a8282 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Program.cs b/Assets/Packages/Mirror/Editor/Weaver/Program.cs new file mode 100644 index 0000000..62163d2 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Program.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace Mirror.Weaver +{ + public static class Log + { + public static Action WarningMethod; + public static Action ErrorMethod; + + public static void Warning(string msg) + { + WarningMethod("Mirror.Weaver warning: " + msg); + } + + public static void Error(string msg) + { + ErrorMethod("Mirror.Weaver error: " + msg); + } + } + + public static class Program + { + public static bool Process(string unityEngine, string netDLL, string outputDirectory, string[] assemblies, string[] extraAssemblyPaths, Action printWarning, Action printError) + { + CheckDLLPath(unityEngine); + CheckDLLPath(netDLL); + CheckOutputDirectory(outputDirectory); + CheckAssemblies(assemblies); + Log.WarningMethod = printWarning; + Log.ErrorMethod = printError; + return Weaver.WeaveAssemblies(assemblies, extraAssemblyPaths, outputDirectory, unityEngine, netDLL); + } + + 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 (outputDir != null && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Program.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Program.cs.meta new file mode 100644 index 0000000..3f62978 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Program.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2a21c60c40a4c4d679c2b71a7c40882e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Readers.cs b/Assets/Packages/Mirror/Editor/Weaver/Readers.cs new file mode 100644 index 0000000..a50798d --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Readers.cs @@ -0,0 +1,371 @@ +using System.Collections.Generic; +using Mono.CecilX; +using Mono.CecilX.Cil; +using Mono.CecilX.Rocks; + + +namespace Mirror.Weaver +{ + public static class Readers + { + const int MaxRecursionCount = 128; + static Dictionary readFuncs; + + public static void Init() + { + readFuncs = new Dictionary(); + } + + internal static void Register(TypeReference dataType, MethodReference methodReference) + { + readFuncs[dataType.FullName] = methodReference; + } + + public static MethodReference GetReadFunc(TypeReference variable, int recursionCount = 0) + { + if (readFuncs.TryGetValue(variable.FullName, out MethodReference foundFunc)) + { + return foundFunc; + } + + TypeDefinition td = variable.Resolve(); + if (td == null) + { + Weaver.Error($"{variable} is not a supported type"); + return null; + } + + if (variable.IsByReference) + { + // error?? + Weaver.Error($"{variable} is not a supported reference type"); + return null; + } + + MethodDefinition newReaderFunc; + + if (variable.IsArray) + { + newReaderFunc = GenerateArrayReadFunc(variable, recursionCount); + } + else if (td.IsEnum) + { + return GetReadFunc(td.GetEnumUnderlyingType(), recursionCount); + } + else if (variable.FullName.StartsWith("System.ArraySegment`1", System.StringComparison.Ordinal)) + { + newReaderFunc = GenerateArraySegmentReadFunc(variable, recursionCount); + } + else + { + newReaderFunc = GenerateStructReadFunction(variable, recursionCount); + } + + if (newReaderFunc == null) + { + Weaver.Error($"{variable} is not a supported type"); + return null; + } + RegisterReadFunc(variable.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); + } + + static MethodDefinition GenerateArrayReadFunc(TypeReference variable, int recursionCount) + { + if (!variable.IsArrayType()) + { + Weaver.Error($"{variable} is an unsupported type. Jagged and multidimensional arrays are not supported"); + return null; + } + + TypeReference elementType = variable.GetElementType(); + MethodReference elementReadFunc = GetReadFunc(elementType, recursionCount + 1); + if (elementReadFunc == null) + { + return null; + } + + string functionName = "_ReadArray" + variable.GetElementType().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); + + readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkReaderType))); + + readerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); + readerFunc.Body.Variables.Add(new VariableDefinition(variable)); + readerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); + readerFunc.Body.InitLocals = true; + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + // int length = reader.ReadPackedInt32(); + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Call, GetReadFunc(Weaver.int32Type))); + worker.Append(worker.Create(OpCodes.Stloc_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); + + + // 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)); + return readerFunc; + } + + static MethodDefinition GenerateArraySegmentReadFunc(TypeReference variable, int recursionCount) + { + GenericInstanceType genericInstance = (GenericInstanceType)variable; + TypeReference elementType = genericInstance.GenericArguments[0]; + + MethodReference elementReadFunc = GetReadFunc(elementType, recursionCount + 1); + if (elementReadFunc == null) + { + return null; + } + + string functionName = "_ReadArraySegment_" + variable.GetElementType().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); + + readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkReaderType))); + + // int lengh + readerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); + // T[] array + readerFunc.Body.Variables.Add(new VariableDefinition(elementType.MakeArrayType())); + // int i; + readerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); + readerFunc.Body.InitLocals = true; + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + // int length = reader.ReadPackedInt32(); + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Call, GetReadFunc(Weaver.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, Weaver.ArraySegmentConstructorReference.MakeHostInstanceGeneric(genericInstance))); + worker.Append(worker.Create(OpCodes.Ret)); + return readerFunc; + } + + static MethodDefinition GenerateStructReadFunction(TypeReference variable, int recursionCount) + { + if (recursionCount > MaxRecursionCount) + { + Weaver.Error($"{variable} can't be deserialized because it references itself"); + return null; + } + + if (!Weaver.IsValidTypeToGenerate(variable.Resolve())) + { + 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); + + // 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(Weaver.NetworkReaderType))); + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + if (variable.IsValueType) + { + // structs are created with Initobj + worker.Append(worker.Create(OpCodes.Ldloca, 0)); + worker.Append(worker.Create(OpCodes.Initobj, variable)); + } + else + { + // classes are created with their constructor + + MethodDefinition ctor = Resolvers.ResolveDefaultPublicCtor(variable); + if (ctor == null) + { + Weaver.Error($"{variable} can't be deserialized bcause i has no default constructor"); + return null; + } + + worker.Append(worker.Create(OpCodes.Newobj, ctor)); + worker.Append(worker.Create(OpCodes.Stloc_0)); + } + + uint fields = 0; + foreach (FieldDefinition field in variable.Resolve().Fields) + { + if (field.IsStatic || field.IsPrivate) + continue; + + // 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); + if (readFunc != null) + { + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Call, readFunc)); + } + else + { + Weaver.Error($"{field} has an unsupported type"); + return null; + } + + worker.Append(worker.Create(OpCodes.Stfld, field)); + fields++; + } + if (fields == 0) + { + Log.Warning($"{variable} has no public or non-static fields to deserialize"); + } + + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Ret)); + return readerFunc; + } + + } + +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Readers.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Readers.cs.meta new file mode 100644 index 0000000..838ff59 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Readers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be40277098a024539bf63d0205cae824 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Resolvers.cs b/Assets/Packages/Mirror/Editor/Weaver/Resolvers.cs new file mode 100644 index 0000000..434aed4 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Resolvers.cs @@ -0,0 +1,141 @@ +// all the resolve functions for the weaver +// NOTE: these functions should be made extensions, but right now they still +// make heavy use of Weaver.fail and we'd have to check each one's return +// value for null otherwise. +// (original FieldType.Resolve returns null if not found too, so +// exceptions would be a bit inconsistent here) +using Mono.CecilX; + +namespace Mirror.Weaver +{ + public static class Resolvers + { + public static MethodReference ResolveMethod(TypeReference tr, AssemblyDefinition scriptDef, string name) + { + //Console.WriteLine("ResolveMethod " + t.ToString () + " " + name); + if (tr == null) + { + Weaver.Error("Type missing for " + name); + return null; + } + foreach (MethodDefinition methodRef in tr.Resolve().Methods) + { + if (methodRef.Name == name) + { + return scriptDef.MainModule.ImportReference(methodRef); + } + } + Weaver.Error($"{tr}.{name}() not found"); + return null; + } + + // TODO reuse ResolveMethod in here after Weaver.fail was removed + public static MethodReference ResolveMethodInParents(TypeReference tr, AssemblyDefinition scriptDef, string name) + { + if (tr == null) + { + Weaver.Error("Type missing for " + name); + return null; + } + foreach (MethodDefinition methodRef in tr.Resolve().Methods) + { + if (methodRef.Name == name) + { + return scriptDef.MainModule.ImportReference(methodRef); + } + } + // Could not find the method in this class, try the parent + return ResolveMethodInParents(tr.Resolve().BaseType, scriptDef, name); + } + + // System.Byte[] arguments need a version with a string + public static MethodReference ResolveMethodWithArg(TypeReference tr, AssemblyDefinition scriptDef, string name, string argTypeFullName) + { + foreach (MethodDefinition methodRef in tr.Resolve().Methods) + { + if (methodRef.Name == name) + { + if (methodRef.Parameters.Count == 1) + { + if (methodRef.Parameters[0].ParameterType.FullName == argTypeFullName) + { + return scriptDef.MainModule.ImportReference(methodRef); + } + } + } + } + Weaver.Error($"{tr}.{name}({argTypeFullName}) not found"); + return null; + } + + // reuse ResolveMethodWithArg string version + public static MethodReference ResolveMethodWithArg(TypeReference tr, AssemblyDefinition scriptDef, string name, TypeReference argType) + { + return ResolveMethodWithArg(tr, scriptDef, name, argType.FullName); + } + + public static MethodDefinition ResolveDefaultPublicCtor(TypeReference variable) + { + foreach (MethodDefinition methodRef in variable.Resolve().Methods) + { + if (methodRef.Name == ".ctor" && + methodRef.Resolve().IsPublic && + methodRef.Parameters.Count == 0) + { + return methodRef; + } + } + return null; + } + + public static GenericInstanceMethod ResolveMethodGeneric(TypeReference t, AssemblyDefinition scriptDef, string name, TypeReference genericType) + { + foreach (MethodDefinition methodRef in t.Resolve().Methods) + { + if (methodRef.Name == name) + { + if (methodRef.Parameters.Count == 0) + { + if (methodRef.GenericParameters.Count == 1) + { + MethodReference tmp = scriptDef.MainModule.ImportReference(methodRef); + GenericInstanceMethod gm = new GenericInstanceMethod(tmp); + gm.GenericArguments.Add(genericType); + if (gm.GenericArguments[0].FullName == genericType.FullName) + { + return gm; + } + } + } + } + } + + Weaver.Error($"{t}.{name}<{genericType}>() not found"); + return null; + } + + public static FieldReference ResolveField(TypeReference tr, AssemblyDefinition scriptDef, string name) + { + foreach (FieldDefinition fd in tr.Resolve().Fields) + { + if (fd.Name == name) + { + return scriptDef.MainModule.ImportReference(fd); + } + } + return null; + } + + public static MethodReference ResolveProperty(TypeReference tr, AssemblyDefinition scriptDef, string name) + { + foreach (PropertyDefinition pd in tr.Resolve().Properties) + { + if (pd.Name == name) + { + return scriptDef.MainModule.ImportReference(pd.GetMethod); + } + } + return null; + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Resolvers.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Resolvers.cs.meta new file mode 100644 index 0000000..f4f6602 --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Resolvers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3039a59c76aec43c797ad66930430367 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Weaver.cs b/Assets/Packages/Mirror/Editor/Weaver/Weaver.cs new file mode 100644 index 0000000..cf905ad --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Weaver.cs @@ -0,0 +1,598 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + // This data is flushed each time - if we are run multiple times in the same process/domain + class WeaverLists + { + // 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(); + + // [Command]/[ClientRpc] functions that should be replaced. dict + public Dictionary replaceMethods = 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(); + } + + class Weaver + { + public static WeaverLists WeaveLists { get; private set; } + public static AssemblyDefinition CurrentAssembly { get; private set; } + public static ModuleDefinition CorLibModule { get; private set; } + public static AssemblyDefinition UnityAssembly { get; private set; } + public static AssemblyDefinition NetAssembly { get; private set; } + public static bool WeavingFailed { get; private set; } + public static bool GenerateLogErrors { get; set; } + + // private properties + static readonly bool DebugLogEnabled = true; + + // Network types + public static TypeReference NetworkBehaviourType; + public static TypeReference NetworkBehaviourType2; + public static TypeReference MonoBehaviourType; + public static TypeReference ScriptableObjectType; + public static TypeReference NetworkConnectionType; + + public static TypeReference MessageBaseType; + public static TypeReference SyncListType; + public static TypeReference SyncSetType; + public static TypeReference SyncDictionaryType; + + public static MethodReference NetworkBehaviourDirtyBitsReference; + public static MethodReference GetPooledWriterReference; + public static MethodReference RecycleWriterReference; + public static TypeReference NetworkClientType; + public static TypeReference NetworkServerType; + + public static TypeReference NetworkReaderType; + + public static TypeReference NetworkWriterType; + + public static TypeReference NetworkIdentityType; + public static TypeReference IEnumeratorType; + + public static TypeReference ClientSceneType; + public static MethodReference ReadyConnectionReference; + + public static TypeReference ComponentType; + + public static TypeReference CmdDelegateReference; + public static MethodReference CmdDelegateConstructor; + + public static MethodReference NetworkServerGetActive; + public static MethodReference NetworkServerGetLocalClientActive; + public static MethodReference NetworkClientGetActive; + public static MethodReference getBehaviourIsServer; + + // 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; + + // array segment + public static TypeReference ArraySegmentType; + public static MethodReference ArraySegmentConstructorReference; + public static MethodReference ArraySegmentArrayReference; + public static MethodReference ArraySegmentOffsetReference; + public static MethodReference ArraySegmentCountReference; + + // 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 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 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 int GetSyncVarStart(string className) + { + return WeaveLists.numSyncVars.ContainsKey(className) + ? WeaveLists.numSyncVars[className] + : 0; + } + + public static void SetNumSyncVars(string className, int num) + { + WeaveLists.numSyncVars[className] = num; + } + + internal static void ConfirmGeneratedCodeClass() + { + if (WeaveLists.generateContainerClass == null) + { + WeaveLists.generateContainerClass = new TypeDefinition("Mirror", "GeneratedNetworkCode", + TypeAttributes.BeforeFieldInit | TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.Public | TypeAttributes.AutoClass, + objectType); + + const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; + MethodDefinition method = new MethodDefinition(".ctor", methodAttributes, voidType); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, Resolvers.ResolveMethod(objectType, CurrentAssembly, ".ctor"))); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + + WeaveLists.generateContainerClass.Methods.Add(method); + } + } + + static bool ProcessNetworkBehaviourType(TypeDefinition td) + { + if (!NetworkBehaviourProcessor.WasProcessed(td)) + { + DLog(td, "Found NetworkBehaviour " + td.FullName); + + NetworkBehaviourProcessor proc = new NetworkBehaviourProcessor(td); + proc.Process(); + return true; + } + return false; + } + + static void SetupUnityTypes() + { + gameObjectType = UnityAssembly.MainModule.GetType("UnityEngine.GameObject"); + transformType = UnityAssembly.MainModule.GetType("UnityEngine.Transform"); + + NetworkClientType = NetAssembly.MainModule.GetType("Mirror.NetworkClient"); + NetworkServerType = NetAssembly.MainModule.GetType("Mirror.NetworkServer"); + + SyncVarType = NetAssembly.MainModule.GetType("Mirror.SyncVarAttribute"); + CommandType = NetAssembly.MainModule.GetType("Mirror.CommandAttribute"); + ClientRpcType = NetAssembly.MainModule.GetType("Mirror.ClientRpcAttribute"); + TargetRpcType = NetAssembly.MainModule.GetType("Mirror.TargetRpcAttribute"); + SyncEventType = NetAssembly.MainModule.GetType("Mirror.SyncEventAttribute"); + SyncObjectType = NetAssembly.MainModule.GetType("Mirror.SyncObject"); + } + + static void SetupCorLib() + { + AssemblyNameReference name = AssemblyNameReference.Parse("mscorlib"); + ReaderParameters parameters = new ReaderParameters + { + AssemblyResolver = CurrentAssembly.MainModule.AssemblyResolver + }; + CorLibModule = CurrentAssembly.MainModule.AssemblyResolver.Resolve(name, parameters).MainModule; + } + + static TypeReference ImportCorLibType(string fullName) + { + TypeDefinition type = CorLibModule.GetType(fullName) ?? CorLibModule.ExportedTypes.First(t => t.FullName == fullName).Resolve(); + if (type != null) + { + return CurrentAssembly.MainModule.ImportReference(type); + } + 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; + } + + static void SetupTargetTypes() + { + // system types + SetupCorLib(); + voidType = ImportCorLibType("System.Void"); + singleType = ImportCorLibType("System.Single"); + doubleType = ImportCorLibType("System.Double"); + boolType = ImportCorLibType("System.Boolean"); + int64Type = ImportCorLibType("System.Int64"); + uint64Type = ImportCorLibType("System.UInt64"); + int32Type = ImportCorLibType("System.Int32"); + uint32Type = ImportCorLibType("System.UInt32"); + objectType = ImportCorLibType("System.Object"); + typeType = ImportCorLibType("System.Type"); + IEnumeratorType = ImportCorLibType("System.Collections.IEnumerator"); + + ArraySegmentType = ImportCorLibType("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"); + + + NetworkReaderType = NetAssembly.MainModule.GetType("Mirror.NetworkReader"); + NetworkWriterType = NetAssembly.MainModule.GetType("Mirror.NetworkWriter"); + + NetworkServerGetActive = Resolvers.ResolveMethod(NetworkServerType, CurrentAssembly, "get_active"); + NetworkServerGetLocalClientActive = Resolvers.ResolveMethod(NetworkServerType, CurrentAssembly, "get_localClientActive"); + NetworkClientGetActive = Resolvers.ResolveMethod(NetworkClientType, CurrentAssembly, "get_active"); + + CmdDelegateReference = NetAssembly.MainModule.GetType("Mirror.NetworkBehaviour/CmdDelegate"); + CmdDelegateConstructor = Resolvers.ResolveMethod(CmdDelegateReference, CurrentAssembly, ".ctor"); + CurrentAssembly.MainModule.ImportReference(gameObjectType); + CurrentAssembly.MainModule.ImportReference(transformType); + + TypeReference networkIdentityTmp = NetAssembly.MainModule.GetType("Mirror.NetworkIdentity"); + NetworkIdentityType = CurrentAssembly.MainModule.ImportReference(networkIdentityTmp); + + NetworkBehaviourType = NetAssembly.MainModule.GetType("Mirror.NetworkBehaviour"); + NetworkBehaviourType2 = CurrentAssembly.MainModule.ImportReference(NetworkBehaviourType); + NetworkConnectionType = NetAssembly.MainModule.GetType("Mirror.NetworkConnection"); + + MonoBehaviourType = UnityAssembly.MainModule.GetType("UnityEngine.MonoBehaviour"); + ScriptableObjectType = UnityAssembly.MainModule.GetType("UnityEngine.ScriptableObject"); + + NetworkConnectionType = NetAssembly.MainModule.GetType("Mirror.NetworkConnection"); + NetworkConnectionType = CurrentAssembly.MainModule.ImportReference(NetworkConnectionType); + + MessageBaseType = NetAssembly.MainModule.GetType("Mirror.MessageBase"); + SyncListType = NetAssembly.MainModule.GetType("Mirror.SyncList`1"); + SyncSetType = NetAssembly.MainModule.GetType("Mirror.SyncSet`1"); + SyncDictionaryType = NetAssembly.MainModule.GetType("Mirror.SyncDictionary`2"); + + NetworkBehaviourDirtyBitsReference = Resolvers.ResolveProperty(NetworkBehaviourType, CurrentAssembly, "syncVarDirtyBits"); + TypeDefinition NetworkWriterPoolType = NetAssembly.MainModule.GetType("Mirror.NetworkWriterPool"); + GetPooledWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, CurrentAssembly, "GetWriter"); + RecycleWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, CurrentAssembly, "Recycle"); + + ComponentType = UnityAssembly.MainModule.GetType("UnityEngine.Component"); + ClientSceneType = NetAssembly.MainModule.GetType("Mirror.ClientScene"); + ReadyConnectionReference = Resolvers.ResolveMethod(ClientSceneType, CurrentAssembly, "get_readyConnection"); + + getBehaviourIsServer = Resolvers.ResolveMethod(NetworkBehaviourType, CurrentAssembly, "get_isServer"); + 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(NetworkBehaviourType, CurrentAssembly, "RegisterCommandDelegate"); + registerRpcDelegateReference = Resolvers.ResolveMethod(NetworkBehaviourType, CurrentAssembly, "RegisterRpcDelegate"); + registerEventDelegateReference = Resolvers.ResolveMethod(NetworkBehaviourType, 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"); + } + + public static bool IsNetworkBehaviour(TypeDefinition td) + { + return td.IsDerivedFrom(NetworkBehaviourType); + } + + public static bool IsValidTypeToGenerate(TypeDefinition variable) + { + // a valid type is a simple class or struct. so we generate only code for types we dont know, and if they are not inside + // this assembly it must mean that we are trying to serialize a variable outside our scope. and this will fail. + // no need to report an error here, the caller will report a better error + string assembly = CurrentAssembly.MainModule.Name; + return variable.Module.Name == assembly; + } + + static void CheckMonoBehaviour(TypeDefinition td) + { + if (td.IsDerivedFrom(MonoBehaviourType)) + { + MonoBehaviourProcessor.Process(td); + } + } + + static bool CheckNetworkBehaviour(TypeDefinition td) + { + if (!td.IsClass) + return false; + + if (!IsNetworkBehaviour(td)) + { + CheckMonoBehaviour(td); + return false; + } + + // process this and base classes from parent to child order + + List behaviourClasses = new List(); + + TypeDefinition parent = td; + while (parent != null) + { + if (parent.FullName == NetworkBehaviourType.FullName) + { + break; + } + try + { + behaviourClasses.Insert(0, parent); + parent = parent.BaseType.Resolve(); + } + catch (AssemblyResolutionException) + { + // this can happen for plugins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + + bool didWork = false; + foreach (TypeDefinition behaviour in behaviourClasses) + { + didWork |= ProcessNetworkBehaviourType(behaviour); + } + return didWork; + } + + static bool CheckMessageBase(TypeDefinition td) + { + if (!td.IsClass) + return false; + + bool didWork = false; + + // are ANY parent classes MessageBase + TypeReference parent = td.BaseType; + while (parent != null) + { + if (parent.FullName == MessageBaseType.FullName) + { + MessageClassProcessor.Process(td); + didWork = true; + break; + } + try + { + parent = parent.Resolve().BaseType; + } + catch (AssemblyResolutionException) + { + // this can happen for plugins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + + // check for embedded types + foreach (TypeDefinition embedded in td.NestedTypes) + { + didWork |= CheckMessageBase(embedded); + } + + return didWork; + } + + static bool CheckSyncList(TypeDefinition td) + { + if (!td.IsClass) + return false; + + bool didWork = false; + + // are ANY parent classes SyncListStruct + TypeReference parent = td.BaseType; + while (parent != null) + { + if (parent.FullName.StartsWith(SyncListType.FullName, StringComparison.Ordinal)) + { + SyncListProcessor.Process(td); + didWork = true; + break; + } + if (parent.FullName.StartsWith(SyncSetType.FullName, StringComparison.Ordinal)) + { + SyncListProcessor.Process(td); + didWork = true; + break; + } + if (parent.FullName.StartsWith(SyncDictionaryType.FullName, StringComparison.Ordinal)) + { + SyncDictionaryProcessor.Process(td); + didWork = true; + break; + } + try + { + parent = parent.Resolve().BaseType; + } + catch (AssemblyResolutionException) + { + // this can happen for pluins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + + // check for embedded types + foreach (TypeDefinition embedded in td.NestedTypes) + { + didWork |= CheckSyncList(embedded); + } + + return didWork; + } + + static bool Weave(string assName, 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); + } + } + + SetupTargetTypes(); + System.Diagnostics.Stopwatch rwstopwatch = System.Diagnostics.Stopwatch.StartNew(); + ReaderWriterProcessor.ProcessReadersAndWriters(CurrentAssembly); + rwstopwatch.Stop(); + Console.WriteLine("Find all reader and writers took " + rwstopwatch.ElapsedMilliseconds + " milliseconds"); + + ModuleDefinition moduleDefinition = CurrentAssembly.MainModule; + Console.WriteLine("Script Module: {0}", moduleDefinition.Name); + + // Process each NetworkBehaviour + bool didWork = false; + + // We need to do 2 passes, because SyncListStructs might be referenced from other modules, so we must make sure we generate them first. + for (int pass = 0; pass < 2; pass++) + { + System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew(); + foreach (TypeDefinition td in moduleDefinition.Types) + { + if (td.IsClass && td.BaseType.CanBeResolved()) + { + try + { + if (pass == 0) + { + didWork |= CheckSyncList(td); + } + else + { + didWork |= CheckNetworkBehaviour(td); + didWork |= CheckMessageBase(td); + } + } + catch (Exception ex) + { + Error(ex.ToString()); + throw ex; + } + } + + if (WeavingFailed) + { + return false; + } + } + watch.Stop(); + Console.WriteLine("Pass: " + pass + " took " + watch.ElapsedMilliseconds + " milliseconds"); + } + + if (didWork) + { + // this must be done for ALL code, not just NetworkBehaviours + try + { + PropertySiteProcessor.ProcessSitesModule(CurrentAssembly.MainModule); + } + catch (Exception e) + { + Log.Error("ProcessPropertySites exception: " + e); + return false; + } + + if (WeavingFailed) + { + //Log.Error("Failed phase II."); + return false; + } + + // write to outputDir if specified, otherwise perform in-place write + WriterParameters writeParams = new WriterParameters { WriteSymbols = true }; + if (outputDir != null) + { + CurrentAssembly.Write(Helpers.DestinationFileFor(outputDir, assName), writeParams); + } + else + { + CurrentAssembly.Write(writeParams); + } + } + } + + return true; + } + + public static bool WeaveAssemblies(IEnumerable assemblies, IEnumerable dependencies, string outputDir, string unityEngineDLLPath, string mirrorNetDLLPath) + { + WeavingFailed = false; + WeaveLists = new WeaverLists(); + + using (UnityAssembly = AssemblyDefinition.ReadAssembly(unityEngineDLLPath)) + using (NetAssembly = AssemblyDefinition.ReadAssembly(mirrorNetDLLPath)) + { + SetupUnityTypes(); + + try + { + foreach (string ass in assemblies) + { + if (!Weave(ass, dependencies, unityEngineDLLPath, mirrorNetDLLPath, outputDir)) + { + return false; + } + } + } + catch (Exception e) + { + Log.Error("Exception :" + e); + return false; + } + } + return true; + } + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Weaver.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Weaver.cs.meta new file mode 100644 index 0000000..0ea2dfe --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Weaver.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de160f52931054064852f2afd7e7a86f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Editor/Weaver/Writers.cs b/Assets/Packages/Mirror/Editor/Weaver/Writers.cs new file mode 100644 index 0000000..040960d --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Writers.cs @@ -0,0 +1,350 @@ +using System.Collections.Generic; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + + public static class Writers + { + const int MaxRecursionCount = 128; + + static Dictionary writeFuncs; + + public static void Init() + { + writeFuncs = new Dictionary(); + } + + public static void Register(TypeReference dataType, MethodReference methodReference) + { + writeFuncs[dataType.FullName] = methodReference; + } + + public static MethodReference GetWriteFunc(TypeReference variable, int recursionCount = 0) + { + if (writeFuncs.TryGetValue(variable.FullName, out MethodReference foundFunc)) + { + return foundFunc; + } + + if (variable.IsByReference) + { + // error?? + Weaver.Error($"{variable} has unsupported type. Use one of Mirror supported types instead"); + return null; + } + + MethodDefinition newWriterFunc; + + if (variable.IsArray) + { + newWriterFunc = GenerateArrayWriteFunc(variable, recursionCount); + } + else if (variable.Resolve().IsEnum) + { + return GetWriteFunc(variable.Resolve().GetEnumUnderlyingType(), recursionCount); + } + else if (variable.FullName.StartsWith("System.ArraySegment`1", System.StringComparison.Ordinal)) + { + newWriterFunc = GenerateArraySegmentWriteFunc(variable, recursionCount); + } + else + { + newWriterFunc = GenerateStructWriterFunction(variable, recursionCount); + } + + if (newWriterFunc == null) + { + return null; + } + + RegisterWriteFunc(variable.FullName, newWriterFunc); + return newWriterFunc; + } + + static void RegisterWriteFunc(string name, MethodDefinition newWriterFunc) + { + writeFuncs[name] = newWriterFunc; + Weaver.WeaveLists.generatedWriteFunctions.Add(newWriterFunc); + + Weaver.ConfirmGeneratedCodeClass(); + Weaver.WeaveLists.generateContainerClass.Methods.Add(newWriterFunc); + } + + static MethodDefinition GenerateStructWriterFunction(TypeReference variable, int recursionCount) + { + if (recursionCount > MaxRecursionCount) + { + Weaver.Error($"{variable} can't be serialized because it references itself"); + return null; + } + + if (!Weaver.IsValidTypeToGenerate(variable.Resolve())) + { + return null; + } + + string functionName = "_Write" + variable.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, + Weaver.voidType); + + writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); + writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(variable))); + + ILProcessor worker = writerFunc.Body.GetILProcessor(); + + uint fields = 0; + foreach (FieldDefinition field in variable.Resolve().Fields) + { + if (field.IsStatic || field.IsPrivate) + continue; + + if (field.FieldType.Resolve().HasGenericParameters) + { + Weaver.Error($"{field} has unsupported type. Create a derived class instead of using generics"); + return null; + } + + if (field.FieldType.Resolve().IsInterface) + { + Weaver.Error($"{field} has unsupported type. Use a concrete class instead of an interface"); + return null; + } + + MethodReference writeFunc = GetWriteFunc(field.FieldType, recursionCount + 1); + if (writeFunc != null) + { + fields++; + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Ldarg_1)); + worker.Append(worker.Create(OpCodes.Ldfld, field)); + worker.Append(worker.Create(OpCodes.Call, writeFunc)); + } + else + { + Weaver.Error($"{field} has unsupported type. Use a type supported by Mirror instead"); + return null; + } + } + if (fields == 0) + { + Log.Warning($" {variable} has no no public or non-static fields to serialize"); + } + worker.Append(worker.Create(OpCodes.Ret)); + return writerFunc; + } + + static MethodDefinition GenerateArrayWriteFunc(TypeReference variable, int recursionCount) + { + + if (!variable.IsArrayType()) + { + Weaver.Error($"{variable} is an unsupported type. Jagged and multidimensional arrays are not supported"); + return null; + } + + TypeReference elementType = variable.GetElementType(); + MethodReference elementWriteFunc = GetWriteFunc(elementType, recursionCount + 1); + if (elementWriteFunc == null) + { + return null; + } + + string functionName = "_WriteArray" + variable.GetElementType().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, + Weaver.voidType); + + writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); + writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(variable))); + + writerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); + writerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); + 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, GetWriteFunc(Weaver.int32Type))); + worker.Append(worker.Create(OpCodes.Ret)); + + // int length = value.Length; + worker.Append(labelNull); + 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, GetWriteFunc(Weaver.int32Type))); + + // 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, variable.GetElementType())); + worker.Append(worker.Create(OpCodes.Ldobj, variable.GetElementType())); + 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)); + return writerFunc; + } + + static MethodDefinition GenerateArraySegmentWriteFunc(TypeReference variable, int recursionCount) + { + GenericInstanceType genericInstance = (GenericInstanceType)variable; + TypeReference elementType = genericInstance.GenericArguments[0]; + MethodReference elementWriteFunc = GetWriteFunc(elementType, recursionCount + 1); + + if (elementWriteFunc == null) + { + 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, + Weaver.voidType); + + writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); + writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, variable)); + + writerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); + writerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); + writerFunc.Body.InitLocals = true; + + ILProcessor worker = writerFunc.Body.GetILProcessor(); + + MethodReference countref = Weaver.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)); + + + // writer.WritePackedInt32(length); + worker.Append(worker.Create(OpCodes.Ldarg_0)); + worker.Append(worker.Create(OpCodes.Ldloc_0)); + worker.Append(worker.Create(OpCodes.Call, GetWriteFunc(Weaver.int32Type))); + + // Loop through the ArraySegment and call the writer for each element. + // generates this: + // for (int i=0; i< length; i++) + // { + // writer.Write(value.Array[i + value.Offset]); + // } + 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, Weaver.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, Weaver.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; + } + + } +} diff --git a/Assets/Packages/Mirror/Editor/Weaver/Writers.cs.meta b/Assets/Packages/Mirror/Editor/Weaver/Writers.cs.meta new file mode 100644 index 0000000..3769f7f --- /dev/null +++ b/Assets/Packages/Mirror/Editor/Weaver/Writers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a90060ad76ea044aba613080dd922709 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples.meta b/Assets/Packages/Mirror/Examples.meta new file mode 100644 index 0000000..b594a81 --- /dev/null +++ b/Assets/Packages/Mirror/Examples.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a08b1f591326642d1b140fc818c9c6b1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes.meta new file mode 100644 index 0000000..bf61013 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b84b2a39b3027c747b21ad714a439214 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/AnimationControllers.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/AnimationControllers.meta new file mode 100644 index 0000000..c9cd79f --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/AnimationControllers.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4969918300bfa9a4a8c733975df74016 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/AnimationControllers/Tank.controller b/Assets/Packages/Mirror/Examples/AdditiveScenes/AnimationControllers/Tank.controller new file mode 100644 index 0000000..5a7f506 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/AnimationControllers/Tank.controller @@ -0,0 +1,156 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!91 &9100000 +AnimatorController: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Tank + serializedVersion: 5 + m_AnimatorParameters: + - m_Name: Fire + m_Type: 9 + m_DefaultFloat: 0 + m_DefaultInt: 0 + m_DefaultBool: 0 + m_Controller: {fileID: 0} + m_AnimatorLayers: + - serializedVersion: 5 + m_Name: Base Layer + m_StateMachine: {fileID: 1107206089488630588} + m_Mask: {fileID: 0} + m_Motions: [] + m_Behaviours: [] + m_BlendingMode: 0 + m_SyncedLayerIndex: -1 + m_DefaultWeight: 0 + m_IKPass: 0 + m_SyncedLayerAffectsTiming: 0 + m_Controller: {fileID: 9100000} +--- !u!1101 &1101845105868117086 +AnimatorStateTransition: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + m_Conditions: + - m_ConditionMode: 1 + m_ConditionEvent: Fire + m_EventTreshold: 0 + m_DstStateMachine: {fileID: 0} + m_DstState: {fileID: 1102477577393645330} + m_Solo: 0 + m_Mute: 0 + m_IsExit: 0 + serializedVersion: 3 + m_TransitionDuration: 0.25 + m_TransitionOffset: 0 + m_ExitTime: 0.45454544 + m_HasExitTime: 0 + m_HasFixedDuration: 1 + m_InterruptionSource: 0 + m_OrderedInterruption: 1 + m_CanTransitionToSelf: 1 +--- !u!1101 &1101857281332299900 +AnimatorStateTransition: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + m_Conditions: [] + m_DstStateMachine: {fileID: 0} + m_DstState: {fileID: 1102845660080023070} + m_Solo: 0 + m_Mute: 0 + m_IsExit: 0 + serializedVersion: 3 + m_TransitionDuration: 0.058695674 + m_TransitionOffset: 0.41739127 + m_ExitTime: 0.9060869 + m_HasExitTime: 1 + m_HasFixedDuration: 1 + m_InterruptionSource: 0 + m_OrderedInterruption: 1 + m_CanTransitionToSelf: 1 +--- !u!1102 &1102477577393645330 +AnimatorState: + serializedVersion: 5 + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Recon_Tank_Rig|Shoot + m_Speed: 1 + m_CycleOffset: 0 + m_Transitions: + - {fileID: 1101857281332299900} + m_StateMachineBehaviours: [] + m_Position: {x: 50, y: 50, z: 0} + m_IKOnFeet: 0 + m_WriteDefaultValues: 1 + m_Mirror: 0 + m_SpeedParameterActive: 0 + m_MirrorParameterActive: 0 + m_CycleOffsetParameterActive: 0 + m_TimeParameterActive: 0 + m_Motion: {fileID: 7400006, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + m_Tag: + m_SpeedParameter: + m_MirrorParameter: + m_CycleOffsetParameter: + m_TimeParameter: +--- !u!1102 &1102845660080023070 +AnimatorState: + serializedVersion: 5 + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Recon_Tank_Rig|Idle + m_Speed: 1 + m_CycleOffset: 0 + m_Transitions: + - {fileID: 1101845105868117086} + m_StateMachineBehaviours: [] + m_Position: {x: 50, y: 50, z: 0} + m_IKOnFeet: 0 + m_WriteDefaultValues: 1 + m_Mirror: 0 + m_SpeedParameterActive: 0 + m_MirrorParameterActive: 0 + m_CycleOffsetParameterActive: 0 + m_TimeParameterActive: 0 + m_Motion: {fileID: 7400004, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + m_Tag: + m_SpeedParameter: + m_MirrorParameter: + m_CycleOffsetParameter: + m_TimeParameter: +--- !u!1107 &1107206089488630588 +AnimatorStateMachine: + serializedVersion: 5 + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Base Layer + m_ChildStates: + - serializedVersion: 1 + m_State: {fileID: 1102845660080023070} + m_Position: {x: 132, y: 300, z: 0} + - serializedVersion: 1 + m_State: {fileID: 1102477577393645330} + m_Position: {x: 360, y: 432, z: 0} + m_ChildStateMachines: [] + m_AnyStateTransitions: [] + m_EntryTransitions: [] + m_StateMachineTransitions: {} + m_StateMachineBehaviours: [] + m_AnyStatePosition: {x: 50, y: 20, z: 0} + m_EntryPosition: {x: 50, y: 120, z: 0} + m_ExitPosition: {x: 800, y: 120, z: 0} + m_ParentStateMachinePosition: {x: 800, y: 20, z: 0} + m_DefaultState: {fileID: 1102845660080023070} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/AnimationControllers/Tank.controller.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/AnimationControllers/Tank.controller.meta new file mode 100644 index 0000000..b4df009 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/AnimationControllers/Tank.controller.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e0dbc8b2f2711a54f9b7ed1358a4c6af +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 9100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials.meta new file mode 100644 index 0000000..d6629fb --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7ef7a74859259a546b73ed820e449ae8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Capsule.mat b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Capsule.mat new file mode 100644 index 0000000..09a4fa2 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Capsule.mat @@ -0,0 +1,77 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Capsule + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0, g: 0.07727194, b: 1, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Capsule.mat.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Capsule.mat.meta new file mode 100644 index 0000000..b202aa9 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Capsule.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3ec90781e3720544da7fc86055e6cbe6 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cube.mat b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cube.mat new file mode 100644 index 0000000..f7e2181 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cube.mat @@ -0,0 +1,77 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Cube + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 1, g: 0.93989503, b: 0, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cube.mat.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cube.mat.meta new file mode 100644 index 0000000..9c096c8 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cube.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1d5f3015968dad04780bf9d2113cc772 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cylinder.mat b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cylinder.mat new file mode 100644 index 0000000..59d5192 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cylinder.mat @@ -0,0 +1,77 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Cylinder + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0, g: 0.5943396, b: 0.054526776, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cylinder.mat.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cylinder.mat.meta new file mode 100644 index 0000000..00cc85e --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Cylinder.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 439a10ee8f8d14040be9003239449741 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Player.mat b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Player.mat new file mode 100644 index 0000000..d16a481 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Player.mat @@ -0,0 +1,77 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Player + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0, g: 0, b: 0, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Player.mat.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Player.mat.meta new file mode 100644 index 0000000..56884a4 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Player.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 792117fe9a386a8489e8010bec746339 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Quad.mat b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Quad.mat new file mode 100644 index 0000000..060786b --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Quad.mat @@ -0,0 +1,77 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Quad + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0.8207547, g: 0.8207547, b: 0.8207547, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Quad.mat.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Quad.mat.meta new file mode 100644 index 0000000..be7d0db --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Quad.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6eb3f3ba66756364d8b94e662e7e8af5 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Shelter.mat b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Shelter.mat new file mode 100644 index 0000000..73ef86d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Shelter.mat @@ -0,0 +1,77 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Shelter + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0.8018868, g: 0.52244145, b: 0, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Shelter.mat.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Shelter.mat.meta new file mode 100644 index 0000000..c261931 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Shelter.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: aef230244d219314fb8453f0365b8176 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Sphere.mat b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Sphere.mat new file mode 100644 index 0000000..4358e1b --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Sphere.mat @@ -0,0 +1,77 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Sphere + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0.9716981, g: 0, b: 0.77970594, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Sphere.mat.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Sphere.mat.meta new file mode 100644 index 0000000..8822215 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Sphere.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 58936713efca1ec488624ee297b5d687 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Zone.mat b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Zone.mat new file mode 100644 index 0000000..38e8f91 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Zone.mat @@ -0,0 +1,78 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Zone + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: _ALPHAPREMULTIPLY_ON + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: 3000 + stringTagMap: + RenderType: Transparent + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 10 + - _GlossMapScale: 1 + - _Glossiness: 0 + - _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, g: 0, b: 0, a: 0.039215688} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Zone.mat.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Zone.mat.meta new file mode 100644 index 0000000..4cfbe95 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Materials/Zone.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a7c679cf124f7ae46a0291ea35848554 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs.meta new file mode 100644 index 0000000..37601bf --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2be4f78570b2a1e4cae84466d35d606c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Capsule.prefab b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Capsule.prefab new file mode 100644 index 0000000..ed82957 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Capsule.prefab @@ -0,0 +1,132 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &1076878374699499732 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1076878374699499735} + - component: {fileID: 1076878374699499728} + - component: {fileID: 1076878374699499729} + - component: {fileID: 1076878374699499734} + - component: {fileID: 2648107611936813301} + - component: {fileID: 5697694911122891659} + m_Layer: 0 + m_Name: Capsule + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1076878374699499735 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1076878374699499732} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 20, y: 1, z: -20} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &1076878374699499728 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1076878374699499732} + m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &1076878374699499729 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1076878374699499732} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 3ec90781e3720544da7fc86055e6cbe6, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!136 &1076878374699499734 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1076878374699499732} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &2648107611936813301 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1076878374699499732} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_ServerOnly: 0 + m_LocalPlayerAuthority: 0 + m_AssetId: e1971f4a8c7661546bc509b44bd91b80 + m_SceneId: 0 +--- !u!114 &5697694911122891659 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1076878374699499732} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 1731d8de2d0c84333b08ebe1e79f4118, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + visRange: 5 + visUpdateInterval: 0.1 + checkMethod: 0 + forceHidden: 0 + castLayers: + serializedVersion: 2 + m_Bits: 512 diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Capsule.prefab.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Capsule.prefab.meta new file mode 100644 index 0000000..99fb5c0 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Capsule.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: e1971f4a8c7661546bc509b44bd91b80 +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cube.prefab b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cube.prefab new file mode 100644 index 0000000..1c18855 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cube.prefab @@ -0,0 +1,131 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &5623359707189648430 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5623359707189648426} + - component: {fileID: 5623359707189648427} + - component: {fileID: 5623359707189648424} + - component: {fileID: 5623359707189648425} + - component: {fileID: 5623359707189648404} + - component: {fileID: 5623359707189648405} + m_Layer: 0 + m_Name: Cube + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &5623359707189648426 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5623359707189648430} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1, z: 2} + m_LocalScale: {x: 2, y: 2, z: 2} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &5623359707189648427 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5623359707189648430} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &5623359707189648424 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5623359707189648430} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 1d5f3015968dad04780bf9d2113cc772, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!65 &5623359707189648425 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5623359707189648430} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &5623359707189648404 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5623359707189648430} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_ServerOnly: 0 + m_LocalPlayerAuthority: 0 + m_AssetId: 4ff300cf6bb3c6342a9552c4f18788c8 + m_SceneId: 0 +--- !u!114 &5623359707189648405 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5623359707189648430} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 1731d8de2d0c84333b08ebe1e79f4118, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + visRange: 5 + visUpdateInterval: 0.1 + checkMethod: 0 + forceHidden: 0 + castLayers: + serializedVersion: 2 + m_Bits: 512 diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cube.prefab.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cube.prefab.meta new file mode 100644 index 0000000..8b53f72 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cube.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4ff300cf6bb3c6342a9552c4f18788c8 +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cylinder.prefab b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cylinder.prefab new file mode 100644 index 0000000..c20ee74 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cylinder.prefab @@ -0,0 +1,132 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &6852530814182375312 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 6852530814182375316} + - component: {fileID: 6852530814182375315} + - component: {fileID: 6852530814182375314} + - component: {fileID: 6852530814182375313} + - component: {fileID: 6852530814182375318} + - component: {fileID: 6852530814182375317} + m_Layer: 0 + m_Name: Cylinder + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &6852530814182375316 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6852530814182375312} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -2, y: 1, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &6852530814182375315 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6852530814182375312} + m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &6852530814182375314 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6852530814182375312} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 439a10ee8f8d14040be9003239449741, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!136 &6852530814182375313 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6852530814182375312} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &6852530814182375318 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6852530814182375312} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_ServerOnly: 0 + m_LocalPlayerAuthority: 0 + m_AssetId: + m_SceneId: 1282598157 +--- !u!114 &6852530814182375317 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6852530814182375312} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 1731d8de2d0c84333b08ebe1e79f4118, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + visRange: 5 + visUpdateInterval: 0.1 + checkMethod: 0 + forceHidden: 0 + castLayers: + serializedVersion: 2 + m_Bits: 512 diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cylinder.prefab.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cylinder.prefab.meta new file mode 100644 index 0000000..113674d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Cylinder.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 12a4c14e672c00b4b840f937d824b890 +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Player.prefab b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Player.prefab new file mode 100644 index 0000000..3279cc9 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Player.prefab @@ -0,0 +1,249 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &5815001218983416211 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3254954141432383832} + - component: {fileID: 1800893346221236401} + - component: {fileID: 136369082707552984} + m_Layer: 0 + m_Name: Visor + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &3254954141432383832 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5815001218983416211} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0.39999998, z: 0.505} + m_LocalScale: {x: 0.5, y: 0.099999994, z: 0.19999999} + m_Children: [] + m_Father: {fileID: 5328458565928408179} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &1800893346221236401 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5815001218983416211} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &136369082707552984 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5815001218983416211} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_RendererPriority: 0 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!1 &8872462076811691049 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5328458565928408179} + - component: {fileID: 7482234573209362796} + - component: {fileID: 8972496075962964235} + - component: {fileID: 8993127209816276930} + - component: {fileID: 8537344390966522168} + - component: {fileID: 8704659178864205755} + - component: {fileID: 887491563423388292} + - component: {fileID: 3117920708280701079} + m_Layer: 9 + m_Name: Player + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &5328458565928408179 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8872462076811691049} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1.08, z: -20} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 3254954141432383832} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &7482234573209362796 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8872462076811691049} + m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &8972496075962964235 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8872462076811691049} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 792117fe9a386a8489e8010bec746339, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!143 &8993127209816276930 +CharacterController: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8872462076811691049} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Height: 2 + m_Radius: 0.5 + m_SlopeLimit: 45 + m_StepOffset: 0.3 + m_SkinWidth: 0.08 + m_MinMoveDistance: 0.001 + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &8537344390966522168 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8872462076811691049} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + serverOnly: 0 + localPlayerAuthority: 1 + m_AssetId: a5bdca0a2315d43499be7dcef473fbc7 + m_SceneId: 0 +--- !u!114 &8704659178864205755 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8872462076811691049} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: e8f68561248aaca4fb96847ce24742ee, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0 + playerColor: {r: 0, g: 0, b: 0, a: 1} + moveSpeed: 8 + turnSpeedAccel: 5 + turnSpeedDecel: 5 + maxTurnSpeed: 150 + jumpSpeed: 0 + maxJumpSpeed: 5 + jumpFactor: 0.05 + horizontal: 0 + vertical: 0 + turn: 0 + isGrounded: 1 + isFalling: 0 +--- !u!114 &887491563423388292 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8872462076811691049} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2f74aedd71d9a4f55b3ce499326d45fb, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + compressRotation: 1 +--- !u!114 &3117920708280701079 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8872462076811691049} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2925d2020e4083646acf0ba4f4a06858, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Player.prefab.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Player.prefab.meta new file mode 100644 index 0000000..b91d19d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Player.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a5bdca0a2315d43499be7dcef473fbc7 +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Sphere.prefab b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Sphere.prefab new file mode 100644 index 0000000..de222c8 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Sphere.prefab @@ -0,0 +1,131 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &855244094988030905 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 855244094988030909} + - component: {fileID: 855244094988030906} + - component: {fileID: 855244094988030907} + - component: {fileID: 855244094988030904} + - component: {fileID: 855244094988030911} + - component: {fileID: 855244094988030908} + m_Layer: 0 + m_Name: Sphere + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &855244094988030909 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 855244094988030905} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 2, y: 1, z: 0} + m_LocalScale: {x: 2, y: 2, z: 2} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &855244094988030906 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 855244094988030905} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &855244094988030907 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 855244094988030905} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 58936713efca1ec488624ee297b5d687, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!135 &855244094988030904 +SphereCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 855244094988030905} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Radius: 0.5 + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &855244094988030911 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 855244094988030905} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_ServerOnly: 0 + m_LocalPlayerAuthority: 0 + m_AssetId: f6d08eb9a8e35d84fa30a7e3ae64181a + m_SceneId: 0 +--- !u!114 &855244094988030908 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 855244094988030905} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 1731d8de2d0c84333b08ebe1e79f4118, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + visRange: 5 + visUpdateInterval: 0.1 + checkMethod: 0 + forceHidden: 0 + castLayers: + serializedVersion: 2 + m_Bits: 512 diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Sphere.prefab.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Sphere.prefab.meta new file mode 100644 index 0000000..0fb6a41 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Sphere.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f6d08eb9a8e35d84fa30a7e3ae64181a +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Tank.prefab b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Tank.prefab new file mode 100644 index 0000000..1b542d9 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Tank.prefab @@ -0,0 +1,596 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &160176457 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 160176456} + - component: {fileID: 160176460} + - component: {fileID: 160176459} + - component: {fileID: 160176458} + - component: {fileID: 160176461} + - component: {fileID: 160176462} + m_Layer: 0 + m_Name: reconTank + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &160176456 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 160176457} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -20, y: 0, z: -20} + m_LocalScale: {x: 5, y: 5, z: 5} + m_Children: + - {fileID: 3234001708628876000} + - {fileID: 1042389410631263445} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!95 &160176460 +Animator: + serializedVersion: 3 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 160176457} + m_Enabled: 1 + m_Avatar: {fileID: 9000000, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + m_Controller: {fileID: 9100000, guid: e0dbc8b2f2711a54f9b7ed1358a4c6af, type: 2} + m_CullingMode: 1 + m_UpdateMode: 0 + m_ApplyRootMotion: 0 + m_LinearVelocityBlending: 0 + m_WarningMessage: + m_HasTransformHierarchy: 1 + m_AllowConstantClipSamplingOptimization: 1 + m_KeepAnimatorControllerStateOnDisable: 0 +--- !u!114 &160176459 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 160176457} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_ServerOnly: 0 + m_LocalPlayerAuthority: 0 + m_AssetId: ab222ed73ada1ac4ba2f61e843d7627c + m_SceneId: 0 +--- !u!114 &160176458 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 160176457} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 1731d8de2d0c84333b08ebe1e79f4118, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + visRange: 10 + visUpdateInterval: 0.1 + checkMethod: 0 + forceHidden: 0 + castLayers: + serializedVersion: 2 + m_Bits: 512 +--- !u!114 &160176461 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 160176457} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7f6f3bf89aa97405989c802ba270f815, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + animator: {fileID: 160176460} +--- !u!114 &160176462 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 160176457} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7a25c54cd35eb284eb6b8ed19cf60443, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + Rotation: {x: 0, y: 0, z: 0, w: 0} + turnSpeed: 0.1 +--- !u!1 &489699669850839237 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 6048638457609172120} + m_Layer: 0 + m_Name: Wheel_Rear_L_end + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &6048638457609172120 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 489699669850839237} + m_LocalRotation: {x: 0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -0, y: 0.0021921142, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 5371032128924763904} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &739025013192983599 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1766344861363284577} + m_Layer: 0 + m_Name: Wheel_Middle_L + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1766344861363284577 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 739025013192983599} + m_LocalRotation: {x: -0.5, y: 0.5, z: 0.49999994, w: 0.50000006} + m_LocalPosition: {x: -0, y: 0.0011627917, z: 0.0000000010728836} + m_LocalScale: {x: 1, y: 0.99999994, z: 1} + m_Children: + - {fileID: 9163197381092130014} + m_Father: {fileID: 847897825935598517} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1014401586714983030 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7755980514232685276} + m_Layer: 0 + m_Name: Turret + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &7755980514232685276 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1014401586714983030} + m_LocalRotation: {x: 0, y: -0.000000119209275, z: -0, w: 1} + m_LocalPosition: {x: -0, y: 0.0010293524, z: 0} + m_LocalScale: {x: 1, y: 0.99999994, z: 1} + m_Children: + - {fileID: 1517159280684637724} + m_Father: {fileID: 1703734463393124925} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1218215768088827738 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5371032128924763904} + m_Layer: 0 + m_Name: Wheel_Rear_L + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &5371032128924763904 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1218215768088827738} + m_LocalRotation: {x: -0.5, y: 0.5, z: 0.49999994, w: 0.50000006} + m_LocalPosition: {x: -0, y: 0.0011627917, z: -0.0026999994} + m_LocalScale: {x: 1, y: 0.99999994, z: 1} + m_Children: + - {fileID: 6048638457609172120} + m_Father: {fileID: 847897825935598517} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &2620739405153902494 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7509984371715941402} + m_Layer: 0 + m_Name: Barrel_end + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &7509984371715941402 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2620739405153902494} + m_LocalRotation: {x: 0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -0, y: 0.0063666296, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1517159280684637724} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &4300763244710219681 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3234001708628876000} + - component: {fileID: 2715744559599808281} + - component: {fileID: 4300454509241183841} + m_Layer: 0 + m_Name: Recon_Tank + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &3234001708628876000 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4300763244710219681} + m_LocalRotation: {x: -0.7071068, y: 0, z: -0, w: 0.7071067} + m_LocalPosition: {x: -0, y: 0, z: 0} + m_LocalScale: {x: 100, y: 100, z: 100} + m_Children: [] + m_Father: {fileID: 160176456} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!137 &2715744559599808281 +SkinnedMeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4300763244710219681} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 2e67e42170aa64aa9a33424f8045ac89, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + serializedVersion: 2 + m_Quality: 0 + m_UpdateWhenOffscreen: 0 + m_SkinnedMotionVectors: 1 + m_Mesh: {fileID: 4300000, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + m_Bones: + - {fileID: 847897825935598517} + - {fileID: 1703734463393124925} + - {fileID: 7755980514232685276} + - {fileID: 1517159280684637724} + - {fileID: 7124543900430328667} + - {fileID: 1766344861363284577} + - {fileID: 5371032128924763904} + m_BlendShapeWeights: [] + m_RootBone: {fileID: 847897825935598517} + m_AABB: + m_Center: {x: 0, y: 0.0041689305, z: 0.0018957809} + m_Extent: {x: 0.0028734768, y: 0.004266139, z: 0.006842426} + m_DirtyAABB: 0 +--- !u!64 &4300454509241183841 +MeshCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4300763244710219681} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Convex: 0 + m_CookingOptions: 14 + m_Mesh: {fileID: 4300000, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} +--- !u!1 &4728827432125738153 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 847897825935598517} + m_Layer: 0 + m_Name: Root + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &847897825935598517 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4728827432125738153} + m_LocalRotation: {x: 0.7071068, y: 0, z: 0, w: 0.7071067} + m_LocalPosition: {x: -0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1703734463393124925} + - {fileID: 7124543900430328667} + - {fileID: 1766344861363284577} + - {fileID: 5371032128924763904} + m_Father: {fileID: 1042389410631263445} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &5311698857118067376 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7124543900430328667} + m_Layer: 0 + m_Name: Wheel_Front_L + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &7124543900430328667 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5311698857118067376} + m_LocalRotation: {x: -0.5, y: 0.5, z: 0.49999994, w: 0.50000006} + m_LocalPosition: {x: -0, y: 0.0011627917, z: 0.0027000008} + m_LocalScale: {x: 1, y: 0.99999994, z: 1} + m_Children: + - {fileID: 5752532462053122769} + m_Father: {fileID: 847897825935598517} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &5804173475777962202 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1703734463393124925} + m_Layer: 0 + m_Name: Chasis + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1703734463393124925 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5804173475777962202} + m_LocalRotation: {x: 0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -0, y: 0.0015, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 7755980514232685276} + m_Father: {fileID: 847897825935598517} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &6536093484198670798 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1517159280684637724} + m_Layer: 0 + m_Name: Barrel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1517159280684637724 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6536093484198670798} + m_LocalRotation: {x: 0.00000017845065, y: 0.7071068, z: 0.7071067, w: 0.000000009863265} + m_LocalPosition: {x: 5.6542865e-10, y: 0.0015793034, z: 0.00237158} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 7509984371715941402} + m_Father: {fileID: 7755980514232685276} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &7509875135952387032 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1042389410631263445} + m_Layer: 0 + m_Name: Recon_Tank_Rig + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1042389410631263445 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7509875135952387032} + m_LocalRotation: {x: -0.7071068, y: 0, z: -0, w: 0.7071067} + m_LocalPosition: {x: -0, y: 0, z: 0} + m_LocalScale: {x: 100, y: 100, z: 100} + m_Children: + - {fileID: 847897825935598517} + m_Father: {fileID: 160176456} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &7895955422738415095 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5752532462053122769} + m_Layer: 0 + m_Name: Wheel_Front_L_end + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &5752532462053122769 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7895955422738415095} + m_LocalRotation: {x: 0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -0, y: 0.0021921142, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 7124543900430328667} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &8824818431311294599 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 9163197381092130014} + m_Layer: 0 + m_Name: Wheel_Middle_L_end + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &9163197381092130014 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8824818431311294599} + m_LocalRotation: {x: 0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -0, y: 0.0021921142, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1766344861363284577} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Tank.prefab.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Tank.prefab.meta new file mode 100644 index 0000000..9c53dff --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Prefabs/Tank.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ab222ed73ada1ac4ba2f61e843d7627c +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/README.md b/Assets/Packages/Mirror/Examples/AdditiveScenes/README.md new file mode 100644 index 0000000..203c1d6 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/README.md @@ -0,0 +1,25 @@ +# Additive Scenes Example + +IMPORTANT: Make sure you have a layer in project settings called Player for this example to work well. + +In Build Settings, remove all scenes and add all of the scenes from the Examples\AdditiveScenes\Scenes folder in the following order: + +- MainScene +- SubScene + +Open the MainScene in the Editor and make sure the Sub Scenes list in the Network scene object contains the SubScene scene. This is already setup by default, but if the MainScene was opened and saved before putting the scenes in the Build Settings list, the Sub Scenes list may be cleared accidentally. + +File -> Build and Run + +Start up to 3 built instances: These will all be client players. + +Press Play in the Editor and click LAN Host in the editor +- This will be the host and the 1st player of up to 4. You can also use LAN Server if you prefer. + +Click LAN Client in the built instances. +- WASDQE keys to move & turn your player capsule. +- There are objects in the corners of the scene hidden by Proximity Checkers. +- The big area in the middle is where the subscene will be loaded when you get near the shelter. +- There are also networked objects inside the subscene, also with Proximity Checkers. +- Since subscenes are only loaded for individual clients, other clients that are outside the middle Zone won't see what those in the subscene can see. +- If you play a built instance as Host or Server and play as client in the editor, you'll see the subscene content load and unload in the hierarchy as you move in and out of the middle Zone. diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/README.md.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/README.md.meta new file mode 100644 index 0000000..470c34f --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0a023e0d7315ac74094703ab69348733 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes.meta new file mode 100644 index 0000000..79b44f1 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e989860f377e7764bb7787086ef44ea4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/MainScene.unity b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/MainScene.unity new file mode 100644 index 0000000..ef56d37 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/MainScene.unity @@ -0,0 +1,2105 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0.17276844, g: 0.21589246, b: 0.2978263, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 10 + m_Resolution: 2 + m_BakeResolution: 10 + m_AtlasSize: 512 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 0 + m_BakeBackend: 0 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 256 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 112000004, guid: b287b2046ddc6af4b9ddc48ab35ca3cb, + type: 2} + m_UseShadowmask: 0 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &34755345 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 34755346} + - component: {fileID: 34755348} + - component: {fileID: 34755347} + m_Layer: 0 + m_Name: VisibleRangeCapsule + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &34755346 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 34755345} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 20, y: 1, z: -20} + m_LocalScale: {x: 10, y: 10, z: 10} + m_Children: [] + m_Father: {fileID: 47225731} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &34755347 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 34755345} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: a7c679cf124f7ae46a0291ea35848554, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &34755348 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 34755345} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &47225730 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 47225731} + m_Layer: 0 + m_Name: ProximityVisualizers + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &47225731 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 47225730} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1727677799} + - {fileID: 62078680} + - {fileID: 34755346} + - {fileID: 589935541} + m_Father: {fileID: 909502395} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &62078679 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 62078680} + - component: {fileID: 62078682} + - component: {fileID: 62078681} + m_Layer: 0 + m_Name: VisibleRangeCylinder + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &62078680 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 62078679} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 20, y: 1, z: 20} + m_LocalScale: {x: 10, y: 10, z: 10} + m_Children: [] + m_Father: {fileID: 47225731} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &62078681 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 62078679} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: a7c679cf124f7ae46a0291ea35848554, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &62078682 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 62078679} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &159607907 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 159607911} + - component: {fileID: 159607908} + - component: {fileID: 159607912} + - component: {fileID: 159607913} + m_Layer: 9 + m_Name: Zone + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!135 &159607908 +SphereCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 159607907} + m_Material: {fileID: 0} + m_IsTrigger: 1 + m_Enabled: 1 + serializedVersion: 2 + m_Radius: 15 + m_Center: {x: 0, y: 0, z: 0} +--- !u!4 &159607911 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 159607907} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 6 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &159607912 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 159607907} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + serverOnly: 1 + localPlayerAuthority: 0 + m_AssetId: + m_SceneId: 1834901131 +--- !u!114 &159607913 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 159607907} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 884ed76587eb5854abe6b428b791fdcd, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + subScene: SubScene +--- !u!1001 &160176455 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 909502395} + m_Modifications: + - target: {fileID: 160176457, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_Name + value: reconTank + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalPosition.x + value: -20 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalPosition.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalPosition.z + value: -20 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalRotation.y + value: 0.38268343 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalRotation.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalRotation.w + value: 0.92387956 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_RootOrder + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 45 + objectReference: {fileID: 0} + - target: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 160176459, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_AssetId + value: ab222ed73ada1ac4ba2f61e843d7627c + objectReference: {fileID: 0} + - target: {fileID: 160176459, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_SceneId + value: 705590806 + objectReference: {fileID: 0} + - target: {fileID: 160176459, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + propertyPath: m_LocalPlayerAuthority + value: 0 + objectReference: {fileID: 0} + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} +--- !u!4 &160176456 stripped +Transform: + m_CorrespondingSourceObject: {fileID: 160176456, guid: ab222ed73ada1ac4ba2f61e843d7627c, + type: 3} + m_PrefabInstance: {fileID: 160176455} + m_PrefabAsset: {fileID: 0} +--- !u!1 &178547537 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 178547538} + - component: {fileID: 178547539} + m_Layer: 0 + m_Name: StartPos + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &178547538 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 178547537} + m_LocalRotation: {x: 0, y: 1, z: 0, w: 0} + m_LocalPosition: {x: 0, y: 1.08, z: 20} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1172568542} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0} +--- !u!114 &178547539 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 178547537} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &534669902 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 534669905} + - component: {fileID: 534669904} + - component: {fileID: 534669903} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &534669903 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 534669902} + m_Enabled: 1 +--- !u!20 &534669904 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 534669902} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_projectionMatrixMode: 1 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_GateFitMode: 2 + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &534669905 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 534669902} + m_LocalRotation: {x: 0.7071068, y: 0, z: 0, w: 0.7071068} + m_LocalPosition: {x: 0, y: 50, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0} +--- !u!1 &589935540 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 589935541} + - component: {fileID: 589935543} + - component: {fileID: 589935542} + m_Layer: 0 + m_Name: VisibleRangeTank + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &589935541 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 589935540} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -20, y: 1, z: -20} + m_LocalScale: {x: 20, y: 20, z: 20} + m_Children: [] + m_Father: {fileID: 47225731} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &589935542 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 589935540} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: a7c679cf124f7ae46a0291ea35848554, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &589935543 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 589935540} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &612284967 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 612284968} + - component: {fileID: 612284971} + - component: {fileID: 612284970} + - component: {fileID: 612284969} + m_Layer: 0 + m_Name: Pillar + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &612284968 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 612284967} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 8, y: 3, z: -8} + m_LocalScale: {x: 1, y: 3, z: 1} + m_Children: [] + m_Father: {fileID: 1608696205} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!136 &612284969 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 612284967} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5000001 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0.000000059604645, y: 0, z: -0.00000008940697} +--- !u!23 &612284970 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 612284967} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: aef230244d219314fb8453f0365b8176, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &612284971 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 612284967} + m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &652875644 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 652875645} + - component: {fileID: 652875646} + m_Layer: 0 + m_Name: StartPos + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &652875645 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 652875644} + m_LocalRotation: {x: 0, y: 0.7071068, z: -0, w: -0.7071068} + m_LocalPosition: {x: 20, y: 1.08, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1172568542} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 270, z: 0} +--- !u!114 &652875646 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 652875644} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &691846569 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 691846570} + - component: {fileID: 691846571} + m_Layer: 0 + m_Name: StartPos + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &691846570 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 691846569} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1.08, z: -20} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1172568542} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &691846571 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 691846569} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1001 &748207074 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 909502395} + m_Modifications: + - target: {fileID: 855244094988030905, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_Name + value: Sphere + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalPosition.x + value: -20 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalPosition.y + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalPosition.z + value: 20 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalRotation.y + value: 0.92387956 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalRotation.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalRotation.w + value: 0.38268343 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_RootOrder + value: 2 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 135 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030911, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_AssetId + value: f6d08eb9a8e35d84fa30a7e3ae64181a + objectReference: {fileID: 0} + - target: {fileID: 855244094988030911, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_SceneId + value: 529586728 + objectReference: {fileID: 0} + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, type: 3} +--- !u!4 &748207075 stripped +Transform: + m_CorrespondingSourceObject: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + m_PrefabInstance: {fileID: 748207074} + m_PrefabAsset: {fileID: 0} +--- !u!1 &794922164 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 794922165} + - component: {fileID: 794922168} + - component: {fileID: 794922167} + - component: {fileID: 794922166} + m_Layer: 0 + m_Name: Roof + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &794922165 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 794922164} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 6, z: 0} + m_LocalScale: {x: 20, y: 0.2, z: 20} + m_Children: [] + m_Father: {fileID: 1608696205} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!65 &794922166 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 794922164} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!23 &794922167 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 794922164} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: aef230244d219314fb8453f0365b8176, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &794922168 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 794922164} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &856402103 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 856402104} + - component: {fileID: 856402107} + - component: {fileID: 856402106} + - component: {fileID: 856402105} + m_Layer: 0 + m_Name: Pillar + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &856402104 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 856402103} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -8, y: 3, z: 8} + m_LocalScale: {x: 1, y: 3, z: 1} + m_Children: [] + m_Father: {fileID: 1608696205} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!136 &856402105 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 856402103} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5000001 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0.000000059604645, y: 0, z: -0.00000008940697} +--- !u!23 &856402106 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 856402103} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: aef230244d219314fb8453f0365b8176, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &856402107 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 856402103} + m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1001 &901271862 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 909502395} + m_Modifications: + - target: {fileID: 6852530814182375312, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_Name + value: Cylinder + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalPosition.x + value: 20 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalPosition.y + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalPosition.z + value: 20 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalRotation.y + value: 0.9238796 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalRotation.z + value: -0 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalRotation.w + value: -0.38268325 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_RootOrder + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 225 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375318, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_SceneId + value: 568164022 + objectReference: {fileID: 0} + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: 12a4c14e672c00b4b840f937d824b890, type: 3} +--- !u!4 &901271863 stripped +Transform: + m_CorrespondingSourceObject: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + m_PrefabInstance: {fileID: 901271862} + m_PrefabAsset: {fileID: 0} +--- !u!1 &909502394 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 909502395} + m_Layer: 0 + m_Name: Prefabs + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &909502395 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 909502394} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 160176456} + - {fileID: 901271863} + - {fileID: 748207075} + - {fileID: 1284471874} + - {fileID: 47225731} + m_Father: {fileID: 0} + m_RootOrder: 8 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1047741290 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1047741291} + - component: {fileID: 1047741294} + - component: {fileID: 1047741293} + - component: {fileID: 1047741292} + m_Layer: 0 + m_Name: Pillar + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &1047741291 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1047741290} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -8, y: 3, z: -8} + m_LocalScale: {x: 1, y: 3, z: 1} + m_Children: [] + m_Father: {fileID: 1608696205} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!136 &1047741292 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1047741290} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5000001 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0.000000059604645, y: 0, z: -0.00000008940697} +--- !u!23 &1047741293 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1047741290} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: aef230244d219314fb8453f0365b8176, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &1047741294 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1047741290} + m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1172568541 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1172568542} + m_Layer: 0 + m_Name: StartPositions + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &1172568542 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1172568541} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 178547538} + - {fileID: 1816951100} + - {fileID: 652875645} + - {fileID: 691846570} + m_Father: {fileID: 0} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!4 &1284471874 stripped +Transform: + m_CorrespondingSourceObject: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + m_PrefabInstance: {fileID: 1076878375580925077} + m_PrefabAsset: {fileID: 0} +--- !u!1 &1405375878 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1405375880} + - component: {fileID: 1405375879} + m_Layer: 0 + m_Name: Directional Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &1405375879 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1405375878} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 1 + m_Color: {r: 0.9622642, g: 0.90969414, b: 0.748932, a: 1} + m_Intensity: 0.8 + m_Range: 10 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 0.5 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &1405375880 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1405375878} + m_LocalRotation: {x: 0.7071068, y: 0, z: 0, w: 0.7071068} + m_LocalPosition: {x: 0, y: 1, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0} +--- !u!1 &1461518024 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1461518032} + - component: {fileID: 1461518031} + - component: {fileID: 1461518030} + - component: {fileID: 1461518029} + - component: {fileID: 1461518028} + - component: {fileID: 1461518027} + - component: {fileID: 1461518026} + - component: {fileID: 1461518025} + m_Layer: 0 + m_Name: Quad + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!65 &1461518025 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1461518024} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 0.01, z: 3} + m_Center: {x: 0, y: -0.5, z: -1.5} +--- !u!65 &1461518026 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1461518024} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 0.01, z: 3} + m_Center: {x: 0, y: 0.5, z: -1.5} +--- !u!65 &1461518027 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1461518024} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 0.01, y: 1, z: 3} + m_Center: {x: 0.5, y: 0, z: -1.5} +--- !u!65 &1461518028 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1461518024} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 0.01, y: 1, z: 3} + m_Center: {x: -0.5, y: 0, z: -1.5} +--- !u!64 &1461518029 +MeshCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1461518024} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Convex: 0 + m_CookingOptions: 14 + m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &1461518030 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1461518024} + m_Enabled: 1 + m_CastShadows: 0 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 6eb3f3ba66756364d8b94e662e7e8af5, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &1461518031 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1461518024} + m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1461518032 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1461518024} + m_LocalRotation: {x: 0.7071068, y: 0, z: 0, w: 0.7071068} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 50, y: 50, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0} +--- !u!1 &1462312433 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1462312434} + - component: {fileID: 1462312437} + - component: {fileID: 1462312436} + - component: {fileID: 1462312435} + m_Layer: 0 + m_Name: Pillar + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &1462312434 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1462312433} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 8, y: 3, z: 8} + m_LocalScale: {x: 1, y: 3, z: 1} + m_Children: [] + m_Father: {fileID: 1608696205} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!136 &1462312435 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1462312433} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5000001 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0.000000059604645, y: 0, z: -0.00000008940697} +--- !u!23 &1462312436 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1462312433} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: aef230244d219314fb8453f0365b8176, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &1462312437 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1462312433} + m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1608696204 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1608696205} + m_Layer: 0 + m_Name: Shelter + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &1608696205 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1608696204} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1047741291} + - {fileID: 612284968} + - {fileID: 1462312434} + - {fileID: 856402104} + - {fileID: 794922165} + m_Father: {fileID: 0} + m_RootOrder: 5 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1630383476 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1630383479} + - component: {fileID: 1630383478} + - component: {fileID: 1630383477} + m_Layer: 0 + m_Name: ZoneVisualizer + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!23 &1630383477 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1630383476} + m_Enabled: 1 + m_CastShadows: 0 + m_ReceiveShadows: 0 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 0 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: a7c679cf124f7ae46a0291ea35848554, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &1630383478 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1630383476} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1630383479 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1630383476} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 30, y: 30, z: 30} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 7 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1661834277 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1661834279} + - component: {fileID: 1661834281} + - component: {fileID: 1661834278} + - component: {fileID: 1661834280} + m_Layer: 0 + m_Name: Network + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!114 &1661834278 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1661834277} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 34d1daf9e7dbcb64aa647cb332054ea6, type: 3} + m_Name: + m_EditorClassIdentifier: + dontDestroyOnLoad: 0 + runInBackground: 1 + startOnHeadless: 1 + serverTickRate: 30 + showDebugMessages: 0 + offlineScene: + onlineScene: + transport: {fileID: 1661834280} + networkAddress: localhost + maxConnections: 4 + playerPrefab: {fileID: 8872462076811691049, guid: a5bdca0a2315d43499be7dcef473fbc7, + type: 3} + autoCreatePlayer: 1 + playerSpawnMethod: 1 + spawnPrefabs: + - {fileID: 1076878374699499732, guid: e1971f4a8c7661546bc509b44bd91b80, type: 3} + - {fileID: 5623359707189648430, guid: 4ff300cf6bb3c6342a9552c4f18788c8, type: 3} + - {fileID: 6852530814182375312, guid: 12a4c14e672c00b4b840f937d824b890, type: 3} + - {fileID: 855244094988030905, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, type: 3} + - {fileID: 160176457, guid: ab222ed73ada1ac4ba2f61e843d7627c, type: 3} + subScenes: + - SubScene +--- !u!4 &1661834279 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1661834277} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1661834280 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1661834277} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c7424c1070fad4ba2a7a96b02fbeb4bb, type: 3} + m_Name: + m_EditorClassIdentifier: + OnClientConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnClientDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventArraySegment, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnServerConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + OnServerDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntArraySegment, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + port: 7777 + NoDelay: 1 + serverMaxMessageSize: 16384 + clientMaxMessageSize: 16384 +--- !u!114 &1661834281 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1661834277} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 6442dc8070ceb41f094e44de0bf87274, type: 3} + m_Name: + m_EditorClassIdentifier: + showGUI: 1 + offsetX: 0 + offsetY: 0 +--- !u!1 &1727677796 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1727677799} + - component: {fileID: 1727677798} + - component: {fileID: 1727677797} + m_Layer: 0 + m_Name: VisibleRangeSphere + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!23 &1727677797 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1727677796} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: a7c679cf124f7ae46a0291ea35848554, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &1727677798 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1727677796} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1727677799 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1727677796} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -20, y: 1, z: 20} + m_LocalScale: {x: 10, y: 10, z: 10} + m_Children: [] + m_Father: {fileID: 47225731} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1816951099 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1816951100} + - component: {fileID: 1816951101} + m_Layer: 0 + m_Name: StartPos + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &1816951100 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1816951099} + m_LocalRotation: {x: 0, y: 0.7071068, z: 0, w: 0.7071068} + m_LocalPosition: {x: -20, y: 1.08, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1172568542} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 90, z: 0} +--- !u!114 &1816951101 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1816951099} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1001 &1076878375580925077 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 909502395} + m_Modifications: + - target: {fileID: 1076878374699499732, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_Name + value: Capsule + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499732, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_StaticEditorFlags + value: 4294967295 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalPosition.x + value: 20 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalPosition.y + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalPosition.z + value: -20 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalRotation.y + value: 0.3826836 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalRotation.z + value: -0 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalRotation.w + value: -0.92387944 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_RootOrder + value: 3 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 315 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 2648107611936813301, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_SceneId + value: 2061538488 + objectReference: {fileID: 0} + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: e1971f4a8c7661546bc509b44bd91b80, type: 3} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/MainScene.unity.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/MainScene.unity.meta new file mode 100644 index 0000000..a231750 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/MainScene.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7a0eee2f518e9dc4fb628d96dc452faf +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/SubScene.unity b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/SubScene.unity new file mode 100644 index 0000000..0e8971a --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/SubScene.unity @@ -0,0 +1,793 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0.12731749, g: 0.13414757, b: 0.1210787, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 10 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 112000002, guid: b287b2046ddc6af4b9ddc48ab35ca3cb, + type: 2} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &21610633 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 21610634} + - component: {fileID: 21610636} + - component: {fileID: 21610635} + m_Layer: 0 + m_Name: VisibleRange + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &21610634 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 21610633} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 3, y: 1, z: -3} + m_LocalScale: {x: 10, y: 10, z: 10} + m_Children: [] + m_Father: {fileID: 1690140971} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &21610635 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 21610633} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: a7c679cf124f7ae46a0291ea35848554, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &21610636 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 21610633} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1001 &174598777 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: + - target: {fileID: 1076878374699499732, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_Name + value: Capsule + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499732, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_StaticEditorFlags + value: 4294967295 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalPosition.x + value: 3 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalPosition.y + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalPosition.z + value: -3 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalRotation.y + value: 0.92387956 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalRotation.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalRotation.w + value: 0.38268343 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_RootOrder + value: 3 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 135 + objectReference: {fileID: 0} + - target: {fileID: 1076878374699499735, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 2648107611936813301, guid: e1971f4a8c7661546bc509b44bd91b80, + type: 3} + propertyPath: m_SceneId + value: 15452677 + objectReference: {fileID: 0} + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: e1971f4a8c7661546bc509b44bd91b80, type: 3} +--- !u!1 &222935521 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 222935522} + - component: {fileID: 222935524} + - component: {fileID: 222935523} + m_Layer: 0 + m_Name: VisibleRange + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &222935522 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 222935521} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -3, y: 1, z: 3} + m_LocalScale: {x: 10, y: 10, z: 10} + m_Children: [] + m_Father: {fileID: 1690140971} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &222935523 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 222935521} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: a7c679cf124f7ae46a0291ea35848554, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &222935524 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 222935521} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &507729669 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 507729670} + - component: {fileID: 507729672} + - component: {fileID: 507729671} + m_Layer: 0 + m_Name: VisibleRange + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &507729670 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 507729669} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 3, y: 1, z: 3} + m_LocalScale: {x: 10, y: 10, z: 10} + m_Children: [] + m_Father: {fileID: 1690140971} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &507729671 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 507729669} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: a7c679cf124f7ae46a0291ea35848554, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &507729672 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 507729669} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &1690140970 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1690140971} + m_Layer: 0 + m_Name: ProximityVisualizers + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &1690140971 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1690140970} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1722279649} + - {fileID: 222935522} + - {fileID: 507729670} + - {fileID: 21610634} + m_Father: {fileID: 0} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1722279648 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1722279649} + - component: {fileID: 1722279651} + - component: {fileID: 1722279650} + m_Layer: 0 + m_Name: VisibleRange + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &1722279649 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1722279648} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -3, y: 1, z: -3} + m_LocalScale: {x: 10, y: 10, z: 10} + m_Children: [] + m_Father: {fileID: 1690140971} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &1722279650 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1722279648} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: a7c679cf124f7ae46a0291ea35848554, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &1722279651 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1722279648} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1001 &855244095324068329 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: + - target: {fileID: 855244094988030905, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_Name + value: Sphere + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalPosition.x + value: -3 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalPosition.y + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalPosition.z + value: 3 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalRotation.y + value: 0.3826836 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalRotation.z + value: -0 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalRotation.w + value: -0.92387944 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_RootOrder + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 315 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030909, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 855244094988030911, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_SceneId + value: 11893259 + objectReference: {fileID: 0} + - target: {fileID: 855244096231524078, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_CastShadows + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 855244096231524078, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_ReceiveShadows + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 855244096231524078, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, + type: 3} + propertyPath: m_ReflectionProbeUsage + value: 0 + objectReference: {fileID: 0} + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: f6d08eb9a8e35d84fa30a7e3ae64181a, type: 3} +--- !u!1001 &5623359707641229621 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: + - target: {fileID: 5623359707189648430, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_Name + value: Cube + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalPosition.x + value: -3 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalPosition.y + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalPosition.z + value: -3 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalRotation.y + value: 0.9238796 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalRotation.z + value: -0 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalRotation.w + value: -0.38268325 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_RootOrder + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 225 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648426, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 5623359707189648404, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_SceneId + value: 4733130 + objectReference: {fileID: 0} + - target: {fileID: 5623359706949397433, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_CastShadows + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 5623359706949397433, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_ReceiveShadows + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 5623359706949397433, guid: 4ff300cf6bb3c6342a9552c4f18788c8, + type: 3} + propertyPath: m_ReflectionProbeUsage + value: 0 + objectReference: {fileID: 0} + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: 4ff300cf6bb3c6342a9552c4f18788c8, type: 3} +--- !u!1001 &6852530815080958608 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: + - target: {fileID: 6852530814182375312, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_Name + value: Cylinder + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalPosition.x + value: 3 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalPosition.y + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalPosition.z + value: 3 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalRotation.y + value: 0.38268343 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalRotation.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalRotation.w + value: 0.92387956 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_RootOrder + value: 2 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 45 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375316, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375318, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_AssetId + value: 12a4c14e672c00b4b840f937d824b890 + objectReference: {fileID: 0} + - target: {fileID: 6852530814182375318, guid: 12a4c14e672c00b4b840f937d824b890, + type: 3} + propertyPath: m_SceneId + value: 4633990 + objectReference: {fileID: 0} + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: 12a4c14e672c00b4b840f937d824b890, type: 3} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/SubScene.unity.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/SubScene.unity.meta new file mode 100644 index 0000000..94a2050 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scenes/SubScene.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7f4fd683fc6d866418c95f99977533a6 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts.meta new file mode 100644 index 0000000..cb97b32 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f9c36b0deb5d9b245b7c97e3d6eeed29 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/AdditiveNetworkManager.cs b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/AdditiveNetworkManager.cs new file mode 100644 index 0000000..14f061d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/AdditiveNetworkManager.cs @@ -0,0 +1,55 @@ +using UnityEngine; +using System.Collections; +using UnityEngine.SceneManagement; + +namespace Mirror.Examples.Additive +{ + public class AdditiveNetworkManager : NetworkManager + { + [Scene] + [Tooltip("Add all sub-scenes to this list")] + public string[] subScenes; + + public override void OnStartServer() + { + base.OnStartServer(); + Debug.Log("Loading Scenes"); + + // load all subscenes on the server only + foreach (string sceneName in subScenes) + { + SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); + Debug.LogFormat("Loaded {0}", sceneName); + } + } + + public override void OnStopServer() + { + Debug.Log("Stopping Server"); + base.OnStopServer(); + UnloadScenes(); + } + + public override void OnStopClient() + { + Debug.Log("Stopping Client"); + base.OnStopClient(); + UnloadScenes(); + } + + void UnloadScenes() + { + Debug.Log("Unloading Scenes"); + foreach (string sceneName in subScenes) + if (SceneManager.GetSceneByName(sceneName).IsValid()) + StartCoroutine(UnloadScene(sceneName)); + } + + IEnumerator UnloadScene(string sceneName) + { + yield return SceneManager.UnloadSceneAsync(sceneName); + yield return Resources.UnloadUnusedAssets(); + Debug.LogFormat("Unloaded {0}", sceneName); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/AdditiveNetworkManager.cs.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/AdditiveNetworkManager.cs.meta new file mode 100644 index 0000000..0df3fb3 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/AdditiveNetworkManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 34d1daf9e7dbcb64aa647cb332054ea6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/PlayerController.cs b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/PlayerController.cs new file mode 100644 index 0000000..7a5c4f5 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/PlayerController.cs @@ -0,0 +1,121 @@ +using UnityEngine; + +namespace Mirror.Examples.Additive +{ + [RequireComponent(typeof(CharacterController))] + public class PlayerController : NetworkBehaviour + { + public override void OnStartServer() + { + base.OnStartServer(); + playerColor = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); + } + + [SyncVar(hook = nameof(SetColor))] + Color playerColor = Color.black; + + // Unity clones the material when GetComponent().material is called + // Cache it here and destroy it in OnDestroy to prevent a memory leak + Material cachedMaterial; + + void SetColor(Color color) + { + if (cachedMaterial == null) cachedMaterial = GetComponent().material; + cachedMaterial.color = color; + } + + void OnDisable() + { + if (isLocalPlayer) + { + Camera.main.transform.SetParent(null); + Camera.main.transform.localPosition = new Vector3(0f, 50f, 0f); + Camera.main.transform.localEulerAngles = new Vector3(90f, 0f, 0f); + } + } + + void OnDestroy() + { + Destroy(cachedMaterial); + } + + CharacterController characterController; + + public override void OnStartLocalPlayer() + { + base.OnStartLocalPlayer(); + + characterController = GetComponent(); + + Camera.main.transform.SetParent(transform); + Camera.main.transform.localPosition = new Vector3(0f, 3f, -8f); + Camera.main.transform.localEulerAngles = new Vector3(10f, 0f, 0f); + } + + [Header("Movement Settings")] + public float moveSpeed = 8f; + public float turnSpeedAccel = 5f; + public float turnSpeedDecel = 5f; + public float maxTurnSpeed = 150f; + + [Header("Jump Settings")] + public float jumpSpeed = 0f; + public float maxJumpSpeed = 5F; + public float jumpFactor = .05F; + + [Header("Diagnostics")] + public float horizontal = 0f; + public float vertical = 0f; + public float turn = 0f; + public bool isGrounded = true; + public bool isFalling = false; + + void Update() + { + if (!isLocalPlayer) return; + + horizontal = Input.GetAxis("Horizontal"); + vertical = Input.GetAxis("Vertical"); + + if (Input.GetKey(KeyCode.Q) && (turn > -maxTurnSpeed)) + turn -= turnSpeedAccel; + else if (Input.GetKey(KeyCode.E) && (turn < maxTurnSpeed)) + turn += turnSpeedAccel; + else if (turn > turnSpeedDecel) + turn -= turnSpeedDecel; + else if (turn < -turnSpeedDecel) + turn += turnSpeedDecel; + else + turn = 0f; + + if (!isFalling && Input.GetKey(KeyCode.Space) && (isGrounded || jumpSpeed < maxJumpSpeed)) + jumpSpeed += maxJumpSpeed * jumpFactor; + else if (isGrounded) + isFalling = false; + else + { + isFalling = true; + jumpSpeed = 0; + } + } + + void FixedUpdate() + { + if (!isLocalPlayer || characterController == null) return; + + transform.Rotate(0f, turn * Time.fixedDeltaTime, 0f); + + Vector3 direction = new Vector3(horizontal, jumpSpeed, vertical); + direction = Vector3.ClampMagnitude(direction, 1f); + direction = transform.TransformDirection(direction); + direction *= moveSpeed; + + if (jumpSpeed > 0) + characterController.Move(direction * Time.fixedDeltaTime); + else + characterController.SimpleMove(direction); + + isGrounded = characterController.isGrounded; + } + } +} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/PlayerController.cs.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/PlayerController.cs.meta new file mode 100644 index 0000000..5deced6 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/PlayerController.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e8f68561248aaca4fb96847ce24742ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/SceneLoader.cs b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/SceneLoader.cs new file mode 100644 index 0000000..64b1920 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/SceneLoader.cs @@ -0,0 +1,56 @@ +using UnityEngine; +using System.Collections; +using UnityEngine.SceneManagement; + +namespace Mirror.Examples.Additive +{ + // This script is attached to the player prefab + public class SceneLoader : NetworkBehaviour + { + public enum LoadAction + { + Load, + Unload + } + + // Tell the client to load a single subscene + // This is called from ZoneHandler's server-only OnTrigger events + [TargetRpc] + public void TargetLoadUnloadScene(NetworkConnection networkConnection, string sceneName, LoadAction loadAction) + { + // Check if server here because we already pre-loaded the subscenes on the server + if (!isServer) StartCoroutine(LoadUnloadScene(sceneName, loadAction)); + } + + // isBusy protects us from being overwhelmed by server messages to load several subscenes at once. + bool isBusy = false; + + IEnumerator LoadUnloadScene(string sceneName, LoadAction loadAction) + { + while (isBusy) yield return null; + + isBusy = true; + + if (loadAction == LoadAction.Load) + yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); + else + { + yield return SceneManager.UnloadSceneAsync(sceneName); + yield return Resources.UnloadUnusedAssets(); + } + + isBusy = false; + Debug.LogFormat("{0} {1} Done", sceneName, loadAction.ToString()); + + CmdSceneDone(sceneName, loadAction); + } + + [Command] + public void CmdSceneDone(string sceneName, LoadAction loadAction) + { + // The point of this is to show the client telling server it has loaded the subscene + // so the server might take some further action, e.g. reposition the player. + Debug.LogFormat("{0} {1} done on client", sceneName, loadAction.ToString()); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/SceneLoader.cs.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/SceneLoader.cs.meta new file mode 100644 index 0000000..06c71d9 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/SceneLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2925d2020e4083646acf0ba4f4a06858 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ShootingTankBehaviour.cs b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ShootingTankBehaviour.cs new file mode 100644 index 0000000..c547a7a --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ShootingTankBehaviour.cs @@ -0,0 +1,59 @@ +using UnityEngine; + +namespace Mirror.Examples.Additive +{ + // This script demonstrates the NetworkAnimator and how to leverage + // the built-in observers system to track players. + // Note that all ProximityCheckers should be restricted to the Player layer. + public class ShootingTankBehaviour : NetworkBehaviour + { + [SyncVar] + public Quaternion rotation; + + NetworkAnimator networkAnimator; + + [ServerCallback] + void Start() + { + networkAnimator = GetComponent(); + } + + [Range(0, 1)] + public float turnSpeed = 0.1f; + + void Update() + { + if (isServer && netIdentity.observers.Count > 0) + ShootNearestPlayer(); + + if (isClient) + transform.rotation = Quaternion.Slerp(transform.rotation, rotation, turnSpeed); + } + + [Server] + void ShootNearestPlayer() + { + GameObject target = null; + float distance = 100f; + + foreach (NetworkConnection networkConnection in netIdentity.observers.Values) + { + GameObject tempTarget = networkConnection.playerController.gameObject; + float tempDistance = Vector3.Distance(tempTarget.transform.position, transform.position); + + if (target == null || distance > tempDistance) + { + target = tempTarget; + distance = tempDistance; + } + } + + if (target != null) + { + transform.LookAt(target.transform.position + Vector3.down); + rotation = transform.rotation; + networkAnimator.SetTrigger("Fire"); + } + } + } +} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ShootingTankBehaviour.cs.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ShootingTankBehaviour.cs.meta new file mode 100644 index 0000000..90771ab --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ShootingTankBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a25c54cd35eb284eb6b8ed19cf60443 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ZoneHandler.cs b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ZoneHandler.cs new file mode 100644 index 0000000..72d7e79 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ZoneHandler.cs @@ -0,0 +1,46 @@ +using UnityEngine; + +namespace Mirror.Examples.Additive +{ + // This script is attached to a scene object called Zone that is on the Player layer and has: + // - Sphere Collider with isTrigger = true + // - Network Identity with Server Only checked + // These OnTrigger events only run on the server and will only send a message to the player + // that entered the Zone to load the subscene assigned to the subscene property. + public class ZoneHandler : NetworkBehaviour + { + [Scene] + [Tooltip("Assign the sub-scene to load for this zone")] + public string subScene; + + [Server] + void OnTriggerEnter(Collider other) + { + Debug.LogFormat("Loading {0}", subScene); + + // Get a reference to the SceneLoader component on the player prefab + SceneLoader sceneLoader = other.gameObject.GetComponent(); + + NetworkIdentity networkIdentity = other.gameObject.GetComponent(); + + // One or both of these might be null if you don't have Layers set up properly + if (sceneLoader != null && networkIdentity != null) + sceneLoader.TargetLoadUnloadScene(networkIdentity.connectionToClient, subScene, SceneLoader.LoadAction.Load); + } + + [Server] + void OnTriggerExit(Collider other) + { + Debug.LogFormat("Unloading {0}", subScene); + + // Get a reference to the SceneLoader component on the player prefab + SceneLoader sceneLoader = other.gameObject.GetComponent(); + + NetworkIdentity networkIdentity = other.gameObject.GetComponent(); + + // One or both of these might be null if you don't have Layers set up properly + if (sceneLoader != null && networkIdentity != null) + sceneLoader.TargetLoadUnloadScene(networkIdentity.connectionToClient, subScene, SceneLoader.LoadAction.Unload); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ZoneHandler.cs.meta b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ZoneHandler.cs.meta new file mode 100644 index 0000000..126d072 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/AdditiveScenes/Scripts/ZoneHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 884ed76587eb5854abe6b428b791fdcd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Basic.meta b/Assets/Packages/Mirror/Examples/Basic.meta new file mode 100644 index 0000000..653ea78 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0ea49fcefbc864e19a94091a170fc06c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Basic/Prefabs.meta b/Assets/Packages/Mirror/Examples/Basic/Prefabs.meta new file mode 100644 index 0000000..234c22a --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/Prefabs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4f821a97809492a479cac0843442e245 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Basic/Prefabs/Player.prefab b/Assets/Packages/Mirror/Examples/Basic/Prefabs/Player.prefab new file mode 100644 index 0000000..db613d0 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/Prefabs/Player.prefab @@ -0,0 +1,271 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &1088833922664441133 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1088833922664441134} + - component: {fileID: 1088833922664441128} + - component: {fileID: 1088833922664441135} + m_Layer: 5 + m_Name: PlayerNameText + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1088833922664441134 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833922664441133} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1088833923132447023} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 0, y: 1} + m_AnchoredPosition: {x: 60, y: -15} + m_SizeDelta: {x: 120, y: 30} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &1088833922664441128 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833922664441133} + m_CullTransparentMesh: 0 +--- !u!114 &1088833922664441135 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833922664441133} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 0 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 22 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 2 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 1 + m_VerticalOverflow: 1 + m_LineSpacing: 1 + m_Text: Player 00 +--- !u!1 &1088833923132447022 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1088833923132447023} + - component: {fileID: 1088833923132446996} + - component: {fileID: 1088833923132447019} + - component: {fileID: 1088833923132447017} + - component: {fileID: 1088833923132447018} + m_Layer: 5 + m_Name: Player + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1088833923132447023 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833923132447022} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1088833922664441134} + - {fileID: 1088833924003616757} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 0, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 120, y: 60} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &1088833923132446996 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833923132447022} + m_CullTransparentMesh: 0 +--- !u!114 &1088833923132447019 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833923132447022} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0, g: 0, b: 0, a: 0} + m_RaycastTarget: 0 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!114 &1088833923132447017 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833923132447022} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: a472ac3ae1701d149861871cf416a46d, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + rectTransform: {fileID: 1088833923132447023} + image: {fileID: 1088833923132447019} + playerNameText: {fileID: 1088833922664441135} + playerDataText: {fileID: 1088833924003616759} +--- !u!114 &1088833923132447018 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833923132447022} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + serverOnly: 0 + localPlayerAuthority: 0 + m_AssetId: 22f1fa3a0aff72b46a371f667bb4fb30 + m_SceneId: 0 +--- !u!1 &1088833924003616756 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1088833924003616757} + - component: {fileID: 1088833924003616752} + - component: {fileID: 1088833924003616759} + m_Layer: 5 + m_Name: PlayerDataText + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1088833924003616757 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833924003616756} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1088833923132447023} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 0, y: 1} + m_AnchoredPosition: {x: 60, y: -45} + m_SizeDelta: {x: 120, y: 30} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &1088833924003616752 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833924003616756} + m_CullTransparentMesh: 0 +--- !u!114 &1088833924003616759 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1088833924003616756} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 0 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 22 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 2 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 1 + m_VerticalOverflow: 1 + m_LineSpacing: 1 + m_Text: 'Data: 000' diff --git a/Assets/Packages/Mirror/Examples/Basic/Prefabs/Player.prefab.meta b/Assets/Packages/Mirror/Examples/Basic/Prefabs/Player.prefab.meta new file mode 100644 index 0000000..c6a8284 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/Prefabs/Player.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 22f1fa3a0aff72b46a371f667bb4fb30 +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Basic/README.md b/Assets/Packages/Mirror/Examples/Basic/README.md new file mode 100644 index 0000000..3bde055 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/README.md @@ -0,0 +1,16 @@ +# Basic Example + +This is a bare bones example of a running game with Network Manager and UI prefab players: + +1. Remove all scenes from Build Settings, then add the Example scene alone. + +2. Open the Example scene and build the project. + +3. In the editor, click Play, and LAN Host or LAN Server...it will be listening on port 7777. + - If you clicked LAN Host, the host player will appear as Player 00. + +4. Run one or more instances (up to 16 total players) of the built application. + +5. Click LAN Client on each instance. + +6. Now you will see all players in the editor and the clients, all with data being updated and synchronized. diff --git a/Assets/Packages/Mirror/Examples/Basic/README.md.meta b/Assets/Packages/Mirror/Examples/Basic/README.md.meta new file mode 100644 index 0000000..d4e1715 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 67177defd4d334a549e535f10506cc66 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Basic/Scenes.meta b/Assets/Packages/Mirror/Examples/Basic/Scenes.meta new file mode 100644 index 0000000..0c751c6 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/Scenes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 16f46473489d3364badc2f37c4db8634 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Basic/Scenes/Example.unity b/Assets/Packages/Mirror/Examples/Basic/Scenes/Example.unity new file mode 100644 index 0000000..2f71476 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/Scenes/Example.unity @@ -0,0 +1,633 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0.44657898, g: 0.4964133, b: 0.5748178, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 10 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &249891953 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 249891957} + - component: {fileID: 249891954} + - component: {fileID: 249891956} + - component: {fileID: 249891955} + m_Layer: 0 + m_Name: NetworkManager + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &249891954 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 249891953} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 6442dc8070ceb41f094e44de0bf87274, type: 3} + m_Name: + m_EditorClassIdentifier: + showGUI: 1 + offsetX: 0 + offsetY: 0 +--- !u!114 &249891955 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 249891953} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c7424c1070fad4ba2a7a96b02fbeb4bb, type: 3} + m_Name: + m_EditorClassIdentifier: + OnClientConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnClientDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventArraySegment, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnServerConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + OnServerDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntArraySegment, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + port: 7777 + NoDelay: 1 + serverMaxMessageSize: 16384 + clientMaxMessageSize: 16384 +--- !u!114 &249891956 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 249891953} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 8aab4c8111b7c411b9b92cf3dbc5bd4e, type: 3} + m_Name: + m_EditorClassIdentifier: + dontDestroyOnLoad: 0 + runInBackground: 1 + startOnHeadless: 0 + serverTickRate: 30 + showDebugMessages: 0 + offlineScene: + onlineScene: + transport: {fileID: 249891955} + networkAddress: localhost + maxConnections: 16 + playerPrefab: {fileID: 1088833923132447022, guid: 22f1fa3a0aff72b46a371f667bb4fb30, + type: 3} + autoCreatePlayer: 1 + playerSpawnMethod: 1 + spawnPrefabs: [] +--- !u!4 &249891957 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 249891953} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -10, y: 4, z: 5} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &288173824 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 288173827} + - component: {fileID: 288173826} + - component: {fileID: 288173825} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &288173825 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 288173824} + m_Enabled: 1 +--- !u!20 &288173826 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 288173824} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 2 + m_BackGroundColor: {r: 0, g: 0, b: 0, a: 0} + m_projectionMatrixMode: 1 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_GateFitMode: 2 + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 1 + orthographic size: 5 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &288173827 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 288173824} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1, z: -1} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &379082678 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 379082679} + - component: {fileID: 379082681} + - component: {fileID: 379082680} + m_Layer: 5 + m_Name: PlayersPanel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &379082679 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 379082678} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 533055204} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &379082680 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 379082678} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0, g: 0, b: 0, a: 0} + m_RaycastTarget: 0 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &379082681 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 379082678} + m_CullTransparentMesh: 0 +--- !u!1 &522137823 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 522137826} + - component: {fileID: 522137825} + - component: {fileID: 522137824} + m_Layer: 0 + m_Name: EventSystem + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &522137824 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 522137823} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1077351063, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_HorizontalAxis: Horizontal + m_VerticalAxis: Vertical + m_SubmitButton: Submit + m_CancelButton: Cancel + m_InputActionsPerSecond: 10 + m_RepeatDelay: 0.5 + m_ForceModuleActive: 0 +--- !u!114 &522137825 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 522137823} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -619905303, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_FirstSelected: {fileID: 0} + m_sendNavigationEvents: 1 + m_DragThreshold: 10 +--- !u!4 &522137826 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 522137823} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &533055200 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 533055204} + - component: {fileID: 533055203} + - component: {fileID: 533055202} + - component: {fileID: 533055201} + m_Layer: 5 + m_Name: Canvas + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &533055201 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 533055200} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1301386320, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_IgnoreReversedGraphics: 1 + m_BlockingObjects: 0 + m_BlockingMask: + serializedVersion: 2 + m_Bits: 4294967295 +--- !u!114 &533055202 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 533055200} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1980459831, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_UiScaleMode: 0 + m_ReferencePixelsPerUnit: 100 + m_ScaleFactor: 1 + m_ReferenceResolution: {x: 800, y: 600} + m_ScreenMatchMode: 0 + m_MatchWidthOrHeight: 0 + m_PhysicalUnit: 3 + m_FallbackScreenDPI: 96 + m_DefaultSpriteDPI: 96 + m_DynamicPixelsPerUnit: 1 +--- !u!223 &533055203 +Canvas: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 533055200} + m_Enabled: 1 + serializedVersion: 3 + m_RenderMode: 0 + m_Camera: {fileID: 0} + m_PlaneDistance: 100 + m_PixelPerfect: 0 + m_ReceivesEvents: 1 + m_OverrideSorting: 0 + m_OverridePixelPerfect: 0 + m_SortingBucketNormalizedSize: 0 + m_AdditionalShaderChannelsFlag: 0 + m_SortingLayerID: 0 + m_SortingOrder: 0 + m_TargetDisplay: 0 +--- !u!224 &533055204 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 533055200} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 0, y: 0, z: 0} + m_Children: + - {fileID: 379082679} + m_Father: {fileID: 0} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0, y: 0} +--- !u!1 &707756284 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 707756286} + - component: {fileID: 707756285} + m_Layer: 0 + m_Name: Directional Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &707756285 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 707756284} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 1 + m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &707756286 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 707756284} + m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261} + m_LocalPosition: {x: 0, y: 3, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0} diff --git a/Assets/Packages/Mirror/Examples/Basic/Scenes/Example.unity.meta b/Assets/Packages/Mirror/Examples/Basic/Scenes/Example.unity.meta new file mode 100644 index 0000000..25c602e --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/Scenes/Example.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b30904751905d3f4dacde62ac85ec7c2 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Basic/Scripts.meta b/Assets/Packages/Mirror/Examples/Basic/Scripts.meta new file mode 100644 index 0000000..5cc0800 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9c5291659f25af9409bbc25a2d37d628 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Basic/Scripts/Player.cs b/Assets/Packages/Mirror/Examples/Basic/Scripts/Player.cs new file mode 100644 index 0000000..fe00d50 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/Scripts/Player.cs @@ -0,0 +1,56 @@ +using UnityEngine; +using UnityEngine.UI; + +namespace Mirror.Examples.Basic2 +{ + public class Player : NetworkBehaviour + { + [Header("Player Components")] + public RectTransform rectTransform; + public Image image; + + [Header("Child Text Objects")] + public Text playerNameText; + public Text playerDataText; + + [SyncVar] + int playerNo; + [SyncVar] + int playerData; + [SyncVar] + Color playerColor; + + public override void OnStartServer() + { + base.OnStartServer(); + playerNo = connectionToClient.connectionId; + playerColor = Random.ColorHSV(0f, 1f, 0.9f, 0.9f, 1f, 1f); + InvokeRepeating(nameof(UpdateData), 1, 1); + } + + void UpdateData() + { + playerData = Random.Range(100, 1000); + } + + void Start() + { + transform.SetParent(GameObject.Find("PlayersPanel").transform); + + int x = 100 + ((playerNo % 4) * 150); + int y = -170 - ((playerNo / 4) * 80); + rectTransform.anchoredPosition = new Vector2(x, y); + } + + void Update() + { + // shade the panel background for the local player + if (isLocalPlayer) + image.color = new Color(1f, 1f, 1f, 0.1f); + + playerNameText.color = playerColor; + playerNameText.text = string.Format("Player {0:00}", playerNo); + playerDataText.text = string.Format("Data: {0:000}", playerData); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Basic/Scripts/Player.cs.meta b/Assets/Packages/Mirror/Examples/Basic/Scripts/Player.cs.meta new file mode 100644 index 0000000..cf15827 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Basic/Scripts/Player.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a472ac3ae1701d149861871cf416a46d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/ListServer.meta b/Assets/Packages/Mirror/Examples/ListServer.meta new file mode 100644 index 0000000..af33e59 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e192f90e0acbb41f88dfe3dba300a5c9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/ListServer/ListServer.cs b/Assets/Packages/Mirror/Examples/ListServer/ListServer.cs new file mode 100644 index 0000000..58b64d5 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/ListServer.cs @@ -0,0 +1,338 @@ +// add this component to the NetworkManager +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using UnityEngine; +using UnityEngine.UI; + +namespace Mirror.Examples.ListServer +{ + public class ServerStatus + { + public string ip; + //public ushort port; // <- not all transports use a port. assume default port. feel free to also send a port if needed. + public string title; + public ushort players; + public ushort capacity; + + public int lastLatency = -1; +#if !UNITY_WEBGL // Ping isn't known in WebGL builds + public Ping ping; +#endif + public ServerStatus(string ip, /*ushort port,*/ string title, ushort players, ushort capacity) + { + this.ip = ip; + //this.port = port; + this.title = title; + this.players = players; + this.capacity = capacity; +#if !UNITY_WEBGL // Ping isn't known in WebGL builds + ping = new Ping(ip); +#endif + } + } + + [RequireComponent(typeof(NetworkManager))] + public class ListServer : MonoBehaviour + { + [Header("Listen Server Connection")] + public string listServerIp = "127.0.0.1"; + public ushort gameServerToListenPort = 8887; + public ushort clientToListenPort = 8888; + public string gameServerTitle = "Deathmatch"; + + Telepathy.Client gameServerToListenConnection = new Telepathy.Client(); + Telepathy.Client clientToListenConnection = new Telepathy.Client(); + + [Header("UI")] + public GameObject mainPanel; + public Transform content; + public Text statusText; + public UIServerStatusSlot slotPrefab; + public Button serverAndPlayButton; + public Button serverOnlyButton; + public GameObject connectingPanel; + public Text connectingText; + public Button connectingCancelButton; + int connectingDots = 0; + + // all the servers, stored as dict with unique ip key so we can + // update them more easily + // (use "ip:port" if port is needed) + Dictionary list = new Dictionary(); + + void Start() + { + // examples + //list["127.0.0.1"] = new ServerStatus("127.0.0.1", "Deathmatch", 3, 10); + //list["192.168.0.1"] = new ServerStatus("192.168.0.1", "Free for all", 7, 10); + //list["172.217.22.3"] = new ServerStatus("172.217.22.3", "5vs5", 10, 10); + //list["172.217.16.142"] = new ServerStatus("172.217.16.142", "Hide & Seek Mod", 0, 10); + + // Update once a second. no need to try to reconnect or read data + // in each Update call + // -> calling it more than 1/second would also cause significantly + // more broadcasts in the list server. + InvokeRepeating(nameof(Tick), 0, 1); + } + + bool IsConnecting() => NetworkClient.active && !ClientScene.ready; + bool FullyConnected() => NetworkClient.active && ClientScene.ready; + + // should we use the client to listen connection? + bool UseClientToListen() + { + return !NetworkManager.isHeadless && !NetworkServer.active && !FullyConnected(); + } + + // should we use the game server to listen connection? + bool UseGameServerToListen() + { + return NetworkServer.active; + } + + void Tick() + { + TickGameServer(); + TickClient(); + } + + // send server status to list server + void SendStatus() + { + BinaryWriter writer = new BinaryWriter(new MemoryStream()); + + // create message + writer.Write((ushort)NetworkServer.connections.Count); + writer.Write((ushort)NetworkManager.singleton.maxConnections); + byte[] titleBytes = Encoding.UTF8.GetBytes(gameServerTitle); + writer.Write((ushort)titleBytes.Length); + writer.Write(titleBytes); + writer.Flush(); + + // list server only allows up to 128 bytes per message + if (writer.BaseStream.Position <= 128) + { + // send it + gameServerToListenConnection.Send(((MemoryStream)writer.BaseStream).ToArray()); + } + else Debug.LogError("[List Server] List Server will reject messages longer than 128 bytes. Please use a shorter title."); + } + + void TickGameServer() + { + // send server data to listen + if (UseGameServerToListen()) + { + // connected yet? + if (gameServerToListenConnection.Connected) + { + SendStatus(); + } + // otherwise try to connect + // (we may have just started the game) + else if (!gameServerToListenConnection.Connecting) + { + Debug.Log("[List Server] GameServer connecting......"); + gameServerToListenConnection.Connect(listServerIp, gameServerToListenPort); + } + } + // shouldn't use game server, but still using it? + else if (gameServerToListenConnection.Connected) + { + gameServerToListenConnection.Disconnect(); + } + } + + void ParseMessage(byte[] bytes) + { + // note: we don't use ReadString here because the list server + // doesn't know C#'s '7-bit-length + utf8' encoding for strings + BinaryReader reader = new BinaryReader(new MemoryStream(bytes, false), Encoding.UTF8); + byte ipBytesLength = reader.ReadByte(); + byte[] ipBytes = reader.ReadBytes(ipBytesLength); + string ip = new IPAddress(ipBytes).ToString(); + //ushort port = reader.ReadUInt16(); <- not all Transports use a port. assume default. + ushort players = reader.ReadUInt16(); + ushort capacity = reader.ReadUInt16(); + ushort titleLength = reader.ReadUInt16(); + string title = Encoding.UTF8.GetString(reader.ReadBytes(titleLength)); + //Debug.Log("PARSED: ip=" + ip + /*" port=" + port +*/ " players=" + players + " capacity= " + capacity + " title=" + title); + + // build key + string key = ip/* + ":" + port*/; + + // find existing or create new one + if (list.TryGetValue(key, out ServerStatus server)) + { + // refresh + server.title = title; + server.players = players; + server.capacity = capacity; + } + else + { + // create + server = new ServerStatus(ip, /*port,*/ title, players, capacity); + } + + // save + list[key] = server; + } + + void TickClient() + { + // receive client data from listen + if (UseClientToListen()) + { + // connected yet? + if (clientToListenConnection.Connected) + { + // receive latest game server info + while (clientToListenConnection.GetNextMessage(out Telepathy.Message message)) + { + // connected? + if (message.eventType == Telepathy.EventType.Connected) + Debug.Log("[List Server] Client connected!"); + // data message? + else if (message.eventType == Telepathy.EventType.Data) + ParseMessage(message.data); + // disconnected? + else if (message.eventType == Telepathy.EventType.Connected) + Debug.Log("[List Server] Client disconnected."); + } + +#if !UNITY_WEBGL // Ping isn't known in WebGL builds + // ping again if previous ping finished + foreach (ServerStatus server in list.Values) + { + if (server.ping.isDone) + { + server.lastLatency = server.ping.time; + server.ping = new Ping(server.ip); + } + } +#endif + } + // otherwise try to connect + // (we may have just joined the menu/disconnect from game server) + else if (!clientToListenConnection.Connecting) + { + Debug.Log("[List Server] Client connecting..."); + clientToListenConnection.Connect(listServerIp, clientToListenPort); + } + } + // shouldn't use client, but still using it? (e.g. after joining) + else if (clientToListenConnection.Connected) + { + clientToListenConnection.Disconnect(); + list.Clear(); + } + + // refresh UI afterwards + OnUI(); + } + + // instantiate/remove enough prefabs to match amount + public static void BalancePrefabs(GameObject prefab, int amount, Transform parent) + { + // instantiate until amount + for (int i = parent.childCount; i < amount; ++i) + { + Instantiate(prefab, parent, false); + } + + // delete everything that's too much + // (backwards loop because Destroy changes childCount) + for (int i = parent.childCount-1; i >= amount; --i) + Destroy(parent.GetChild(i).gameObject); + } + + void OnUI() + { + // only show while client not connected and server not started + if (!NetworkManager.singleton.isNetworkActive || IsConnecting()) + { + mainPanel.SetActive(true); + + // status text + if (clientToListenConnection.Connecting) + { + //statusText.color = Color.yellow; + statusText.text = "Connecting..."; + } + else if (clientToListenConnection.Connected) + { + //statusText.color = Color.green; + statusText.text = "Connected!"; + } + else + { + //statusText.color = Color.gray; + statusText.text = "Disconnected"; + } + + // instantiate/destroy enough slots + BalancePrefabs(slotPrefab.gameObject, list.Count, content); + + // refresh all members + for (int i = 0; i < list.Values.Count; ++i) + { + UIServerStatusSlot slot = content.GetChild(i).GetComponent(); + ServerStatus server = list.Values.ToList()[i]; + slot.titleText.text = server.title; + slot.playersText.text = server.players + "/" + server.capacity; + slot.latencyText.text = server.lastLatency != -1 ? server.lastLatency.ToString() : "..."; + slot.addressText.text = server.ip; + slot.joinButton.interactable = !IsConnecting(); + slot.joinButton.gameObject.SetActive(server.players < server.capacity); + slot.joinButton.onClick.RemoveAllListeners(); + slot.joinButton.onClick.AddListener(() => { + NetworkManager.singleton.networkAddress = server.ip; + NetworkManager.singleton.StartClient(); + }); + } + + // server buttons + serverAndPlayButton.interactable = !IsConnecting(); + serverAndPlayButton.onClick.RemoveAllListeners(); + serverAndPlayButton.onClick.AddListener(() => { + NetworkManager.singleton.StartHost(); + }); + + serverOnlyButton.interactable = !IsConnecting(); + serverOnlyButton.onClick.RemoveAllListeners(); + serverOnlyButton.onClick.AddListener(() => { + NetworkManager.singleton.StartServer(); + }); + } + else mainPanel.SetActive(false); + + // show connecting panel while connecting + if (IsConnecting()) + { + connectingPanel.SetActive(true); + + // . => .. => ... => .... + connectingDots = ((connectingDots + 1) % 4); + connectingText.text = "Connecting" + new string('.', connectingDots); + + // cancel button + connectingCancelButton.onClick.RemoveAllListeners(); + connectingCancelButton.onClick.AddListener(NetworkManager.singleton.StopClient); + } + else connectingPanel.SetActive(false); + } + + // disconnect everything when pressing Stop in the Editor + void OnApplicationQuit() + { + if (gameServerToListenConnection.Connected) + gameServerToListenConnection.Disconnect(); + if (clientToListenConnection.Connected) + clientToListenConnection.Disconnect(); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/ListServer/ListServer.cs.meta b/Assets/Packages/Mirror/Examples/ListServer/ListServer.cs.meta new file mode 100644 index 0000000..35af6c4 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/ListServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69f796b44735c414783d66f47b150c5f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/ListServer/Scenes.meta b/Assets/Packages/Mirror/Examples/ListServer/Scenes.meta new file mode 100644 index 0000000..e0412be --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/Scenes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9826d673f42ad4c59b8fc27ae86729e1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/ListServer/Scenes/NavMesh.asset b/Assets/Packages/Mirror/Examples/ListServer/Scenes/NavMesh.asset new file mode 100644 index 0000000..3acffc8 Binary files /dev/null and b/Assets/Packages/Mirror/Examples/ListServer/Scenes/NavMesh.asset differ diff --git a/Assets/Packages/Mirror/Examples/ListServer/Scenes/NavMesh.asset.meta b/Assets/Packages/Mirror/Examples/ListServer/Scenes/NavMesh.asset.meta new file mode 100644 index 0000000..a7a9f22 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/Scenes/NavMesh.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b7816657e55c04901be36ace7275ad85 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 23800000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/ListServer/Scenes/Scene.unity b/Assets/Packages/Mirror/Examples/ListServer/Scenes/Scene.unity new file mode 100644 index 0000000..6409c7b --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/Scenes/Scene.unity @@ -0,0 +1,3469 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 3 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &4 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 10 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 0 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 1024 + m_ReflectionCompression: 2 + m_MixedBakeMode: 1 + m_BakeBackend: 0 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 0 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 0 +--- !u!196 &5 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 23800000, guid: b7816657e55c04901be36ace7275ad85, type: 2} +--- !u!1 &13922436 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 13922437} + - component: {fileID: 13922439} + - component: {fileID: 13922438} + m_Layer: 5 + m_Name: TextStatus + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &13922437 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 13922436} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1926990971} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: -29} + m_SizeDelta: {x: 0, y: 18} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &13922438 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 13922436} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 1 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Status +--- !u!222 &13922439 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 13922436} + m_CullTransparentMesh: 0 +--- !u!1 &21701407 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 21701408} + - component: {fileID: 21701410} + - component: {fileID: 21701409} + m_Layer: 5 + m_Name: TextJoinServer + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &21701408 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 21701407} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 776519261} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: -29} + m_SizeDelta: {x: 0, y: 18} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &21701409 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 21701407} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 1 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Join Server +--- !u!222 &21701410 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 21701407} + m_CullTransparentMesh: 0 +--- !u!1 &88936773 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 88936777} + - component: {fileID: 88936776} + - component: {fileID: 88936775} + - component: {fileID: 88936774} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &88936774 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 88936773} + m_Enabled: 1 +--- !u!124 &88936775 +Behaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 88936773} + m_Enabled: 1 +--- !u!20 &88936776 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 88936773} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0, g: 0, b: 0, a: 0} + m_projectionMatrixMode: 1 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_GateFitMode: 2 + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &88936777 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 88936773} + m_LocalRotation: {x: 0, y: 0.92387956, z: -0.38268343, w: 0} + m_LocalPosition: {x: 0, y: 6.5, z: 8} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 45, y: 180, z: 0} +--- !u!1 &123981370 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 123981371} + - component: {fileID: 123981373} + - component: {fileID: 123981372} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &123981371 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 123981370} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 276447173} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &123981372 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 123981370} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Cancel +--- !u!222 &123981373 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 123981370} + m_CullTransparentMesh: 0 +--- !u!1 &177548782 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 177548783} + - component: {fileID: 177548785} + - component: {fileID: 177548784} + m_Layer: 5 + m_Name: TextTitle + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &177548783 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 177548782} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1007872741} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0.5} + m_AnchorMax: {x: 1, y: 0.5} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: -36, y: 20} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &177548784 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 177548782} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.23137255, g: 1, b: 0.6862745, a: 1} + m_RaycastTarget: 0 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 14 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Mirror ListServer Demo* +--- !u!222 &177548785 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 177548782} + m_CullTransparentMesh: 0 +--- !u!1 &232720476 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 232720477} + - component: {fileID: 232720479} + - component: {fileID: 232720478} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &232720477 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 232720476} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1578438653} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 0, y: 1} + m_AnchoredPosition: {x: 7, y: 0} + m_SizeDelta: {x: 218, y: 20} + m_Pivot: {x: 0, y: 1} +--- !u!114 &232720478 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 232720476} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 0.23137255, b: 0.5803922, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 1 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 3 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Server +--- !u!222 &232720479 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 232720476} + m_CullTransparentMesh: 0 +--- !u!1 &251893064 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 251893065} + - component: {fileID: 251893066} + m_Layer: 0 + m_Name: Spawn + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &251893065 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 251893064} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 3, y: 0, z: 3} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 8 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &251893066 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 251893064} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &276447172 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 276447173} + - component: {fileID: 276447176} + - component: {fileID: 276447175} + - component: {fileID: 276447174} + m_Layer: 5 + m_Name: ButtonCancel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &276447173 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 276447172} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 123981371} + m_Father: {fileID: 1926990971} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 0} + m_AnchoredPosition: {x: 4, y: 16} + m_SizeDelta: {x: -8, y: 20} + m_Pivot: {x: 0, y: 0.5} +--- !u!114 &276447174 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 276447172} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 0.32156864, g: 0.32156864, b: 0.32156864, a: 1} + m_HighlightedColor: {r: 0.3529412, g: 0.3529412, b: 0.3529412, a: 1} + m_PressedColor: {r: 0.3882353, g: 0.3882353, b: 0.3882353, a: 1} + m_DisabledColor: {r: 0.3882353, g: 0.3882353, b: 0.3882353, a: 0.2509804} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 276447175} + m_OnClick: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, + Culture=neutral, PublicKeyToken=null +--- !u!114 &276447175 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 276447172} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &276447176 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 276447172} + m_CullTransparentMesh: 0 +--- !u!1 &354490534 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 354490535} + - component: {fileID: 354490537} + - component: {fileID: 354490536} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &354490535 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 354490534} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1578438653} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 0, y: 1} + m_AnchoredPosition: {x: 345, y: 0} + m_SizeDelta: {x: 130, y: 20} + m_Pivot: {x: 0, y: 1} +--- !u!114 &354490536 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 354490534} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 0.23137255, b: 0.5803922, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 1 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 5 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Address +--- !u!222 &354490537 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 354490534} + m_CullTransparentMesh: 0 +--- !u!1 &424897549 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 424897550} + - component: {fileID: 424897552} + - component: {fileID: 424897551} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &424897550 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 424897549} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1578438653} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 0, y: 1} + m_AnchoredPosition: {x: 225, y: 0} + m_SizeDelta: {x: 60, y: 20} + m_Pivot: {x: 0, y: 1} +--- !u!114 &424897551 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 424897549} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 0.23137255, b: 0.5803922, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 1 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 5 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Players +--- !u!222 &424897552 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 424897549} + m_CullTransparentMesh: 0 +--- !u!1 &531282979 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 531282980} + - component: {fileID: 531282982} + - component: {fileID: 531282981} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &531282980 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 531282979} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1004751478} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &531282981 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 531282979} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Server & Play +--- !u!222 &531282982 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 531282979} + m_CullTransparentMesh: 0 +--- !u!1 &535675709 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 535675710} + - component: {fileID: 535675712} + - component: {fileID: 535675711} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &535675710 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 535675709} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1578438653} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 0, y: 1} + m_AnchoredPosition: {x: 285, y: 0} + m_SizeDelta: {x: 60, y: 20} + m_Pivot: {x: 0, y: 1} +--- !u!114 &535675711 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 535675709} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 0.23137255, b: 0.5803922, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 1 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 5 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Latency +--- !u!222 &535675712 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 535675709} + m_CullTransparentMesh: 0 +--- !u!1 &535739935 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 535739936} + - component: {fileID: 535739937} + m_Layer: 0 + m_Name: Spawn + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &535739936 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 535739935} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 3, y: 0, z: -3} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 6 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &535739937 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 535739935} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &583153858 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 583153859} + - component: {fileID: 583153861} + - component: {fileID: 583153860} + m_Layer: 5 + m_Name: Content + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &583153859 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 583153858} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1918165881} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 0, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 560, y: 0} + m_Pivot: {x: 0, y: 1} +--- !u!114 &583153860 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 583153858} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -2095666955, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Padding: + m_Left: 2 + m_Right: 2 + m_Top: 4 + m_Bottom: 2 + m_ChildAlignment: 0 + m_StartCorner: 0 + m_StartAxis: 0 + m_CellSize: {x: 560, y: 16} + m_Spacing: {x: 0, y: 0} + m_Constraint: 1 + m_ConstraintCount: 1 +--- !u!114 &583153861 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 583153858} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_HorizontalFit: 0 + m_VerticalFit: 2 +--- !u!1 &586458803 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 586458804} + - component: {fileID: 586458807} + - component: {fileID: 586458806} + - component: {fileID: 586458805} + m_Layer: 5 + m_Name: Scrollbar Vertical + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &586458804 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 586458803} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1345848863} + m_Father: {fileID: 1918165881} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 1, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 20, y: 0} + m_Pivot: {x: 1, y: 1} +--- !u!114 &586458805 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 586458803} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -2061169968, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 0.4117647, g: 0.4117647, b: 0.4117647, a: 1} + m_HighlightedColor: {r: 0.41176474, g: 0.41176474, b: 0.41176474, a: 1} + m_PressedColor: {r: 0.41176474, g: 0.41176474, b: 0.41176474, a: 1} + m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 2064208032} + m_HandleRect: {fileID: 2064208031} + m_Direction: 2 + m_Value: 0 + m_Size: 1 + m_NumberOfSteps: 0 + m_OnValueChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.Scrollbar+ScrollEvent, UnityEngine.UI, Version=1.0.0.0, + Culture=neutral, PublicKeyToken=null +--- !u!114 &586458806 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 586458803} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.24313726, g: 0.24313726, b: 0.24313726, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &586458807 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 586458803} + m_CullTransparentMesh: 0 +--- !u!1 &635355836 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 635355837} + - component: {fileID: 635355839} + - component: {fileID: 635355838} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &635355837 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 635355836} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1578438653} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 0, y: 1} + m_AnchoredPosition: {x: 475, y: 0} + m_SizeDelta: {x: 40, y: 20} + m_Pivot: {x: 0, y: 1} +--- !u!114 &635355838 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 635355836} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 0.23137255, b: 0.5803922, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 1 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 5 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Action +--- !u!222 &635355839 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 635355836} + m_CullTransparentMesh: 0 +--- !u!1 &651109221 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 651109222} + - component: {fileID: 651109224} + - component: {fileID: 651109223} + m_Layer: 5 + m_Name: Background + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &651109222 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 651109221} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1206549608} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 863, y: 754} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &651109223 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 651109221} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.39215687, g: 0.58431375, b: 0.92941177, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 0} + m_Type: 0 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &651109224 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 651109221} + m_CullTransparentMesh: 0 +--- !u!1 &712827150 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 712827151} + - component: {fileID: 712827153} + - component: {fileID: 712827152} + m_Layer: 5 + m_Name: TextStatus + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &712827151 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 712827150} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 776519261} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 1, y: 1} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: -3, y: -19} + m_SizeDelta: {x: 157.79, y: 19} + m_Pivot: {x: 1, y: 1} +--- !u!114 &712827152 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 712827150} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 0.24313726} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 2 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 5 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Status +--- !u!222 &712827153 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 712827150} + m_CullTransparentMesh: 0 +--- !u!1 &719699535 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1206549608} + m_Layer: 5 + m_Name: ServerList + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!1 &747705678 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 747705679} + - component: {fileID: 747705681} + - component: {fileID: 747705680} + m_Layer: 5 + m_Name: TitleBar + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &747705679 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 747705678} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1093045669} + m_Father: {fileID: 1926990971} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 20} + m_Pivot: {x: 0.5, y: 1} +--- !u!114 &747705680 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 747705678} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.31764707, g: 0.31764707, b: 0.31764707, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &747705681 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 747705678} + m_CullTransparentMesh: 0 +--- !u!1 &776519260 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 776519261} + - component: {fileID: 776519264} + - component: {fileID: 776519263} + m_Layer: 5 + m_Name: ServerListPanel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &776519261 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 776519260} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1007872741} + - {fileID: 21701408} + - {fileID: 712827151} + - {fileID: 1578438653} + - {fileID: 1918165881} + - {fileID: 1052220088} + - {fileID: 1291804678} + - {fileID: 777480155} + m_Father: {fileID: 1206549608} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0.5, y: 0.5} + m_AnchorMax: {x: 0.5, y: 0.5} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 526, y: 400} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &776519263 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 776519260} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19215687, g: 0.19215687, b: 0.19215687, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &776519264 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 776519260} + m_CullTransparentMesh: 0 +--- !u!1 &777480154 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 777480155} + - component: {fileID: 777480157} + - component: {fileID: 777480156} + m_Layer: 5 + m_Name: TextFootnote + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &777480155 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 777480154} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 776519261} + m_RootOrder: 7 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 0} + m_AnchoredPosition: {x: 0, y: -10} + m_SizeDelta: {x: 0, y: 20} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &777480156 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 777480154} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 2 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: '* Host your own List Server with: mirror-networking.com/list-server' +--- !u!222 &777480157 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 777480154} + m_CullTransparentMesh: 0 +--- !u!1 &993261493 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 993261494} + - component: {fileID: 993261497} + - component: {fileID: 993261496} + - component: {fileID: 993261495} + m_Layer: 5 + m_Name: ButtonServerOnly + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &993261494 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 993261493} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 2020215609} + m_Father: {fileID: 1291804678} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 1, y: 0.5} + m_AnchorMax: {x: 1, y: 0.5} + m_AnchoredPosition: {x: -2, y: 0} + m_SizeDelta: {x: 260, y: 20} + m_Pivot: {x: 1, y: 0.5} +--- !u!114 &993261495 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 993261493} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 0.32156864, g: 0.32156864, b: 0.32156864, a: 1} + m_HighlightedColor: {r: 0.3529412, g: 0.3529412, b: 0.3529412, a: 1} + m_PressedColor: {r: 0.3882353, g: 0.3882353, b: 0.3882353, a: 1} + m_DisabledColor: {r: 0.3882353, g: 0.3882353, b: 0.3882353, a: 0.2509804} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 993261496} + m_OnClick: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, + Culture=neutral, PublicKeyToken=null +--- !u!114 &993261496 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 993261493} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &993261497 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 993261493} + m_CullTransparentMesh: 0 +--- !u!1 &1004751477 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1004751478} + - component: {fileID: 1004751481} + - component: {fileID: 1004751480} + - component: {fileID: 1004751479} + m_Layer: 5 + m_Name: ButtonServer&Play + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1004751478 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1004751477} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 531282980} + m_Father: {fileID: 1291804678} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0.5} + m_AnchorMax: {x: 0, y: 0.5} + m_AnchoredPosition: {x: 2, y: 0} + m_SizeDelta: {x: 260, y: 20} + m_Pivot: {x: 0, y: 0.5} +--- !u!114 &1004751479 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1004751477} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 0.32156864, g: 0.32156864, b: 0.32156864, a: 1} + m_HighlightedColor: {r: 0.3529412, g: 0.3529412, b: 0.3529412, a: 1} + m_PressedColor: {r: 0.3882353, g: 0.3882353, b: 0.3882353, a: 1} + m_DisabledColor: {r: 0.3882353, g: 0.3882353, b: 0.3882353, a: 0.2509804} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 1004751480} + m_OnClick: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, + Culture=neutral, PublicKeyToken=null +--- !u!114 &1004751480 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1004751477} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &1004751481 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1004751477} + m_CullTransparentMesh: 0 +--- !u!1 &1007872740 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1007872741} + - component: {fileID: 1007872744} + - component: {fileID: 1007872743} + m_Layer: 5 + m_Name: TitleBar + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1007872741 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1007872740} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 177548783} + m_Father: {fileID: 776519261} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 20} + m_Pivot: {x: 0.5, y: 1} +--- !u!114 &1007872743 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1007872740} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.31764707, g: 0.31764707, b: 0.31764707, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &1007872744 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1007872740} + m_CullTransparentMesh: 0 +--- !u!1 &1052220087 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1052220088} + - component: {fileID: 1052220090} + - component: {fileID: 1052220089} + m_Layer: 5 + m_Name: TextStartServer + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1052220088 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1052220087} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 776519261} + m_RootOrder: 5 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 0} + m_AnchoredPosition: {x: 0, y: 40} + m_SizeDelta: {x: 0, y: 20} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1052220089 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1052220087} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 1 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Start Server +--- !u!222 &1052220090 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1052220087} + m_CullTransparentMesh: 0 +--- !u!1 &1081204137 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1081204138} + - component: {fileID: 1081204140} + - component: {fileID: 1081204139} + m_Layer: 5 + m_Name: TextConnecting + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1081204138 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081204137} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1926990971} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0.5} + m_AnchorMax: {x: 1, y: 0.5} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 20} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1081204139 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081204137} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 0.23137255, b: 0.5803922, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 1 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Connecting... +--- !u!222 &1081204140 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081204137} + m_CullTransparentMesh: 0 +--- !u!1 &1093045668 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1093045669} + - component: {fileID: 1093045671} + - component: {fileID: 1093045670} + m_Layer: 5 + m_Name: TextTitle + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1093045669 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1093045668} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 747705679} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0.5} + m_AnchorMax: {x: 1, y: 0.5} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: -36, y: 20} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1093045670 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1093045668} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.23137255, g: 1, b: 0.6862745, a: 1} + m_RaycastTarget: 0 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 14 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: +--- !u!222 &1093045671 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1093045668} + m_CullTransparentMesh: 0 +--- !u!1 &1107091652 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1107091656} + - component: {fileID: 1107091655} + - component: {fileID: 1107091654} + - component: {fileID: 1107091653} + m_Layer: 0 + m_Name: Ground + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!23 &1107091653 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1107091652} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 29b49c27a74f145918356859bd7af511, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!64 &1107091654 +MeshCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1107091652} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Convex: 0 + m_CookingOptions: 14 + m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} +--- !u!33 &1107091655 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1107091652} + m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1107091656 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1107091652} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!224 &1206549608 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 719699535} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 651109222} + - {fileID: 776519261} + - {fileID: 1926990971} + m_Father: {fileID: 1972322034} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!1 &1282001517 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1282001518} + - component: {fileID: 1282001520} + - component: {fileID: 1282001521} + - component: {fileID: 1282001522} + m_Layer: 0 + m_Name: NetworkManager + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1282001518 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1282001517} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 5 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1282001520 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1282001517} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 8aab4c8111b7c411b9b92cf3dbc5bd4e, type: 3} + m_Name: + m_EditorClassIdentifier: + dontDestroyOnLoad: 1 + runInBackground: 1 + startOnHeadless: 1 + serverTickRate: 30 + showDebugMessages: 0 + offlineScene: + onlineScene: + transport: {fileID: 1282001521} + networkAddress: localhost + maxConnections: 25 + playerPrefab: {fileID: 1916082411674582, guid: 6f43bf5488a7443d19ab2a83c6b91f35, + type: 3} + autoCreatePlayer: 1 + playerSpawnMethod: 1 + spawnPrefabs: + - {fileID: 5890560936853567077, guid: b7dd46dbf38c643f09e206f9fa4be008, type: 3} +--- !u!114 &1282001521 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1282001517} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c7424c1070fad4ba2a7a96b02fbeb4bb, type: 3} + m_Name: + m_EditorClassIdentifier: + OnClientConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnClientDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventByteArray, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnServerConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + OnServerDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntByteArray, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + port: 7777 + NoDelay: 1 + MaxMessageSize: 16384 +--- !u!114 &1282001522 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1282001517} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 69f796b44735c414783d66f47b150c5f, type: 3} + m_Name: + m_EditorClassIdentifier: + listServerIp: 35.243.149.104 + gameServerToListenPort: 8887 + clientToListenPort: 8888 + gameServerTitle: Deathmatch + mainPanel: {fileID: 719699535} + content: {fileID: 583153859} + statusText: {fileID: 712827152} + slotPrefab: {fileID: 114611570997501482, guid: 611330311f6094567ad2f8012b470129, + type: 3} + serverAndPlayButton: {fileID: 1004751479} + serverOnlyButton: {fileID: 993261495} + connectingPanel: {fileID: 1926990970} + connectingText: {fileID: 1081204139} + connectingCancelButton: {fileID: 276447174} +--- !u!1 &1291804677 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1291804678} + - component: {fileID: 1291804680} + - component: {fileID: 1291804679} + m_Layer: 5 + m_Name: PanelStartServer + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1291804678 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1291804677} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1004751478} + - {fileID: 993261494} + m_Father: {fileID: 776519261} + m_RootOrder: 6 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 0} + m_AnchoredPosition: {x: 0, y: 16} + m_SizeDelta: {x: -4, y: 28} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1291804679 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1291804677} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.25882354, g: 0.25882354, b: 0.25882354, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &1291804680 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1291804677} + m_CullTransparentMesh: 0 +--- !u!1 &1345848862 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1345848863} + m_Layer: 5 + m_Name: Sliding Area + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1345848863 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1345848862} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 2064208031} + m_Father: {fileID: 586458804} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: -20, y: -20} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!1 &1458789072 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1458789073} + - component: {fileID: 1458789074} + m_Layer: 0 + m_Name: Spawn + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1458789073 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1458789072} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -3, y: 0, z: 3} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 9 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1458789074 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1458789072} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1501912662 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1501912663} + - component: {fileID: 1501912664} + m_Layer: 0 + m_Name: Spawn + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1501912663 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1501912662} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -3, y: 0, z: -3} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 7 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1501912664 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1501912662} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1578438652 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1578438653} + - component: {fileID: 1578438655} + - component: {fileID: 1578438654} + m_Layer: 5 + m_Name: PanelTableHeader + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1578438653 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1578438652} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 232720477} + - {fileID: 424897550} + - {fileID: 535675710} + - {fileID: 354490535} + - {fileID: 635355837} + m_Father: {fileID: 776519261} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: -48} + m_SizeDelta: {x: 0, y: 20} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1578438654 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1578438652} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.25882354, g: 0.25882354, b: 0.25882354, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &1578438655 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1578438652} + m_CullTransparentMesh: 0 +--- !u!1 &1680368249 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1680368252} + - component: {fileID: 1680368251} + - component: {fileID: 1680368250} + m_Layer: 0 + m_Name: EventSystem + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1680368250 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1680368249} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1077351063, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_HorizontalAxis: Horizontal + m_VerticalAxis: Vertical + m_SubmitButton: Submit + m_CancelButton: Cancel + m_InputActionsPerSecond: 10 + m_RepeatDelay: 0.5 + m_ForceModuleActive: 0 +--- !u!114 &1680368251 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1680368249} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -619905303, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_FirstSelected: {fileID: 0} + m_sendNavigationEvents: 1 + m_DragThreshold: 10 +--- !u!4 &1680368252 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1680368249} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1918165880 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1918165881} + - component: {fileID: 1918165885} + - component: {fileID: 1918165884} + - component: {fileID: 1918165883} + - component: {fileID: 1918165882} + m_Layer: 5 + m_Name: Scroll View + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1918165881 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1918165880} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 583153859} + - {fileID: 586458804} + m_Father: {fileID: 776519261} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: -3} + m_SizeDelta: {x: -2, y: -106} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1918165882 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1918165880} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -1200242548, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_ShowMaskGraphic: 1 +--- !u!114 &1918165883 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1918165880} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.25882354, g: 0.25882354, b: 0.25882354, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &1918165884 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1918165880} + m_CullTransparentMesh: 0 +--- !u!114 &1918165885 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1918165880} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1367256648, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Content: {fileID: 583153859} + m_Horizontal: 0 + m_Vertical: 1 + m_MovementType: 2 + m_Elasticity: 0.1 + m_Inertia: 1 + m_DecelerationRate: 0.135 + m_ScrollSensitivity: 1 + m_Viewport: {fileID: 0} + m_HorizontalScrollbar: {fileID: 0} + m_VerticalScrollbar: {fileID: 586458805} + m_HorizontalScrollbarVisibility: 2 + m_VerticalScrollbarVisibility: 1 + m_HorizontalScrollbarSpacing: -3 + m_VerticalScrollbarSpacing: -3 + m_OnValueChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.ScrollRect+ScrollRectEvent, UnityEngine.UI, Version=1.0.0.0, + Culture=neutral, PublicKeyToken=null +--- !u!1 &1926990970 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1926990971} + - component: {fileID: 1926990973} + - component: {fileID: 1926990972} + m_Layer: 5 + m_Name: ConnectingPanel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1926990971 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1926990970} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 747705679} + - {fileID: 13922437} + - {fileID: 1081204138} + - {fileID: 276447173} + m_Father: {fileID: 1206549608} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0.5, y: 0.5} + m_AnchorMax: {x: 0.5, y: 0.5} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 250, y: 100} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1926990972 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1926990970} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19215687, g: 0.19215687, b: 0.19215687, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &1926990973 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1926990970} + m_CullTransparentMesh: 0 +--- !u!1 &1972322030 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1972322034} + - component: {fileID: 1972322033} + - component: {fileID: 1972322032} + - component: {fileID: 1972322031} + m_Layer: 5 + m_Name: Canvas + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1972322031 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1972322030} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1301386320, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_IgnoreReversedGraphics: 1 + m_BlockingObjects: 0 + m_BlockingMask: + serializedVersion: 2 + m_Bits: 4294967295 +--- !u!114 &1972322032 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1972322030} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1980459831, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_UiScaleMode: 0 + m_ReferencePixelsPerUnit: 100 + m_ScaleFactor: 1 + m_ReferenceResolution: {x: 800, y: 600} + m_ScreenMatchMode: 0 + m_MatchWidthOrHeight: 0 + m_PhysicalUnit: 3 + m_FallbackScreenDPI: 96 + m_DefaultSpriteDPI: 96 + m_DynamicPixelsPerUnit: 1 +--- !u!223 &1972322033 +Canvas: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1972322030} + m_Enabled: 1 + serializedVersion: 3 + m_RenderMode: 0 + m_Camera: {fileID: 0} + m_PlaneDistance: 100 + m_PixelPerfect: 1 + m_ReceivesEvents: 1 + m_OverrideSorting: 0 + m_OverridePixelPerfect: 0 + m_SortingBucketNormalizedSize: 0 + m_AdditionalShaderChannelsFlag: 0 + m_SortingLayerID: 0 + m_SortingOrder: 0 + m_TargetDisplay: 0 +--- !u!224 &1972322034 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1972322030} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 0, y: 0, z: 0} + m_Children: + - {fileID: 1206549608} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0, y: 0} +--- !u!1 &2020215608 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2020215609} + - component: {fileID: 2020215611} + - component: {fileID: 2020215610} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &2020215609 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2020215608} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 993261494} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &2020215610 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2020215608} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Server Only +--- !u!222 &2020215611 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2020215608} + m_CullTransparentMesh: 0 +--- !u!1 &2054208274 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2054208276} + - component: {fileID: 2054208275} + m_Layer: 0 + m_Name: Directional light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &2054208275 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2054208274} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 1 + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &2054208276 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2054208274} + m_LocalRotation: {x: 0.10938167, y: 0.8754261, z: -0.40821788, w: 0.23456976} + m_LocalPosition: {x: 0, y: 10, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 50, y: 150, z: 0} +--- !u!1 &2064208030 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2064208031} + - component: {fileID: 2064208033} + - component: {fileID: 2064208032} + m_Layer: 5 + m_Name: Handle + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &2064208031 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2064208030} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1345848863} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 20, y: 20} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &2064208032 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2064208030} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!222 &2064208033 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2064208030} + m_CullTransparentMesh: 0 diff --git a/Assets/Packages/Mirror/Examples/ListServer/Scenes/Scene.unity.meta b/Assets/Packages/Mirror/Examples/ListServer/Scenes/Scene.unity.meta new file mode 100644 index 0000000..deb580f --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/Scenes/Scene.unity.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ccdea83d270df4b078963a0243e41ac0 +timeCreated: 1426587410 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/ListServer/UI.meta b/Assets/Packages/Mirror/Examples/ListServer/UI.meta new file mode 100644 index 0000000..8588770 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/UI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8d7b75cc57dee4425af050c10508257a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/ListServer/UI/ServerStatusSlot.prefab b/Assets/Packages/Mirror/Examples/ListServer/UI/ServerStatusSlot.prefab new file mode 100644 index 0000000..af38042 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/UI/ServerStatusSlot.prefab @@ -0,0 +1,651 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &1009505356919436 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 224428085307354514} + - component: {fileID: 222534217462828066} + - component: {fileID: 114077992825021022} + m_Layer: 5 + m_Name: TextPlayers + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &224428085307354514 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1009505356919436} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 224813910264502154} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 60, y: 16} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &222534217462828066 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1009505356919436} + m_CullTransparentMesh: 0 +--- !u!114 &114077992825021022 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1009505356919436} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 5 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: '[Players]' +--- !u!1 &1165846264137056 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 224595697833923954} + - component: {fileID: 222565095748274674} + - component: {fileID: 114410999938197916} + m_Layer: 5 + m_Name: TextLatency + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &224595697833923954 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1165846264137056} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 224813910264502154} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 60, y: 16} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &222565095748274674 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1165846264137056} + m_CullTransparentMesh: 0 +--- !u!114 &114410999938197916 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1165846264137056} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 5 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: '[Latency]' +--- !u!1 &1259177336467004 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 224813910264502154} + - component: {fileID: 222443701544564472} + - component: {fileID: 114424214131292870} + - component: {fileID: 114617214395066132} + - component: {fileID: 114618400118094574} + - component: {fileID: 114611570997501482} + m_Layer: 5 + m_Name: ServerStatusSlot + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &224813910264502154 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1259177336467004} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 224596263305646570} + - {fileID: 224428085307354514} + - {fileID: 224595697833923954} + - {fileID: 2588874080615256095} + - {fileID: 224530003443674914} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &222443701544564472 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1259177336467004} + m_CullTransparentMesh: 0 +--- !u!114 &114424214131292870 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1259177336467004} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!114 &114617214395066132 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1259177336467004} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_HorizontalFit: 0 + m_VerticalFit: 2 +--- !u!114 &114618400118094574 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1259177336467004} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -405508275, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Padding: + m_Left: 4 + m_Right: 2 + m_Top: 1 + m_Bottom: 1 + m_ChildAlignment: 0 + m_Spacing: 0 + m_ChildForceExpandWidth: 0 + m_ChildForceExpandHeight: 0 + m_ChildControlWidth: 0 + m_ChildControlHeight: 0 +--- !u!114 &114611570997501482 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1259177336467004} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7f24d39c9182b4098bcfd0c2546d0bf2, type: 3} + m_Name: + m_EditorClassIdentifier: + titleText: {fileID: 114105517410707240} + playersText: {fileID: 114077992825021022} + latencyText: {fileID: 114410999938197916} + addressText: {fileID: 1711666012325280996} + joinButton: {fileID: 114358377111651776} +--- !u!1 &1368168976437814 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 224596263305646570} + - component: {fileID: 222703717971346548} + - component: {fileID: 114105517410707240} + m_Layer: 5 + m_Name: TextTitle + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &224596263305646570 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1368168976437814} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 224813910264502154} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 218, y: 16} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &222703717971346548 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1368168976437814} + m_CullTransparentMesh: 0 +--- !u!114 &114105517410707240 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1368168976437814} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 3 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: '[Title]' +--- !u!1 &1462871638010074 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 224530003443674914} + - component: {fileID: 222322555260831376} + - component: {fileID: 114653458098104780} + - component: {fileID: 114358377111651776} + m_Layer: 5 + m_Name: ButtonJoin + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &224530003443674914 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1462871638010074} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 224615151935076648} + m_Father: {fileID: 224813910264502154} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 40, y: 18} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &222322555260831376 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1462871638010074} + m_CullTransparentMesh: 0 +--- !u!114 &114653458098104780 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1462871638010074} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!114 &114358377111651776 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1462871638010074} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 0.32156864, g: 0.32156864, b: 0.32156864, a: 1} + m_HighlightedColor: {r: 0.3529412, g: 0.3529412, b: 0.3529412, a: 1} + m_PressedColor: {r: 0.3882353, g: 0.3882353, b: 0.3882353, a: 1} + m_DisabledColor: {r: 0.3882353, g: 0.3882353, b: 0.3882353, a: 0.37254903} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 114653458098104780} + m_OnClick: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, + Culture=neutral, PublicKeyToken=null +--- !u!1 &1575165076438694 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 224615151935076648} + - component: {fileID: 222903696298421472} + - component: {fileID: 114447744505293664} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &224615151935076648 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1575165076438694} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 224530003443674914} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &222903696298421472 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1575165076438694} + m_CullTransparentMesh: 0 +--- !u!114 &114447744505293664 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1575165076438694} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Join +--- !u!1 &2231260898927249423 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2588874080615256095} + - component: {fileID: 2389080155505640677} + - component: {fileID: 1711666012325280996} + m_Layer: 5 + m_Name: TextAddress + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &2588874080615256095 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2231260898927249423} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 224813910264502154} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 130, y: 16} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &2389080155505640677 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2231260898927249423} + m_CullTransparentMesh: 0 +--- !u!114 &1711666012325280996 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2231260898927249423} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, + Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 12 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 5 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: '[Address]' diff --git a/Assets/Packages/Mirror/Examples/ListServer/UI/ServerStatusSlot.prefab.meta b/Assets/Packages/Mirror/Examples/ListServer/UI/ServerStatusSlot.prefab.meta new file mode 100644 index 0000000..49ce4ad --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/UI/ServerStatusSlot.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 611330311f6094567ad2f8012b470129 +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/ListServer/UI/UIServerStatusSlot.cs b/Assets/Packages/Mirror/Examples/ListServer/UI/UIServerStatusSlot.cs new file mode 100644 index 0000000..02efe82 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/UI/UIServerStatusSlot.cs @@ -0,0 +1,13 @@ +// Attach to the prefab for easier component access by the UI Scripts. +// Otherwise we would need slot.GetChild(0).GetComponentInChildren etc. +using UnityEngine; +using UnityEngine.UI; + +public class UIServerStatusSlot : MonoBehaviour +{ + public Text titleText; + public Text playersText; + public Text latencyText; + public Text addressText; + public Button joinButton; +} diff --git a/Assets/Packages/Mirror/Examples/ListServer/UI/UIServerStatusSlot.cs.meta b/Assets/Packages/Mirror/Examples/ListServer/UI/UIServerStatusSlot.cs.meta new file mode 100644 index 0000000..a3fee6d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/ListServer/UI/UIServerStatusSlot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f24d39c9182b4098bcfd0c2546d0bf2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby.meta b/Assets/Packages/Mirror/Examples/Lobby.meta new file mode 100644 index 0000000..51c8ec2 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ba0822b68f209a743bc575c6f2cc78f0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials.meta b/Assets/Packages/Mirror/Examples/Lobby/Materials.meta new file mode 100644 index 0000000..1593571 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 177a490b498134246b6eeddfeb608b94 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/PlayArea.mat b/Assets/Packages/Mirror/Examples/Lobby/Materials/PlayArea.mat new file mode 100644 index 0000000..652213d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials/PlayArea.mat @@ -0,0 +1,76 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: PlayArea + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: _GLOSSYREFLECTIONS_OFF _NORMALMAP _SPECULARHIGHLIGHTS_OFF + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _BumpMap: + m_Texture: {fileID: 2800000, guid: 1ef4aad253cf7e9488305da905643f09, type: 3} + 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: 8, y: 8} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 2800000, guid: 0ce4715b95ec59e4ca799c740a5e144a, type: 3} + m_Scale: {x: 8, y: 8} + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 0 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 0 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0.8867924, g: 0.84346247, b: 0.7654859, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/PlayArea.mat.meta b/Assets/Packages/Mirror/Examples/Lobby/Materials/PlayArea.mat.meta new file mode 100644 index 0000000..093bbc4 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials/PlayArea.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3201636fa507dad448e9a36d66a80825 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/Player.mat b/Assets/Packages/Mirror/Examples/Lobby/Materials/Player.mat new file mode 100644 index 0000000..3b0bbe1 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials/Player.mat @@ -0,0 +1,76 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: Player + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0, g: 0, b: 0, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/Player.mat.meta b/Assets/Packages/Mirror/Examples/Lobby/Materials/Player.mat.meta new file mode 100644 index 0000000..46963af --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials/Player.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ac64a68d9ea8fa9459ff2f158065c1d0 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/Prize.mat b/Assets/Packages/Mirror/Examples/Lobby/Materials/Prize.mat new file mode 100644 index 0000000..de7f29f --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials/Prize.mat @@ -0,0 +1,76 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: Prize + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0, g: 0, b: 0, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/Prize.mat.meta b/Assets/Packages/Mirror/Examples/Lobby/Materials/Prize.mat.meta new file mode 100644 index 0000000..18935a5 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials/Prize.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a1d7c9f39b41d414d86e64f7761cd545 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures.meta b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures.meta new file mode 100644 index 0000000..0ab7902 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 047a5014adf04914f9ffded62a715e39 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01.tga b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01.tga new file mode 100644 index 0000000..52fb755 Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01.tga differ diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01.tga.meta b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01.tga.meta new file mode 100644 index 0000000..e48bd95 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01.tga.meta @@ -0,0 +1,88 @@ +fileFormatVersion: 2 +guid: 0ce4715b95ec59e4ca799c740a5e144a +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 7 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 1024 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01_n.tga b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01_n.tga new file mode 100644 index 0000000..c3899ab Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01_n.tga differ diff --git a/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01_n.tga.meta b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01_n.tga.meta new file mode 100644 index 0000000..1e69eda --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Materials/Textures/Wall01_n.tga.meta @@ -0,0 +1,88 @@ +fileFormatVersion: 2 +guid: 1ef4aad253cf7e9488305da905643f09 +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 7 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 1 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 1 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 1024 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Prefabs.meta b/Assets/Packages/Mirror/Examples/Lobby/Prefabs.meta new file mode 100644 index 0000000..78f4e75 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Prefabs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9a6e603a7f407ec4aa25ac2c2799f71b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Prefabs/GamePlayer.prefab b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/GamePlayer.prefab new file mode 100644 index 0000000..5531849 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/GamePlayer.prefab @@ -0,0 +1,237 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &1430875437483682 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 4216737524944602} + - component: {fileID: 33190644788701022} + - component: {fileID: 23708975923909982} + m_Layer: 0 + m_Name: Visor + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4216737524944602 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1430875437483682} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0.4, z: 0.505} + m_LocalScale: {x: 0.5, y: 0.1, z: 0.2} + m_Children: [] + m_Father: {fileID: 4822224316094678} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &33190644788701022 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1430875437483682} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &23708975923909982 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1430875437483682} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_RendererPriority: 0 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!1 &1480027675339556 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 4822224316094678} + - component: {fileID: 33762848230157288} + - component: {fileID: 23313067197120050} + - component: {fileID: 143011667059871024} + - component: {fileID: 114892629901890886} + - component: {fileID: 114402732107420660} + - component: {fileID: 114265392388239132} + m_Layer: 0 + m_Name: GamePlayer + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4822224316094678 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1480027675339556} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 4216737524944602} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!33 &33762848230157288 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1480027675339556} + m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &23313067197120050 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1480027675339556} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: ac64a68d9ea8fa9459ff2f158065c1d0, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!143 &143011667059871024 +CharacterController: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1480027675339556} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Height: 2 + m_Radius: 0.5 + m_SlopeLimit: 45 + m_StepOffset: 0.3 + m_SkinWidth: 0.08 + m_MinMoveDistance: 0.001 + m_Center: {x: 0, y: 0, z: 0} +--- !u!114 &114892629901890886 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1480027675339556} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 24fd13686a451ad498101a604d134e39, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0 + index: 0 + score: 0 + playerColor: {r: 0, g: 0, b: 0, a: 1} + moveSpeed: 6 + turnSpeedAccel: 5 + turnSpeedDecel: 5 + maxTurnSpeed: 150 + jumpSpeed: 0 + maxJumpSpeed: 5 + jumpFactor: 0.05 + horizontal: 0 + vertical: 0 + turn: 0 + isGrounded: 1 + isFalling: 0 +--- !u!114 &114402732107420660 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1480027675339556} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + serverOnly: 0 + localPlayerAuthority: 1 + m_AssetId: 21daf89214c6ee443ad6875b73083c60 + m_SceneId: 0 +--- !u!114 &114265392388239132 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1480027675339556} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2f74aedd71d9a4f55b3ce499326d45fb, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + compressRotation: 1 diff --git a/Assets/Packages/Mirror/Examples/Lobby/Prefabs/GamePlayer.prefab.meta b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/GamePlayer.prefab.meta new file mode 100644 index 0000000..0df6ef0 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/GamePlayer.prefab.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 21daf89214c6ee443ad6875b73083c60 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 100100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Prefabs/LobbyPlayer.prefab b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/LobbyPlayer.prefab new file mode 100644 index 0000000..b3a2f1e --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/LobbyPlayer.prefab @@ -0,0 +1,73 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 0} + m_RootGameObject: {fileID: 1588750985201798} + m_IsPrefabAsset: 1 +--- !u!1 &1588750985201798 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 6 + m_Component: + - component: {fileID: 4817109203880908} + - component: {fileID: 114387717104821018} + - component: {fileID: 114033720796874720} + m_Layer: 0 + m_Name: LobbyPlayer + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4817109203880908 +Transform: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1588750985201798} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &114033720796874720 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1588750985201798} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41fc608223969754e817c29908fdb1d3, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + ShowLobbyGUI: 1 + ReadyToBegin: 0 + Index: 0 +--- !u!114 &114387717104821018 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1588750985201798} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: 0 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 0 + m_AssetId: deae2134a1d77704b9c595efe69767dd diff --git a/Assets/Packages/Mirror/Examples/Lobby/Prefabs/LobbyPlayer.prefab.meta b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/LobbyPlayer.prefab.meta new file mode 100644 index 0000000..153c825 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/LobbyPlayer.prefab.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: deae2134a1d77704b9c595efe69767dd +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 100100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Prefabs/Prize.prefab b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/Prize.prefab new file mode 100644 index 0000000..5846b79 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/Prize.prefab @@ -0,0 +1,130 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1001 &100100000 +Prefab: + m_ObjectHideFlags: 1 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 0} + m_Modifications: [] + m_RemovedComponents: [] + m_SourcePrefab: {fileID: 0} + m_RootGameObject: {fileID: 1139254171913846} + m_IsPrefabAsset: 1 +--- !u!1 &1139254171913846 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + serializedVersion: 6 + m_Component: + - component: {fileID: 4362442735993418} + - component: {fileID: 33086497388294428} + - component: {fileID: 23203154358629070} + - component: {fileID: 135606878775227198} + - component: {fileID: 114048121767222990} + - component: {fileID: 114251241889735402} + m_Layer: 0 + m_Name: Prize + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!4 &4362442735993418 +Transform: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1139254171913846} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1, z: 0} + m_LocalScale: {x: 0.3, y: 0.3, z: 0.3} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!23 &23203154358629070 +MeshRenderer: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1139254171913846} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_Materials: + - {fileID: 2100000, guid: a1d7c9f39b41d414d86e64f7761cd545, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!33 &33086497388294428 +MeshFilter: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1139254171913846} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!114 &114048121767222990 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1139254171913846} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: a22f9eb8ebad79e47babf4c051a714ee, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + prizeColor: {r: 0, g: 0, b: 0, a: 1} + available: 1 + spawner: {fileID: 0} +--- !u!114 &114251241889735402 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1139254171913846} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SceneId: 0 + m_ServerOnly: 0 + m_LocalPlayerAuthority: 0 + m_AssetId: 52f1c9ea06cfd154cb68ff9d1b66fc13 +--- !u!135 &135606878775227198 +SphereCollider: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 100100000} + m_GameObject: {fileID: 1139254171913846} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Radius: 0.5 + m_Center: {x: 0, y: 0, z: 0} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Prefabs/Prize.prefab.meta b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/Prize.prefab.meta new file mode 100644 index 0000000..87ab623 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Prefabs/Prize.prefab.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 52f1c9ea06cfd154cb68ff9d1b66fc13 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 100100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/README.md b/Assets/Packages/Mirror/Examples/Lobby/README.md new file mode 100644 index 0000000..adf8597 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/README.md @@ -0,0 +1,31 @@ +# Lobby Example + +In Build Settings, remove all scenes and add all of the scenes from the Examples\Lobby\Scenes folder in the following order: + +- Offline +- Lobby +- Online + +If you opened the Lobby scene before doing the above steps, you may have to reassign the scenes to the NetworkLobbyManagerExt component of the LobbyManager scene object. + +** Do not assign anything to the Online scene field!** If you do, the lobby will be bypassed. Assign **only* the Offline and Lobby and Gameplay scene fields in the inspector. + +File -> Build and Run + +Start up to 4 built instances: These will all be client players. + +Open the Offline scene in the Editor and press Play + +Click the Join Game and LAN Host in the editor: This will be host and the 5th player. You can also use LAN Server if you prefer. + +Click Join Game and LAN Client in the built instances. + +Click Ready in each instance, and finally in the Editor (Host). + +Click the Start Game button when all players are ready. + +You should now be in the Online scene with your players of random color. + +WASDQE keys to move & turn your player capsule. +Collide with the spheres to score points. +Lighter colors score higher. diff --git a/Assets/Packages/Mirror/Examples/Lobby/README.md.meta b/Assets/Packages/Mirror/Examples/Lobby/README.md.meta new file mode 100644 index 0000000..eb4961d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9110f04bd1e8468479f6625342d311c5 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scenes.meta b/Assets/Packages/Mirror/Examples/Lobby/Scenes.meta new file mode 100644 index 0000000..17072cf --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scenes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4f704ae4b4f98ae41a0bce26658850c1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scenes/LobbyScene.unity b/Assets/Packages/Mirror/Examples/Lobby/Scenes/LobbyScene.unity new file mode 100644 index 0000000..b4eaaf7 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scenes/LobbyScene.unity @@ -0,0 +1,363 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0, g: 0, b: 0, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 10 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &639890310 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 639890313} + - component: {fileID: 639890312} + - component: {fileID: 639890311} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &639890311 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 639890310} + m_Enabled: 1 +--- !u!20 &639890312 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 639890310} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.23429157, g: 0.254717, b: 0.23546094, a: 0} + m_projectionMatrixMode: 1 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_GateFitMode: 2 + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: 3 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 0 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &639890313 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 639890310} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1, z: -10} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &985189858 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 985189859} + m_Layer: 0 + m_Name: Players + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &985189859 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 985189858} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -1.7365334, y: 0.84765625, z: 1.4726781} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &2008127829 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2008127832} + - component: {fileID: 2008127833} + - component: {fileID: 2008127831} + - component: {fileID: 2008127830} + m_Layer: 0 + m_Name: LobbyManager + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &2008127830 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2008127829} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c7424c1070fad4ba2a7a96b02fbeb4bb, type: 3} + m_Name: + m_EditorClassIdentifier: + OnClientConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnClientDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventByteArray, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnServerConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + OnServerDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntByteArray, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + port: 7780 + NoDelay: 1 + MaxMessageSize: 16384 +--- !u!114 &2008127831 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2008127829} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: e7d8650c751710349bb9546d1697b9cb, type: 3} + m_Name: + m_EditorClassIdentifier: + dontDestroyOnLoad: 1 + runInBackground: 1 + startOnHeadless: 1 + serverTickRate: 30 + showDebugMessages: 0 + offlineScene: OfflineScene + onlineScene: + transport: {fileID: 2008127830} + networkAddress: localhost + maxConnections: 5 + playerPrefab: {fileID: 1480027675339556, guid: 21daf89214c6ee443ad6875b73083c60, + type: 3} + autoCreatePlayer: 1 + playerSpawnMethod: 1 + spawnPrefabs: + - {fileID: 1139254171913846, guid: 52f1c9ea06cfd154cb68ff9d1b66fc13, type: 3} + showLobbyGUI: 1 + minPlayers: 1 + lobbyPlayerPrefab: {fileID: 114033720796874720, guid: deae2134a1d77704b9c595efe69767dd, + type: 3} + LobbyScene: LobbyScene + GameplayScene: OnlineScene + lobbySlots: [] + allPlayersReady: 0 +--- !u!4 &2008127832 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2008127829} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &2008127833 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2008127829} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 6442dc8070ceb41f094e44de0bf87274, type: 3} + m_Name: + m_EditorClassIdentifier: + showGUI: 1 + offsetX: 0 + offsetY: 0 diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scenes/LobbyScene.unity.meta b/Assets/Packages/Mirror/Examples/Lobby/Scenes/LobbyScene.unity.meta new file mode 100644 index 0000000..8749026 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scenes/LobbyScene.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 48478f4d522f96945b8396f376299d3a +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scenes/OfflineScene.unity b/Assets/Packages/Mirror/Examples/Lobby/Scenes/OfflineScene.unity new file mode 100644 index 0000000..1e2b740 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scenes/OfflineScene.unity @@ -0,0 +1,210 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0, g: 0, b: 0, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 10 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &639890310 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 639890313} + - component: {fileID: 639890312} + - component: {fileID: 639890311} + - component: {fileID: 639890314} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &639890311 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 639890310} + m_Enabled: 1 +--- !u!20 &639890312 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 639890310} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.23429157, g: 0.254717, b: 0.23546094, a: 0} + m_projectionMatrixMode: 1 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_GateFitMode: 2 + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &639890313 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 639890310} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1, z: -10} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &639890314 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 639890310} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 039bde4e5e3b63e46be9b967d06e5469, type: 3} + m_Name: + m_EditorClassIdentifier: + LobbyScene: LobbyScene diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scenes/OfflineScene.unity.meta b/Assets/Packages/Mirror/Examples/Lobby/Scenes/OfflineScene.unity.meta new file mode 100644 index 0000000..45332ad --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scenes/OfflineScene.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9e6f14982412b2545a0911ebaaa46a23 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scenes/OnlineScene.unity b/Assets/Packages/Mirror/Examples/Lobby/Scenes/OnlineScene.unity new file mode 100644 index 0000000..21db370 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scenes/OnlineScene.unity @@ -0,0 +1,859 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0.17276844, g: 0.21589246, b: 0.2978263, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 10 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 112000002, guid: 83612f89e0d5b404fbd99891bda78df4, + type: 2} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &29930032 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 29930035} + - component: {fileID: 29930034} + - component: {fileID: 29930033} + m_Layer: 0 + m_Name: Spawner + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &29930033 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 29930032} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_ServerOnly: 1 + m_LocalPlayerAuthority: 0 + m_AssetId: + m_SceneId: 6047645 +--- !u!114 &29930034 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 29930032} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 0bf5c082d04f7ea459fcd30e60b5bd70, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + prizePrefab: {fileID: 114251241889735402, guid: 52f1c9ea06cfd154cb68ff9d1b66fc13, + type: 3} +--- !u!4 &29930035 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 29930032} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &151116940 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 151116942} + - component: {fileID: 151116941} + m_Layer: 0 + m_Name: Directional Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &151116941 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 151116940} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 1 + m_Color: {r: 0.990566, g: 0.9496818, b: 0.82702917, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 0.7 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &151116942 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 151116940} + m_LocalRotation: {x: 0.7071068, y: 0, z: 0, w: 0.7071068} + m_LocalPosition: {x: 0, y: 10, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0} +--- !u!1 &204334129 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 204334130} + - component: {fileID: 204334131} + m_Layer: 0 + m_Name: PlayerStart + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &204334130 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 204334129} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: -15} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1445635740} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &204334131 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 204334129} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &263230754 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 263230755} + - component: {fileID: 263230756} + m_Layer: 0 + m_Name: PlayerStart + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &263230755 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 263230754} + m_LocalRotation: {x: 0, y: 0.38268343, z: 0, w: 0.92387956} + m_LocalPosition: {x: -15, y: 0, z: -15} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1445635740} + m_RootOrder: 5 + m_LocalEulerAnglesHint: {x: 0, y: 45, z: 0} +--- !u!114 &263230756 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 263230754} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &290557149 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 290557150} + - component: {fileID: 290557151} + m_Layer: 0 + m_Name: PlayerStart + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &290557150 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 290557149} + m_LocalRotation: {x: 0, y: 0.7071068, z: 0, w: 0.7071068} + m_LocalPosition: {x: -15, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1445635740} + m_RootOrder: 6 + m_LocalEulerAnglesHint: {x: 0, y: 90, z: 0} +--- !u!114 &290557151 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 290557149} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &733367779 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 733367780} + - component: {fileID: 733367781} + m_Layer: 0 + m_Name: PlayerStart + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &733367780 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 733367779} + m_LocalRotation: {x: -0, y: 1, z: -0, w: 0} + m_LocalPosition: {x: 0, y: 0, z: 15} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1445635740} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0} +--- !u!114 &733367781 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 733367779} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &990635329 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 990635330} + - component: {fileID: 990635331} + m_Layer: 0 + m_Name: PlayerStart + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &990635330 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 990635329} + m_LocalRotation: {x: 0, y: 0.92387956, z: 0, w: 0.38268343} + m_LocalPosition: {x: -15, y: 0, z: 15} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1445635740} + m_RootOrder: 7 + m_LocalEulerAnglesHint: {x: 0, y: 135, z: 0} +--- !u!114 &990635331 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 990635329} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1050066542 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1050066545} + - component: {fileID: 1050066544} + - component: {fileID: 1050066543} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &1050066543 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1050066542} + m_Enabled: 1 +--- !u!20 &1050066544 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1050066542} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.23429157, g: 0.254717, b: 0.23546094, a: 0} + m_projectionMatrixMode: 1 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_GateFitMode: 2 + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &1050066545 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1050066542} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 2, z: -10} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1305256737 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1305256745} + - component: {fileID: 1305256744} + - component: {fileID: 1305256742} + - component: {fileID: 1305256743} + - component: {fileID: 1305256741} + - component: {fileID: 1305256740} + - component: {fileID: 1305256739} + - component: {fileID: 1305256738} + m_Layer: 0 + m_Name: PlayArea + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!65 &1305256738 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1305256737} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 10, y: 2, z: 0.1} + m_Center: {x: 0, y: 1, z: 5} +--- !u!65 &1305256739 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1305256737} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 10, y: 2, z: 0.1} + m_Center: {x: 0, y: 1, z: -5} +--- !u!65 &1305256740 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1305256737} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 0.1, y: 2, z: 10} + m_Center: {x: 5, y: 1, z: 0} +--- !u!65 &1305256741 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1305256737} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 0.1, y: 2, z: 10} + m_Center: {x: -5, y: 1, z: 0} +--- !u!23 &1305256742 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1305256737} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 3201636fa507dad448e9a36d66a80825, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!64 &1305256743 +MeshCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1305256737} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Convex: 0 + m_CookingOptions: 14 + m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} +--- !u!33 &1305256744 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1305256737} + m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1305256745 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1305256737} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 4, y: 1, z: 4} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1445635739 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1445635740} + m_Layer: 0 + m_Name: StartPositions + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1445635740 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1445635739} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1.08, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 733367780} + - {fileID: 2127619492} + - {fileID: 1975674813} + - {fileID: 1760045337} + - {fileID: 204334130} + - {fileID: 263230755} + - {fileID: 290557150} + - {fileID: 990635330} + m_Father: {fileID: 0} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1760045336 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1760045337} + - component: {fileID: 1760045338} + m_Layer: 0 + m_Name: PlayerStart + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1760045337 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1760045336} + m_LocalRotation: {x: 0, y: 0.3826836, z: -0, w: -0.92387944} + m_LocalPosition: {x: 15, y: 0, z: -15} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1445635740} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 315, z: 0} +--- !u!114 &1760045338 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1760045336} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1975674812 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1975674813} + - component: {fileID: 1975674814} + m_Layer: 0 + m_Name: PlayerStart + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1975674813 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1975674812} + m_LocalRotation: {x: 0, y: 0.7071068, z: -0, w: -0.7071068} + m_LocalPosition: {x: 15, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1445635740} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 270, z: 0} +--- !u!114 &1975674814 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1975674812} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &2127619491 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2127619492} + - component: {fileID: 2127619493} + m_Layer: 0 + m_Name: PlayerStart + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &2127619492 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2127619491} + m_LocalRotation: {x: 0, y: 0.9238796, z: -0, w: -0.38268325} + m_LocalPosition: {x: 15, y: 0, z: 15} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1445635740} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 225, z: 0} +--- !u!114 &2127619493 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2127619491} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scenes/OnlineScene.unity.meta b/Assets/Packages/Mirror/Examples/Lobby/Scenes/OnlineScene.unity.meta new file mode 100644 index 0000000..8a990fe --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scenes/OnlineScene.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d7a6763559b31854586c9e49916273ef +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts.meta b/Assets/Packages/Mirror/Examples/Lobby/Scripts.meta new file mode 100644 index 0000000..b15256a --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 03401915dd450454e88f0a839d3346f1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyManagerExt.cs b/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyManagerExt.cs new file mode 100644 index 0000000..d16d61a --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyManagerExt.cs @@ -0,0 +1,57 @@ +using UnityEngine; +using UnityEngine.Rendering; + +namespace Mirror.Examples.NetworkLobby +{ + public class NetworkLobbyManagerExt : NetworkLobbyManager + { + /// + /// Called just after GamePlayer object is instantiated and just before it replaces LobbyPlayer object. + /// This is the ideal point to pass any data like player name, credentials, tokens, colors, etc. + /// into the GamePlayer object as it is about to enter the Online scene. + /// + /// + /// + /// true unless some code in here decides it needs to abort the replacement + public override bool OnLobbyServerSceneLoadedForPlayer(GameObject lobbyPlayer, GameObject gamePlayer) + { + PlayerController player = gamePlayer.GetComponent(); + player.index = lobbyPlayer.GetComponent().index; + player.playerColor = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); + return true; + } + + /* + This code below is to demonstrate how to do a Start button that only appears for the Host player + showStartButton is a local bool that's needed because OnLobbyServerPlayersReady is only fired when + all players are ready, but if a player cancels their ready state there's no callback to set it back to false + Therefore, allPlayersReady is used in combination with showStartButton to show/hide the Start button correctly. + Setting showStartButton false when the button is pressed hides it in the game scene since NetworkLobbyManager + is set as DontDestroyOnLoad = true. + */ + + bool showStartButton; + + public override void OnLobbyServerPlayersReady() + { + // calling the base method calls ServerChangeScene as soon as all players are in Ready state. + if (isHeadless) + base.OnLobbyServerPlayersReady(); + else + showStartButton = true; + } + + public override void OnGUI() + { + base.OnGUI(); + + if (allPlayersReady && showStartButton && GUI.Button(new Rect(150, 300, 120, 20), "START GAME")) + { + // set to false to hide it in the game scene + showStartButton = false; + + ServerChangeScene(GameplayScene); + } + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyManagerExt.cs.meta b/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyManagerExt.cs.meta new file mode 100644 index 0000000..d8f5760 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyManagerExt.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e7d8650c751710349bb9546d1697b9cb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyPlayerExt.cs b/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyPlayerExt.cs new file mode 100644 index 0000000..572b9dc --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyPlayerExt.cs @@ -0,0 +1,39 @@ +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace Mirror.Examples.NetworkLobby +{ + public class NetworkLobbyPlayerExt : NetworkLobbyPlayer + { + public override void OnStartClient() + { + if (LogFilter.Debug) Debug.LogFormat("OnStartClient {0}", SceneManager.GetActiveScene().name); + + base.OnStartClient(); + NetworkLobbyManager lobby = NetworkManager.singleton as NetworkLobbyManager; + + /* + This demonstrates how to set the parent of the LobbyPlayerPrefab to an arbitrary scene object + A similar technique would be used if a full canvas layout UI existed and we wanted to show + something more visual for each player in that layout, such as a name, avatar, etc. + + Note: LobbyPlayer prefab will be marked DontDestroyOnLoad and carried forward to the game scene. + Because of this, NetworkLobbyManager must automatically set the parent to null + in ServerChangeScene and OnClientChangeScene. + */ + + if (lobby != null && SceneManager.GetActiveScene().name == lobby.LobbyScene) + gameObject.transform.SetParent(GameObject.Find("Players").transform); + } + + public override void OnClientEnterLobby() + { + if (LogFilter.Debug) Debug.LogFormat("OnClientEnterLobby {0}", SceneManager.GetActiveScene().name); + } + + public override void OnClientExitLobby() + { + if (LogFilter.Debug) Debug.LogFormat("OnClientExitLobby {0}", SceneManager.GetActiveScene().name); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyPlayerExt.cs.meta b/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyPlayerExt.cs.meta new file mode 100644 index 0000000..8e4d135 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/NetworkLobbyPlayerExt.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41fc608223969754e817c29908fdb1d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/OfflineGUI.cs b/Assets/Packages/Mirror/Examples/Lobby/Scripts/OfflineGUI.cs new file mode 100644 index 0000000..bde1ca3 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/OfflineGUI.cs @@ -0,0 +1,30 @@ +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace Mirror.Examples.NetworkLobby +{ + public class OfflineGUI : MonoBehaviour + { + [Scene] + public string LobbyScene; + + void Start() + { + // Ensure main camera is enabled because it will be disabled by PlayerController + Camera.main.enabled = true; + } + + void OnGUI() + { + GUILayout.BeginArea(new Rect(10, 10, 200, 130)); + + GUILayout.Box("OFFLINE SCENE"); + GUILayout.Box("WASDQE keys to move & turn\nTouch the spheres for points\nLighter colors score higher"); + + if (GUILayout.Button("Join Game")) + SceneManager.LoadScene(LobbyScene); + + GUILayout.EndArea(); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/OfflineGUI.cs.meta b/Assets/Packages/Mirror/Examples/Lobby/Scripts/OfflineGUI.cs.meta new file mode 100644 index 0000000..89237e0 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/OfflineGUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 039bde4e5e3b63e46be9b967d06e5469 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/PlayerController.cs b/Assets/Packages/Mirror/Examples/Lobby/Scripts/PlayerController.cs new file mode 100644 index 0000000..fbd7e55 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/PlayerController.cs @@ -0,0 +1,149 @@ +using UnityEngine; + +namespace Mirror.Examples.NetworkLobby +{ + [RequireComponent(typeof(CharacterController))] + public class PlayerController : NetworkBehaviour + { + [SyncVar] + public int index; + + [SyncVar] + public uint score; + + [SyncVar(hook = nameof(SetColor))] + public Color playerColor = Color.black; + + // Unity clones the material when GetComponent().material is called + // Cache it here and destroy it in OnDestroy to prevent a memory leak + Material cachedMaterial; + + void SetColor(Color color) + { + if (cachedMaterial == null) cachedMaterial = GetComponent().material; + cachedMaterial.color = color; + } + + void OnDestroy() + { + Destroy(cachedMaterial); + } + + CharacterController characterController; + + public override void OnStartLocalPlayer() + { + base.OnStartLocalPlayer(); + + characterController = GetComponent(); + + Camera.main.transform.SetParent(transform); + Camera.main.transform.localPosition = new Vector3(0f, 3f, -8f); + Camera.main.transform.localEulerAngles = new Vector3(10f, 0f, 0f); + } + + [Header("Movement Settings")] + public float moveSpeed = 8f; + public float turnSpeedAccel = 5f; + public float turnSpeedDecel = 5f; + public float maxTurnSpeed = 150f; + + [Header("Jump Settings")] + public float jumpSpeed = 0f; + public float maxJumpSpeed = 5F; + public float jumpFactor = .05F; + + [Header("Diagnostics")] + public float horizontal = 0f; + public float vertical = 0f; + public float turn = 0f; + public bool isGrounded = true; + public bool isFalling = false; + + void Update() + { + if (!isLocalPlayer) return; + + horizontal = Input.GetAxis("Horizontal"); + vertical = Input.GetAxis("Vertical"); + + if (Input.GetKey(KeyCode.Q) && (turn > -maxTurnSpeed)) + turn -= turnSpeedAccel; + else if (Input.GetKey(KeyCode.E) && (turn < maxTurnSpeed)) + turn += turnSpeedAccel; + else if (turn > turnSpeedDecel) + turn -= turnSpeedDecel; + else if (turn < -turnSpeedDecel) + turn += turnSpeedDecel; + else + turn = 0f; + + if (!isFalling && Input.GetKey(KeyCode.Space) && (isGrounded || jumpSpeed < maxJumpSpeed)) + jumpSpeed += maxJumpSpeed * jumpFactor; + else if (isGrounded) + isFalling = false; + else + { + isFalling = true; + jumpSpeed = 0; + } + } + + void FixedUpdate() + { + if (!isLocalPlayer || characterController == null) return; + + transform.Rotate(0f, turn * Time.fixedDeltaTime, 0f); + + Vector3 direction = new Vector3(horizontal, jumpSpeed, vertical); + direction = Vector3.ClampMagnitude(direction, 1f); + direction = transform.TransformDirection(direction); + direction *= moveSpeed; + + if (jumpSpeed > 0) + characterController.Move(direction * Time.fixedDeltaTime); + else + characterController.SimpleMove(direction); + + isGrounded = characterController.isGrounded; + } + + GameObject controllerColliderHitObject; + + void OnControllerColliderHit(ControllerColliderHit hit) + { + // If player and prize objects are on their own layer(s) with correct + // collision matrix, we wouldn't have to validate the hit.gameobject. + // Since this is just an example, project settings aren't included so we check the name. + + controllerColliderHitObject = hit.gameObject; + + if (isLocalPlayer && controllerColliderHitObject.name.StartsWith("Prize")) + { + if (LogFilter.Debug) Debug.LogFormat("OnControllerColliderHit {0}[{1}] with {2}[{3}]", name, netId, controllerColliderHitObject.name, controllerColliderHitObject.GetComponent().netId); + + // Disable the prize gameobject so it doesn't impede player movement + // It's going to be destroyed in a few frames and we don't want to spam CmdClaimPrize. + // OnControllerColliderHit will fire many times as the player slides against the object. + controllerColliderHitObject.SetActive(false); + + CmdClaimPrize(controllerColliderHitObject); + } + } + + [Command] + void CmdClaimPrize(GameObject hitObject) + { + // Null check is required, otherwise close timing of multiple claims could throw a null ref. + if (hitObject != null) + { + hitObject.GetComponent().ClaimPrize(gameObject); + } + } + + void OnGUI() + { + GUI.Box(new Rect(10f + (index * 110), 10f, 100f, 25f), score.ToString().PadLeft(10)); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/PlayerController.cs.meta b/Assets/Packages/Mirror/Examples/Lobby/Scripts/PlayerController.cs.meta new file mode 100644 index 0000000..74f8f95 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/PlayerController.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 24fd13686a451ad498101a604d134e39 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/Reward.cs b/Assets/Packages/Mirror/Examples/Lobby/Scripts/Reward.cs new file mode 100644 index 0000000..8fc0bdc --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/Reward.cs @@ -0,0 +1,55 @@ +using UnityEngine; + +namespace Mirror.Examples.NetworkLobby +{ + public class Reward : NetworkBehaviour + { + [SyncVar(hook = nameof(SetColor))] + public Color prizeColor = Color.black; + + // Unity makes a clone of the material when GetComponent().material is used + // Cache it here and Destroy it in OnDestroy to prevent a memory leak + Material materialClone; + + void SetColor(Color color) + { + if (materialClone == null) materialClone = GetComponent().material; + materialClone.color = color; + } + + private void OnDestroy() + { + Destroy(materialClone); + } + + public bool available = true; + public Spawner spawner; + uint points; + + // This is called from PlayerController.CmdClaimPrize which is invoked by PlayerController.OnControllerColliderHit + // This only runs on the server + public void ClaimPrize(GameObject player) + { + if (available) + { + // This is a fast switch to prevent two players claiming the prize in a bang-bang close contest for it. + // First hit turns it off, pending the object being destroyed a few frames later. + available = false; + + // calculate the points from the color ... lighter scores higher as the average approaches 255 + // UnityEngine.Color RGB values are float fractions of 255 + points = (uint)(((prizeColor.r * 255) + (prizeColor.g * 255) + (prizeColor.b * 255)) / 3); + if (LogFilter.Debug) Debug.LogFormat("Scored {0} points R:{1} G:{2} B:{3}", points, prizeColor.r, prizeColor.g, prizeColor.b); + + // award the points via SyncVar on the PlayerController + player.GetComponent().score += points; + + // spawn a replacement + spawner.SpawnPrize(); + + // destroy this one + NetworkServer.Destroy(gameObject); + } + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/Reward.cs.meta b/Assets/Packages/Mirror/Examples/Lobby/Scripts/Reward.cs.meta new file mode 100644 index 0000000..879bc7d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/Reward.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a22f9eb8ebad79e47babf4c051a714ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/Spawner.cs b/Assets/Packages/Mirror/Examples/Lobby/Scripts/Spawner.cs new file mode 100644 index 0000000..cbef229 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/Spawner.cs @@ -0,0 +1,39 @@ +using UnityEngine; + +namespace Mirror.Examples.NetworkLobby +{ + public class Spawner : NetworkBehaviour + { + public NetworkIdentity prizePrefab; + + float x; + float z; + + GameObject newPrize; + Reward reward; + + void Start() + { + for (int i = 0; i < 10; i++) + { + SpawnPrize(); + } + } + + public void SpawnPrize() + { + x = Random.Range(-19, 20); + z = Random.Range(-19, 20); + + newPrize = Instantiate(prizePrefab.gameObject, new Vector3(x, 1, z), Quaternion.identity); + newPrize.name = prizePrefab.name; + reward = newPrize.gameObject.GetComponent(); + reward.spawner = this; + reward.prizeColor = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); + + if (LogFilter.Debug) Debug.LogFormat("Spawning Prize R:{0} G:{1} B:{2}", reward.prizeColor.r, reward.prizeColor.g, reward.prizeColor.b); + + NetworkServer.Spawn(newPrize); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Lobby/Scripts/Spawner.cs.meta b/Assets/Packages/Mirror/Examples/Lobby/Scripts/Spawner.cs.meta new file mode 100644 index 0000000..d4103d6 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Lobby/Scripts/Spawner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0bf5c082d04f7ea459fcd30e60b5bd70 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Mirror.Examples.asmdef b/Assets/Packages/Mirror/Examples/Mirror.Examples.asmdef new file mode 100644 index 0000000..c4f942e --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Mirror.Examples.asmdef @@ -0,0 +1,15 @@ +{ + "name": "Mirror.Examples", + "references": [ + "Mirror", + "Mirror.Components" + ], + "optionalUnityReferences": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [] +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Examples/Mirror.Examples.asmdef.meta b/Assets/Packages/Mirror/Examples/Mirror.Examples.asmdef.meta new file mode 100644 index 0000000..2b545b5 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Mirror.Examples.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: fecf25954bb196642ab50657689761d6 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong.meta b/Assets/Packages/Mirror/Examples/Pong.meta new file mode 100644 index 0000000..ac8a6e2 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2220cb06641bd40be8c8330b3b4dd0ee +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/PhysicsMaterials.meta b/Assets/Packages/Mirror/Examples/Pong/PhysicsMaterials.meta new file mode 100644 index 0000000..3ba9985 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/PhysicsMaterials.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7f122364b93b24938b3f50539de4d746 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/PhysicsMaterials/BallMaterial.physicsMaterial2D b/Assets/Packages/Mirror/Examples/Pong/PhysicsMaterials/BallMaterial.physicsMaterial2D new file mode 100644 index 0000000..e2dd2d0 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/PhysicsMaterials/BallMaterial.physicsMaterial2D @@ -0,0 +1,10 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!62 &6200000 +PhysicsMaterial2D: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: BallMaterial + friction: 0 + bounciness: 1 diff --git a/Assets/Packages/Mirror/Examples/Pong/PhysicsMaterials/BallMaterial.physicsMaterial2D.meta b/Assets/Packages/Mirror/Examples/Pong/PhysicsMaterials/BallMaterial.physicsMaterial2D.meta new file mode 100644 index 0000000..bf2d3b6 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/PhysicsMaterials/BallMaterial.physicsMaterial2D.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 97a3e4cddb8635c4eba1265f44d106bf +timeCreated: 1426602119 +licenseType: Store +NativeFormatImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Prefabs.meta b/Assets/Packages/Mirror/Examples/Pong/Prefabs.meta new file mode 100644 index 0000000..7e90f0d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Prefabs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: db1c7e1499ee84bfba33fa7f2cb1bc57 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Prefabs/Ball.prefab b/Assets/Packages/Mirror/Examples/Pong/Prefabs/Ball.prefab new file mode 100644 index 0000000..6111613 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Prefabs/Ball.prefab @@ -0,0 +1,178 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &1080679924113744 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 4700925592147096} + - component: {fileID: 212107498293566416} + - component: {fileID: 61279514624852186} + - component: {fileID: 50354248948880112} + - component: {fileID: 114290021321007948} + - component: {fileID: 114692463781779748} + - component: {fileID: 114121325390084138} + m_Layer: 0 + m_Name: Ball + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4700925592147096 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1080679924113744} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -3, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!212 &212107498293566416 +SpriteRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1080679924113744} + m_Enabled: 1 + m_CastShadows: 0 + m_ReceiveShadows: 0 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 0 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_Sprite: {fileID: 21300000, guid: 4b66f21097323d44ab40669b2fb9c53d, type: 3} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_FlipX: 0 + m_FlipY: 0 + m_DrawMode: 0 + m_Size: {x: 1, y: 1} + m_AdaptiveModeThreshold: 0.5 + m_SpriteTileMode: 0 + m_WasSpriteAssigned: 1 + m_MaskInteraction: 0 + m_SpriteSortPoint: 0 +--- !u!61 &61279514624852186 +BoxCollider2D: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1080679924113744} + m_Enabled: 1 + m_Density: 1 + m_Material: {fileID: 6200000, guid: 97a3e4cddb8635c4eba1265f44d106bf, type: 2} + m_IsTrigger: 0 + m_UsedByEffector: 0 + m_UsedByComposite: 0 + m_Offset: {x: 0, y: 0} + m_SpriteTilingProperty: + border: {x: 0, y: 0, z: 0, w: 0} + pivot: {x: 0.5, y: 0.5} + oldSize: {x: 1, y: 1} + newSize: {x: 1, y: 1} + adaptiveTilingThreshold: 0.5 + drawMode: 0 + adaptiveTiling: 0 + m_AutoTiling: 0 + serializedVersion: 2 + m_Size: {x: 1, y: 1} + m_EdgeRadius: 0 +--- !u!50 &50354248948880112 +Rigidbody2D: + serializedVersion: 4 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1080679924113744} + m_BodyType: 0 + m_Simulated: 0 + m_UseFullKinematicContacts: 0 + m_UseAutoMass: 0 + m_Mass: 0.0001 + m_LinearDrag: 0 + m_AngularDrag: 0.05 + m_GravityScale: 0 + m_Material: {fileID: 0} + m_Interpolate: 0 + m_SleepingMode: 1 + m_CollisionDetection: 0 + m_Constraints: 4 +--- !u!114 &114290021321007948 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1080679924113744} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + serverOnly: 0 + localPlayerAuthority: 0 + m_AssetId: 5f7a7f34494ed40268eff49dbf9168bf + m_SceneId: 0 +--- !u!114 &114692463781779748 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1080679924113744} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 38b5c2f743cd8034a8beeebf277c92c1, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + speed: 30 + rigidbody2d: {fileID: 50354248948880112} +--- !u!114 &114121325390084138 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1080679924113744} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2f74aedd71d9a4f55b3ce499326d45fb, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0 + compressRotation: 1 diff --git a/Assets/Packages/Mirror/Examples/Pong/Prefabs/Ball.prefab.meta b/Assets/Packages/Mirror/Examples/Pong/Prefabs/Ball.prefab.meta new file mode 100644 index 0000000..6322417 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Prefabs/Ball.prefab.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5f7a7f34494ed40268eff49dbf9168bf +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 100100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Prefabs/Racket.prefab b/Assets/Packages/Mirror/Examples/Pong/Prefabs/Racket.prefab new file mode 100644 index 0000000..81a1792 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Prefabs/Racket.prefab @@ -0,0 +1,178 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &1240244544407914 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 4118252415362944} + - component: {fileID: 212641192162007874} + - component: {fileID: 61279767645666242} + - component: {fileID: 50389918509199184} + - component: {fileID: 114104497298166850} + - component: {fileID: 114626868563338794} + - component: {fileID: 114398896143473162} + m_Layer: 0 + m_Name: Racket + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4118252415362944 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1240244544407914} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!212 &212641192162007874 +SpriteRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1240244544407914} + m_Enabled: 1 + m_CastShadows: 0 + m_ReceiveShadows: 0 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 0 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_Sprite: {fileID: 21300000, guid: 619ccff3ba2f2a04f9ddd19c264a1ecd, type: 3} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_FlipX: 0 + m_FlipY: 0 + m_DrawMode: 0 + m_Size: {x: 1, y: 1} + m_AdaptiveModeThreshold: 0.5 + m_SpriteTileMode: 0 + m_WasSpriteAssigned: 1 + m_MaskInteraction: 0 + m_SpriteSortPoint: 0 +--- !u!61 &61279767645666242 +BoxCollider2D: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1240244544407914} + m_Enabled: 1 + m_Density: 1 + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_UsedByEffector: 0 + m_UsedByComposite: 0 + m_Offset: {x: 0, y: 0} + m_SpriteTilingProperty: + border: {x: 0, y: 0, z: 0, w: 0} + pivot: {x: 0.5, y: 0.5} + oldSize: {x: 2, y: 4} + newSize: {x: 1, y: 1} + adaptiveTilingThreshold: 0.5 + drawMode: 0 + adaptiveTiling: 0 + m_AutoTiling: 0 + serializedVersion: 2 + m_Size: {x: 2, y: 4} + m_EdgeRadius: 0 +--- !u!50 &50389918509199184 +Rigidbody2D: + serializedVersion: 4 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1240244544407914} + m_BodyType: 0 + m_Simulated: 1 + m_UseFullKinematicContacts: 0 + m_UseAutoMass: 0 + m_Mass: 1 + m_LinearDrag: 0 + m_AngularDrag: 0.05 + m_GravityScale: 0 + m_Material: {fileID: 0} + m_Interpolate: 1 + m_SleepingMode: 1 + m_CollisionDetection: 1 + m_Constraints: 4 +--- !u!114 &114104497298166850 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1240244544407914} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + serverOnly: 0 + localPlayerAuthority: 1 + m_AssetId: b1651eaf8c7564a1c86031dfbb8a7b28 + m_SceneId: 0 +--- !u!114 &114626868563338794 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1240244544407914} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 0748c7eda22b19845b9ce0e4d23d1021, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + speed: 1500 + rigidbody2d: {fileID: 50389918509199184} +--- !u!114 &114398896143473162 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1240244544407914} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2f74aedd71d9a4f55b3ce499326d45fb, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0 + compressRotation: 1 diff --git a/Assets/Packages/Mirror/Examples/Pong/Prefabs/Racket.prefab.meta b/Assets/Packages/Mirror/Examples/Pong/Prefabs/Racket.prefab.meta new file mode 100644 index 0000000..c67ac8f --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Prefabs/Racket.prefab.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b1651eaf8c7564a1c86031dfbb8a7b28 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 100100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Scenes.meta b/Assets/Packages/Mirror/Examples/Pong/Scenes.meta new file mode 100644 index 0000000..ba5b4d4 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scenes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 00c56c45628954f44aa4d944cbd9bfca +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Scenes/Scene.unity b/Assets/Packages/Mirror/Examples/Pong/Scenes/Scene.unity new file mode 100644 index 0000000..8ffe2b4 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scenes/Scene.unity @@ -0,0 +1,942 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 3 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &4 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 10 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 0 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 1024 + m_ReflectionCompression: 2 + m_MixedBakeMode: 1 + m_BakeBackend: 0 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 0 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 0 +--- !u!196 &5 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &289876230 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 289876232} + - component: {fileID: 289876231} + m_Layer: 0 + m_Name: DottedLine + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!212 &289876231 +SpriteRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 289876230} + m_Enabled: 1 + m_CastShadows: 0 + m_ReceiveShadows: 0 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 0 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_Sprite: {fileID: 21300000, guid: 1b5c0b514d8b2d24091d5aec516fe860, type: 3} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_FlipX: 0 + m_FlipY: 0 + m_DrawMode: 0 + m_Size: {x: 1, y: 1} + m_AdaptiveModeThreshold: 0.5 + m_SpriteTileMode: 0 + m_WasSpriteAssigned: 1 + m_MaskInteraction: 0 + m_SpriteSortPoint: 0 +--- !u!4 &289876232 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 289876230} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1607538195} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &473997959 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 473997961} + m_Layer: 0 + m_Name: RacketSpawnLeft + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &473997961 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 473997959} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -20, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &753891880 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 753891882} + - component: {fileID: 753891881} + - component: {fileID: 753891883} + m_Layer: 0 + m_Name: WallBottom + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!212 &753891881 +SpriteRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 753891880} + m_Enabled: 1 + m_CastShadows: 0 + m_ReceiveShadows: 0 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 0 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_Sprite: {fileID: 21300000, guid: b931587800e08c54aa8dbbd6c15c894f, type: 3} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_FlipX: 0 + m_FlipY: 0 + m_DrawMode: 0 + m_Size: {x: 1, y: 1} + m_AdaptiveModeThreshold: 0.5 + m_SpriteTileMode: 0 + m_WasSpriteAssigned: 1 + m_MaskInteraction: 0 + m_SpriteSortPoint: 0 +--- !u!4 &753891882 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 753891880} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: -16, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1607538195} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!61 &753891883 +BoxCollider2D: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 753891880} + m_Enabled: 1 + m_Density: 1 + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_UsedByEffector: 0 + m_UsedByComposite: 0 + m_Offset: {x: 0, y: 0} + m_SpriteTilingProperty: + border: {x: 0, y: 0, z: 0, w: 0} + pivot: {x: 0.5, y: 0.5} + oldSize: {x: 50, y: 1} + newSize: {x: 1, y: 1} + adaptiveTilingThreshold: 0.5 + drawMode: 0 + adaptiveTiling: 0 + m_AutoTiling: 0 + serializedVersion: 2 + m_Size: {x: 50, y: 1} + m_EdgeRadius: 0 +--- !u!1 &1346799726 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1346799731} + - component: {fileID: 1346799730} + - component: {fileID: 1346799729} + - component: {fileID: 1346799728} + - component: {fileID: 1346799727} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &1346799727 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1346799726} + m_Enabled: 1 +--- !u!124 &1346799728 +Behaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1346799726} + m_Enabled: 1 +--- !u!92 &1346799729 +Behaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1346799726} + m_Enabled: 1 +--- !u!20 &1346799730 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1346799726} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0, g: 0, b: 0, a: 0.019607844} + m_projectionMatrixMode: 1 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_GateFitMode: 2 + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 1 + orthographic size: 40 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 0 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &1346799731 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1346799726} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: -10} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1352350029 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1352350031} + - component: {fileID: 1352350030} + - component: {fileID: 1352350032} + m_Layer: 0 + m_Name: WallLeft + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!212 &1352350030 +SpriteRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1352350029} + m_Enabled: 1 + m_CastShadows: 0 + m_ReceiveShadows: 0 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 0 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_Sprite: {fileID: 21300000, guid: 0f2833a292a197d4fb0385a8efa1dc91, type: 3} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_FlipX: 0 + m_FlipY: 0 + m_DrawMode: 0 + m_Size: {x: 1, y: 1} + m_AdaptiveModeThreshold: 0.5 + m_SpriteTileMode: 0 + m_WasSpriteAssigned: 1 + m_MaskInteraction: 0 + m_SpriteSortPoint: 0 +--- !u!4 &1352350031 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1352350029} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -24.5, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1607538195} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!61 &1352350032 +BoxCollider2D: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1352350029} + m_Enabled: 1 + m_Density: 1 + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_UsedByEffector: 0 + m_UsedByComposite: 0 + m_Offset: {x: 0, y: 0} + m_SpriteTilingProperty: + border: {x: 0, y: 0, z: 0, w: 0} + pivot: {x: 0.5, y: 0.5} + oldSize: {x: 1, y: 32} + newSize: {x: 1, y: 1} + adaptiveTilingThreshold: 0.5 + drawMode: 0 + adaptiveTiling: 0 + m_AutoTiling: 0 + serializedVersion: 2 + m_Size: {x: 1, y: 32} + m_EdgeRadius: 0 +--- !u!1 &1368547944 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1368547946} + - component: {fileID: 1368547945} + - component: {fileID: 1368547947} + m_Layer: 0 + m_Name: WallTop + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!212 &1368547945 +SpriteRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1368547944} + m_Enabled: 1 + m_CastShadows: 0 + m_ReceiveShadows: 0 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 0 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_Sprite: {fileID: 21300000, guid: b931587800e08c54aa8dbbd6c15c894f, type: 3} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_FlipX: 0 + m_FlipY: 0 + m_DrawMode: 0 + m_Size: {x: 1, y: 1} + m_AdaptiveModeThreshold: 0.5 + m_SpriteTileMode: 0 + m_WasSpriteAssigned: 1 + m_MaskInteraction: 0 + m_SpriteSortPoint: 0 +--- !u!4 &1368547946 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1368547944} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 16, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1607538195} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!61 &1368547947 +BoxCollider2D: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1368547944} + m_Enabled: 1 + m_Density: 1 + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_UsedByEffector: 0 + m_UsedByComposite: 0 + m_Offset: {x: 0, y: 0} + m_SpriteTilingProperty: + border: {x: 0, y: 0, z: 0, w: 0} + pivot: {x: 0.5, y: 0.5} + oldSize: {x: 50, y: 1} + newSize: {x: 1, y: 1} + adaptiveTilingThreshold: 0.5 + drawMode: 0 + adaptiveTiling: 0 + m_AutoTiling: 0 + serializedVersion: 2 + m_Size: {x: 50, y: 1} + m_EdgeRadius: 0 +--- !u!1 &1397990094 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1397990096} + m_Layer: 0 + m_Name: RacketSpawnRight + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1397990096 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1397990094} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 20, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1575697329 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1575697331} + - component: {fileID: 1575697330} + - component: {fileID: 1575697332} + m_Layer: 0 + m_Name: WallRight + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!212 &1575697330 +SpriteRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1575697329} + m_Enabled: 1 + m_CastShadows: 0 + m_ReceiveShadows: 0 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 0 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 + m_Sprite: {fileID: 21300000, guid: 0f2833a292a197d4fb0385a8efa1dc91, type: 3} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_FlipX: 0 + m_FlipY: 0 + m_DrawMode: 0 + m_Size: {x: 1, y: 1} + m_AdaptiveModeThreshold: 0.5 + m_SpriteTileMode: 0 + m_WasSpriteAssigned: 1 + m_MaskInteraction: 0 + m_SpriteSortPoint: 0 +--- !u!4 &1575697331 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1575697329} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 24.5, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1607538195} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!61 &1575697332 +BoxCollider2D: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1575697329} + m_Enabled: 1 + m_Density: 1 + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_UsedByEffector: 0 + m_UsedByComposite: 0 + m_Offset: {x: 0, y: 0} + m_SpriteTilingProperty: + border: {x: 0, y: 0, z: 0, w: 0} + pivot: {x: 0.5, y: 0.5} + oldSize: {x: 1, y: 32} + newSize: {x: 1, y: 1} + adaptiveTilingThreshold: 0.5 + drawMode: 0 + adaptiveTiling: 0 + m_AutoTiling: 0 + serializedVersion: 2 + m_Size: {x: 1, y: 32} + m_EdgeRadius: 0 +--- !u!1 &1607538194 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1607538195} + m_Layer: 0 + m_Name: Table + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1607538195 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1607538194} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1368547946} + - {fileID: 753891882} + - {fileID: 1575697331} + - {fileID: 1352350031} + - {fileID: 289876232} + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1886246549 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1886246550} + - component: {fileID: 1886246552} + - component: {fileID: 1886246551} + - component: {fileID: 1886246553} + m_Layer: 0 + m_Name: NetworkManager + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1886246550 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1886246549} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1886246551 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1886246549} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 6442dc8070ceb41f094e44de0bf87274, type: 3} + m_Name: + m_EditorClassIdentifier: + showGUI: 1 + offsetX: 0 + offsetY: 0 +--- !u!114 &1886246552 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1886246549} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 0aa3018bb284840d6a6d0acee29ab098, type: 3} + m_Name: + m_EditorClassIdentifier: + dontDestroyOnLoad: 1 + runInBackground: 1 + startOnHeadless: 1 + serverTickRate: 30 + showDebugMessages: 0 + offlineScene: + onlineScene: + transport: {fileID: 1886246553} + networkAddress: localhost + maxConnections: 4 + playerPrefab: {fileID: 1240244544407914, guid: b1651eaf8c7564a1c86031dfbb8a7b28, + type: 3} + autoCreatePlayer: 1 + playerSpawnMethod: 1 + spawnPrefabs: + - {fileID: 1080679924113744, guid: 5f7a7f34494ed40268eff49dbf9168bf, type: 3} + leftRacketSpawn: {fileID: 473997961} + rightRacketSpawn: {fileID: 1397990096} +--- !u!114 &1886246553 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1886246549} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c7424c1070fad4ba2a7a96b02fbeb4bb, type: 3} + m_Name: + m_EditorClassIdentifier: + OnClientConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnClientDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventByteArray, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnServerConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + OnServerDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntByteArray, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + port: 7777 + NoDelay: 1 diff --git a/Assets/Packages/Mirror/Examples/Pong/Scenes/Scene.unity.meta b/Assets/Packages/Mirror/Examples/Pong/Scenes/Scene.unity.meta new file mode 100644 index 0000000..f4267c6 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scenes/Scene.unity.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 89a84548859e3b643b4fb27984dc2b0d +timeCreated: 1426587410 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Scripts.meta b/Assets/Packages/Mirror/Examples/Pong/Scripts.meta new file mode 100644 index 0000000..b482c47 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 55e7bd9b7212f4318909cbca3bdb1284 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Scripts/Ball.cs b/Assets/Packages/Mirror/Examples/Pong/Scripts/Ball.cs new file mode 100644 index 0000000..69adbf1 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scripts/Ball.cs @@ -0,0 +1,60 @@ +using UnityEngine; + +namespace Mirror.Examples.Pong +{ + public class Ball : NetworkBehaviour + { + public float speed = 30; + public Rigidbody2D rigidbody2d; + + public override void OnStartServer() + { + base.OnStartServer(); + + // only simulate ball physics on server + rigidbody2d.simulated = true; + + // Serve the ball from left player + rigidbody2d.velocity = Vector2.right * speed; + } + + float HitFactor(Vector2 ballPos, Vector2 racketPos, float racketHeight) + { + // ascii art: + // || 1 <- at the top of the racket + // || + // || 0 <- at the middle of the racket + // || + // || -1 <- at the bottom of the racket + return (ballPos.y - racketPos.y) / racketHeight; + } + + [ServerCallback] // only call this on server + void OnCollisionEnter2D(Collision2D col) + { + // Note: 'col' holds the collision information. If the + // Ball collided with a racket, then: + // col.gameObject is the racket + // col.transform.position is the racket's position + // col.collider is the racket's collider + + // did we hit a racket? then we need to calculate the hit factor + if (col.transform.GetComponent()) + { + // Calculate y direction via hit Factor + float y = HitFactor(transform.position, + col.transform.position, + col.collider.bounds.size.y); + + // Calculate x direction via opposite collision + float x = col.relativeVelocity.x > 0 ? 1 : -1; + + // Calculate direction, make length=1 via .normalized + Vector2 dir = new Vector2(x, y).normalized; + + // Set Velocity with dir * speed + rigidbody2d.velocity = dir * speed; + } + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Pong/Scripts/Ball.cs.meta b/Assets/Packages/Mirror/Examples/Pong/Scripts/Ball.cs.meta new file mode 100644 index 0000000..14a37a0 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scripts/Ball.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 38b5c2f743cd8034a8beeebf277c92c1 +timeCreated: 1426602353 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Scripts/NetworkManagerPong.cs b/Assets/Packages/Mirror/Examples/Pong/Scripts/NetworkManagerPong.cs new file mode 100644 index 0000000..71ba09e --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scripts/NetworkManagerPong.cs @@ -0,0 +1,37 @@ +using UnityEngine; +using Mirror; + +// Custom NetworkManager that simply assigns the correct racket positions when +// spawning players. The built in RoundRobin spawn method wouldn't work after +// someone reconnects (both players would be on the same side). +public class NetworkManagerPong : NetworkManager +{ + public Transform leftRacketSpawn; + public Transform rightRacketSpawn; + GameObject ball; + + public override void OnServerAddPlayer(NetworkConnection conn, AddPlayerMessage extraMessage) + { + // add player at correct spawn position + Transform start = numPlayers == 0 ? leftRacketSpawn : rightRacketSpawn; + GameObject player = Instantiate(playerPrefab, start.position, start.rotation); + NetworkServer.AddPlayerForConnection(conn, player); + + // spawn ball if two players + if (numPlayers == 2) + { + ball = Instantiate(spawnPrefabs.Find(prefab => prefab.name == "Ball")); + NetworkServer.Spawn(ball); + } + } + + public override void OnServerDisconnect(NetworkConnection conn) + { + // destroy ball + if (ball != null) + NetworkServer.Destroy(ball); + + // call base functionality (actually destroys the player) + base.OnServerDisconnect(conn); + } +} diff --git a/Assets/Packages/Mirror/Examples/Pong/Scripts/NetworkManagerPong.cs.meta b/Assets/Packages/Mirror/Examples/Pong/Scripts/NetworkManagerPong.cs.meta new file mode 100644 index 0000000..4b191ea --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scripts/NetworkManagerPong.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0aa3018bb284840d6a6d0acee29ab098 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Scripts/Player.cs b/Assets/Packages/Mirror/Examples/Pong/Scripts/Player.cs new file mode 100644 index 0000000..4b9e3b9 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scripts/Player.cs @@ -0,0 +1,19 @@ +using UnityEngine; + +namespace Mirror.Examples.Pong +{ + public class Player : NetworkBehaviour + { + public float speed = 30; + public Rigidbody2D rigidbody2d; + + // need to use FixedUpdate for rigidbody + void FixedUpdate() + { + // only let the local player control the racket. + // don't control other player's rackets + if (isLocalPlayer) + rigidbody2d.velocity = new Vector2(0, Input.GetAxisRaw("Vertical")) * speed * Time.fixedDeltaTime; + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Pong/Scripts/Player.cs.meta b/Assets/Packages/Mirror/Examples/Pong/Scripts/Player.cs.meta new file mode 100644 index 0000000..f0de41d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Scripts/Player.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0748c7eda22b19845b9ce0e4d23d1021 +timeCreated: 1426597826 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Sprites.meta b/Assets/Packages/Mirror/Examples/Pong/Sprites.meta new file mode 100644 index 0000000..42350a3 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Sprites.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9d39b68545c2e43cfa4a37f6703a983b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Sprites/Ball.png b/Assets/Packages/Mirror/Examples/Pong/Sprites/Ball.png new file mode 100644 index 0000000..20c4387 Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Pong/Sprites/Ball.png differ diff --git a/Assets/Packages/Mirror/Examples/Pong/Sprites/Ball.png.meta b/Assets/Packages/Mirror/Examples/Pong/Sprites/Ball.png.meta new file mode 100644 index 0000000..384c0c1 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Sprites/Ball.png.meta @@ -0,0 +1,91 @@ +fileFormatVersion: 2 +guid: 4b66f21097323d44ab40669b2fb9c53d +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 0 + aniso: 16 + mipBias: -100 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 1 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Sprites/DottedLine.png b/Assets/Packages/Mirror/Examples/Pong/Sprites/DottedLine.png new file mode 100644 index 0000000..0bcab09 Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Pong/Sprites/DottedLine.png differ diff --git a/Assets/Packages/Mirror/Examples/Pong/Sprites/DottedLine.png.meta b/Assets/Packages/Mirror/Examples/Pong/Sprites/DottedLine.png.meta new file mode 100644 index 0000000..34ea0cb --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Sprites/DottedLine.png.meta @@ -0,0 +1,91 @@ +fileFormatVersion: 2 +guid: 1b5c0b514d8b2d24091d5aec516fe860 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 0 + aniso: 16 + mipBias: -100 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 1 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/Sprites/Racket.png b/Assets/Packages/Mirror/Examples/Pong/Sprites/Racket.png new file mode 100644 index 0000000..c73938d Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Pong/Sprites/Racket.png differ diff --git a/Assets/Packages/Mirror/Examples/Pong/Sprites/Racket.png.meta b/Assets/Packages/Mirror/Examples/Pong/Sprites/Racket.png.meta new file mode 100644 index 0000000..f89655d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/Sprites/Racket.png.meta @@ -0,0 +1,91 @@ +fileFormatVersion: 2 +guid: 619ccff3ba2f2a04f9ddd19c264a1ecd +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 0 + aniso: 16 + mipBias: -100 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 1 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/WallHorizontal.png b/Assets/Packages/Mirror/Examples/Pong/WallHorizontal.png new file mode 100644 index 0000000..6bb5dc3 Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Pong/WallHorizontal.png differ diff --git a/Assets/Packages/Mirror/Examples/Pong/WallHorizontal.png.meta b/Assets/Packages/Mirror/Examples/Pong/WallHorizontal.png.meta new file mode 100644 index 0000000..dbc9224 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/WallHorizontal.png.meta @@ -0,0 +1,91 @@ +fileFormatVersion: 2 +guid: b931587800e08c54aa8dbbd6c15c894f +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 0 + aniso: 16 + mipBias: -100 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 1 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Pong/WallVertical.png b/Assets/Packages/Mirror/Examples/Pong/WallVertical.png new file mode 100644 index 0000000..32406c1 Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Pong/WallVertical.png differ diff --git a/Assets/Packages/Mirror/Examples/Pong/WallVertical.png.meta b/Assets/Packages/Mirror/Examples/Pong/WallVertical.png.meta new file mode 100644 index 0000000..7dad3f7 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Pong/WallVertical.png.meta @@ -0,0 +1,91 @@ +fileFormatVersion: 2 +guid: 0f2833a292a197d4fb0385a8efa1dc91 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 0 + aniso: 16 + mipBias: -100 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 1 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks.meta b/Assets/Packages/Mirror/Examples/Tanks.meta new file mode 100644 index 0000000..bee4222 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a6dc5104926d44c9296aec7699989ac3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models.meta b/Assets/Packages/Mirror/Examples/Tanks/Models.meta new file mode 100644 index 0000000..c94259a --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6878aacf12b204d03a94f71e49f9ad60 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank.meta b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank.meta new file mode 100644 index 0000000..93b0075 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d8b3e43538fc240feb28e07816c7e733 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/BaseColor.png b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/BaseColor.png new file mode 100644 index 0000000..bcd4bee Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/BaseColor.png differ diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/BaseColor.png.meta b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/BaseColor.png.meta new file mode 100644 index 0000000..6e069a1 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/BaseColor.png.meta @@ -0,0 +1,88 @@ +fileFormatVersion: 2 +guid: ce00d67f9368944fa8ef4de6ccc77bfa +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 9 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Controller.controller b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Controller.controller new file mode 100644 index 0000000..e05d28c --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Controller.controller @@ -0,0 +1,272 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!91 &9100000 +AnimatorController: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Controller + serializedVersion: 5 + m_AnimatorParameters: + - m_Name: Moving + m_Type: 4 + m_DefaultFloat: 0 + m_DefaultInt: 0 + m_DefaultBool: 0 + m_Controller: {fileID: 0} + - m_Name: Shoot + m_Type: 9 + m_DefaultFloat: 0 + m_DefaultInt: 0 + m_DefaultBool: 0 + m_Controller: {fileID: 0} + m_AnimatorLayers: + - serializedVersion: 5 + m_Name: Base Layer + m_StateMachine: {fileID: 1107772262116321704} + m_Mask: {fileID: 0} + m_Motions: [] + m_Behaviours: [] + m_BlendingMode: 0 + m_SyncedLayerIndex: -1 + m_DefaultWeight: 0 + m_IKPass: 0 + m_SyncedLayerAffectsTiming: 0 + m_Controller: {fileID: 9100000} +--- !u!1101 &1101104249963802978 +AnimatorStateTransition: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + m_Conditions: + - m_ConditionMode: 1 + m_ConditionEvent: Moving + m_EventTreshold: 0 + m_DstStateMachine: {fileID: 0} + m_DstState: {fileID: 1102824315819425342} + m_Solo: 0 + m_Mute: 0 + m_IsExit: 0 + serializedVersion: 3 + m_TransitionDuration: 0.25 + m_TransitionOffset: 0 + m_ExitTime: 0.6 + m_HasExitTime: 0 + m_HasFixedDuration: 1 + m_InterruptionSource: 0 + m_OrderedInterruption: 1 + m_CanTransitionToSelf: 1 +--- !u!1101 &1101366829127142966 +AnimatorStateTransition: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + m_Conditions: + - m_ConditionMode: 1 + m_ConditionEvent: Shoot + m_EventTreshold: 0 + m_DstStateMachine: {fileID: 0} + m_DstState: {fileID: 1102254808008813326} + m_Solo: 0 + m_Mute: 0 + m_IsExit: 0 + serializedVersion: 3 + m_TransitionDuration: 0 + m_TransitionOffset: 0 + m_ExitTime: 1 + m_HasExitTime: 0 + m_HasFixedDuration: 1 + m_InterruptionSource: 0 + m_OrderedInterruption: 1 + m_CanTransitionToSelf: 1 +--- !u!1101 &1101806660142692138 +AnimatorStateTransition: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + m_Conditions: + - m_ConditionMode: 2 + m_ConditionEvent: Moving + m_EventTreshold: 0 + m_DstStateMachine: {fileID: 0} + m_DstState: {fileID: 1102207974245764242} + m_Solo: 0 + m_Mute: 0 + m_IsExit: 0 + serializedVersion: 3 + m_TransitionDuration: 0.25 + m_TransitionOffset: 0 + m_ExitTime: 0.6 + m_HasExitTime: 0 + m_HasFixedDuration: 1 + m_InterruptionSource: 0 + m_OrderedInterruption: 1 + m_CanTransitionToSelf: 1 +--- !u!1101 &1101862483397811748 +AnimatorStateTransition: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + m_Conditions: + - m_ConditionMode: 2 + m_ConditionEvent: Moving + m_EventTreshold: 0 + m_DstStateMachine: {fileID: 0} + m_DstState: {fileID: 1102207974245764242} + m_Solo: 0 + m_Mute: 0 + m_IsExit: 0 + serializedVersion: 3 + m_TransitionDuration: 0.25 + m_TransitionOffset: 0 + m_ExitTime: 0.75 + m_HasExitTime: 0 + m_HasFixedDuration: 1 + m_InterruptionSource: 0 + m_OrderedInterruption: 1 + m_CanTransitionToSelf: 1 +--- !u!1101 &1101947542735704306 +AnimatorStateTransition: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + m_Conditions: + - m_ConditionMode: 1 + m_ConditionEvent: Moving + m_EventTreshold: 0 + m_DstStateMachine: {fileID: 0} + m_DstState: {fileID: 1102824315819425342} + m_Solo: 0 + m_Mute: 0 + m_IsExit: 0 + serializedVersion: 3 + m_TransitionDuration: 0.25 + m_TransitionOffset: 0 + m_ExitTime: 0.75 + m_HasExitTime: 0 + m_HasFixedDuration: 1 + m_InterruptionSource: 0 + m_OrderedInterruption: 1 + m_CanTransitionToSelf: 1 +--- !u!1102 &1102207974245764242 +AnimatorState: + serializedVersion: 5 + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Idle + m_Speed: 1 + m_CycleOffset: 0 + m_Transitions: + - {fileID: 1101947542735704306} + m_StateMachineBehaviours: [] + m_Position: {x: 50, y: 50, z: 0} + m_IKOnFeet: 0 + m_WriteDefaultValues: 1 + m_Mirror: 0 + m_SpeedParameterActive: 0 + m_MirrorParameterActive: 0 + m_CycleOffsetParameterActive: 0 + m_TimeParameterActive: 0 + m_Motion: {fileID: 0} + m_Tag: + m_SpeedParameter: + m_MirrorParameter: + m_CycleOffsetParameter: + m_TimeParameter: +--- !u!1102 &1102254808008813326 +AnimatorState: + serializedVersion: 5 + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Shoot + m_Speed: 1 + m_CycleOffset: 0 + m_Transitions: + - {fileID: 1101104249963802978} + - {fileID: 1101806660142692138} + m_StateMachineBehaviours: [] + m_Position: {x: 50, y: 50, z: 0} + m_IKOnFeet: 0 + m_WriteDefaultValues: 1 + m_Mirror: 0 + m_SpeedParameterActive: 0 + m_MirrorParameterActive: 0 + m_CycleOffsetParameterActive: 0 + m_TimeParameterActive: 0 + m_Motion: {fileID: 7400006, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + m_Tag: + m_SpeedParameter: + m_MirrorParameter: + m_CycleOffsetParameter: + m_TimeParameter: +--- !u!1102 &1102824315819425342 +AnimatorState: + serializedVersion: 5 + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Moving + m_Speed: 1 + m_CycleOffset: 0 + m_Transitions: + - {fileID: 1101862483397811748} + m_StateMachineBehaviours: [] + m_Position: {x: 50, y: 50, z: 0} + m_IKOnFeet: 0 + m_WriteDefaultValues: 1 + m_Mirror: 0 + m_SpeedParameterActive: 0 + m_MirrorParameterActive: 0 + m_CycleOffsetParameterActive: 0 + m_TimeParameterActive: 0 + m_Motion: {fileID: 7400004, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + m_Tag: + m_SpeedParameter: + m_MirrorParameter: + m_CycleOffsetParameter: + m_TimeParameter: +--- !u!1107 &1107772262116321704 +AnimatorStateMachine: + serializedVersion: 5 + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Base Layer + m_ChildStates: + - serializedVersion: 1 + m_State: {fileID: 1102207974245764242} + m_Position: {x: 252, y: 48, z: 0} + - serializedVersion: 1 + m_State: {fileID: 1102824315819425342} + m_Position: {x: 252, y: 204, z: 0} + - serializedVersion: 1 + m_State: {fileID: 1102254808008813326} + m_Position: {x: 420, y: 120, z: 0} + m_ChildStateMachines: [] + m_AnyStateTransitions: + - {fileID: 1101366829127142966} + m_EntryTransitions: [] + m_StateMachineTransitions: {} + m_StateMachineBehaviours: [] + m_AnyStatePosition: {x: 60, y: 132, z: 0} + m_EntryPosition: {x: 60, y: 168, z: 0} + m_ExitPosition: {x: 60, y: 96, z: 0} + m_ParentStateMachinePosition: {x: 800, y: 20, z: 0} + m_DefaultState: {fileID: 1102207974245764242} diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Controller.controller.meta b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Controller.controller.meta new file mode 100644 index 0000000..7e1061c --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Controller.controller.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a7211483bbd794b6d85ed88576e7d85c +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 9100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Emissive.png b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Emissive.png new file mode 100644 index 0000000..61ca0cb Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Emissive.png differ diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Emissive.png.meta b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Emissive.png.meta new file mode 100644 index 0000000..333174c --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Emissive.png.meta @@ -0,0 +1,88 @@ +fileFormatVersion: 2 +guid: 9b3e91ab0048a4aa3a17706a349c6bf5 +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 9 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Metallic.png b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Metallic.png new file mode 100644 index 0000000..d5d5559 Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Metallic.png differ diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Metallic.png.meta b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Metallic.png.meta new file mode 100644 index 0000000..91006e4 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Metallic.png.meta @@ -0,0 +1,88 @@ +fileFormatVersion: 2 +guid: a7467e18a834e4d1390091c8b1ea562c +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 9 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Normal.png b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Normal.png new file mode 100644 index 0000000..f1a448f Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Normal.png differ diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Normal.png.meta b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Normal.png.meta new file mode 100644 index 0000000..acc128a --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Normal.png.meta @@ -0,0 +1,88 @@ +fileFormatVersion: 2 +guid: 2617bfecca4d44805a3a51a7aa215d7c +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 9 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 1 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Recon_Tank - License.txt b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Recon_Tank - License.txt new file mode 100644 index 0000000..ed10006 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Recon_Tank - License.txt @@ -0,0 +1,7 @@ +Recon Tank (update), by Mophs +https://opengameart.org/users/mophs + +Based on original work, Recon Tank, By MNDV.ecb, 2018 Eric Buisson +https://opengameart.org/content/recon-tank + +CC-BY 4.0 \ No newline at end of file diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Recon_Tank - License.txt.meta b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Recon_Tank - License.txt.meta new file mode 100644 index 0000000..2168518 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/Recon_Tank - License.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 6e745106dbbc3412bbe43eaf25dabd4f +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/TankMaterial.mat b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/TankMaterial.mat new file mode 100644 index 0000000..207b1f7 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/TankMaterial.mat @@ -0,0 +1,82 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: TankMaterial + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: _EMISSION _METALLICGLOSSMAP _NORMALMAP _SPECGLOSSMAP + m_LightmapFlags: 0 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _BumpMap: + m_Texture: {fileID: 2800000, guid: 2617bfecca4d44805a3a51a7aa215d7c, type: 3} + 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: 2800000, guid: 9b3e91ab0048a4aa3a17706a349c6bf5, type: 3} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 2800000, guid: ce00d67f9368944fa8ef4de6ccc77bfa, type: 3} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MetallicGlossMap: + m_Texture: {fileID: 2800000, guid: a7467e18a834e4d1390091c8b1ea562c, type: 3} + 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} + - _SpecGlossMap: + m_Texture: {fileID: 2800000, guid: a7467e18a834e4d1390091c8b1ea562c, type: 3} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - _BumpScale: 1.75 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 0.09 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 1, g: 1, b: 1, a: 1} + - _EmissionColor: {r: 1, g: 1, b: 1, a: 1} + - _SpecColor: {r: 0.2, g: 0.2, b: 0.2, a: 1} diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/TankMaterial.mat.meta b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/TankMaterial.mat.meta new file mode 100644 index 0000000..080f534 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/TankMaterial.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2e67e42170aa64aa9a33424f8045ac89 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/reconTank.fbx b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/reconTank.fbx new file mode 100644 index 0000000..5877b09 Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/reconTank.fbx differ diff --git a/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/reconTank.fbx.meta b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/reconTank.fbx.meta new file mode 100644 index 0000000..1ac1ee0 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Models/(Public Domain) Recon_Tank/reconTank.fbx.meta @@ -0,0 +1,239 @@ +fileFormatVersion: 2 +guid: 38b49695fc0a4418bbc350f2366660c5 +ModelImporter: + serializedVersion: 23 + fileIDToRecycleName: + 100000: Barrel + 100002: Barrel_end + 100004: Chasis + 100006: Recon_Tank + 100008: Recon_Tank_Rig + 100010: //RootNode + 100012: Root + 100014: Turret + 100016: Wheel_Front_L + 100018: Wheel_Front_L_end + 100020: Wheel_Middle_L + 100022: Wheel_Middle_L_end + 100024: Wheel_Rear_L + 100026: Wheel_Rear_L_end + 400000: Barrel + 400002: Barrel_end + 400004: Chasis + 400006: Recon_Tank + 400008: Recon_Tank_Rig + 400010: //RootNode + 400012: Root + 400014: Turret + 400016: Wheel_Front_L + 400018: Wheel_Front_L_end + 400020: Wheel_Middle_L + 400022: Wheel_Middle_L_end + 400024: Wheel_Rear_L + 400026: Wheel_Rear_L_end + 2100000: Recon_Tank + 4300000: Recon_Tank + 7400000: Recon_Tank_Rig|Drive + 7400002: Recon_Tank_Rig|Forward + 7400004: Recon_Tank_Rig|Idle + 7400006: Recon_Tank_Rig|Shoot + 9500000: //RootNode + 13700000: Recon_Tank + externalObjects: {} + materials: + importMaterials: 1 + materialName: 0 + materialSearch: 1 + materialLocation: 1 + animations: + legacyGenerateAnimations: 4 + bakeSimulation: 0 + resampleCurves: 1 + optimizeGameObjects: 0 + motionNodeName: + rigImportErrors: + rigImportWarnings: + animationImportErrors: + animationImportWarnings: + animationRetargetingWarnings: + animationDoRetargetingWarnings: 0 + importAnimatedCustomProperties: 0 + importConstraints: 0 + animationCompression: 1 + animationRotationError: 0.5 + animationPositionError: 0.5 + animationScaleError: 0.5 + animationWrapMode: 0 + extraExposedTransformPaths: [] + extraUserProperties: [] + clipAnimations: + - serializedVersion: 16 + name: Recon_Tank_Rig|Drive + takeName: Recon_Tank_Rig|Drive + firstFrame: 0 + lastFrame: 1 + wrapMode: 0 + orientationOffsetY: 0 + level: 0 + cycleOffset: 0 + loop: 0 + hasAdditiveReferencePose: 0 + loopTime: 0 + loopBlend: 0 + loopBlendOrientation: 0 + loopBlendPositionY: 0 + loopBlendPositionXZ: 0 + keepOriginalOrientation: 0 + keepOriginalPositionY: 1 + keepOriginalPositionXZ: 0 + heightFromFeet: 0 + mirror: 0 + bodyMask: 01000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000 + curves: [] + events: [] + transformMask: [] + maskType: 3 + maskSource: {instanceID: 0} + additiveReferencePoseFrame: 0 + - serializedVersion: 16 + name: Recon_Tank_Rig|Forward + takeName: Recon_Tank_Rig|Forward + firstFrame: 0 + lastFrame: 25 + wrapMode: 0 + orientationOffsetY: 0 + level: 0 + cycleOffset: 0 + loop: 0 + hasAdditiveReferencePose: 0 + loopTime: 0 + loopBlend: 0 + loopBlendOrientation: 0 + loopBlendPositionY: 0 + loopBlendPositionXZ: 0 + keepOriginalOrientation: 0 + keepOriginalPositionY: 1 + keepOriginalPositionXZ: 0 + heightFromFeet: 0 + mirror: 0 + bodyMask: 01000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000 + curves: [] + events: [] + transformMask: [] + maskType: 3 + maskSource: {instanceID: 0} + additiveReferencePoseFrame: 0 + - serializedVersion: 16 + name: Recon_Tank_Rig|Idle + takeName: Recon_Tank_Rig|Idle + firstFrame: 0 + lastFrame: 11 + wrapMode: 0 + orientationOffsetY: 0 + level: 0 + cycleOffset: 0 + loop: 0 + hasAdditiveReferencePose: 0 + loopTime: 1 + loopBlend: 1 + loopBlendOrientation: 0 + loopBlendPositionY: 0 + loopBlendPositionXZ: 0 + keepOriginalOrientation: 0 + keepOriginalPositionY: 1 + keepOriginalPositionXZ: 0 + heightFromFeet: 0 + mirror: 0 + bodyMask: 01000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000 + curves: [] + events: [] + transformMask: [] + maskType: 3 + maskSource: {instanceID: 0} + additiveReferencePoseFrame: 0 + - serializedVersion: 16 + name: Recon_Tank_Rig|Shoot + takeName: Recon_Tank_Rig|Shoot + firstFrame: 0 + lastFrame: 15 + wrapMode: 0 + orientationOffsetY: 0 + level: 0 + cycleOffset: 0 + loop: 0 + hasAdditiveReferencePose: 0 + loopTime: 0 + loopBlend: 0 + loopBlendOrientation: 0 + loopBlendPositionY: 0 + loopBlendPositionXZ: 0 + keepOriginalOrientation: 0 + keepOriginalPositionY: 1 + keepOriginalPositionXZ: 0 + heightFromFeet: 0 + mirror: 0 + bodyMask: 01000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000 + curves: [] + events: [] + transformMask: [] + maskType: 3 + maskSource: {instanceID: 0} + additiveReferencePoseFrame: 0 + isReadable: 1 + meshes: + lODScreenPercentages: [] + globalScale: 0.15 + meshCompression: 0 + addColliders: 0 + useSRGBMaterialColor: 1 + importVisibility: 1 + importBlendShapes: 1 + importCameras: 1 + importLights: 1 + swapUVChannels: 0 + generateSecondaryUV: 0 + useFileUnits: 1 + optimizeMeshForGPU: 1 + keepQuads: 0 + weldVertices: 1 + preserveHierarchy: 0 + indexFormat: 0 + secondaryUVAngleDistortion: 8 + secondaryUVAreaDistortion: 15.000001 + secondaryUVHardAngle: 88 + secondaryUVPackMargin: 4 + useFileScale: 1 + previousCalculatedGlobalScale: 0.0015 + hasPreviousCalculatedGlobalScale: 1 + tangentSpace: + normalSmoothAngle: 60 + normalImportMode: 0 + tangentImportMode: 3 + normalCalculationMode: 4 + legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes: 0 + blendShapeNormalImportMode: 1 + normalSmoothingSource: 0 + importAnimation: 1 + copyAvatar: 0 + humanDescription: + serializedVersion: 2 + human: [] + skeleton: [] + armTwist: 0.5 + foreArmTwist: 0.5 + upperLegTwist: 0.5 + legTwist: 0.5 + armStretch: 0.05 + legStretch: 0.05 + feetSpacing: 0 + rootMotionBoneName: + hasTranslationDoF: 0 + hasExtraRoot: 0 + skeletonHasParents: 1 + lastHumanDescriptionAvatarSource: {instanceID: 0} + animationType: 2 + humanoidOversampling: 1 + additionalBone: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Prefabs.meta b/Assets/Packages/Mirror/Examples/Tanks/Prefabs.meta new file mode 100644 index 0000000..6c92485 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Prefabs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2baeb281f5e8e421582aa9f72e7f1702 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Projectile.prefab b/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Projectile.prefab new file mode 100644 index 0000000..938c99d --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Projectile.prefab @@ -0,0 +1,246 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &63476987332307980 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 8035186136109819211} + - component: {fileID: 9118274893554935717} + - component: {fileID: 69063397099238371} + m_Layer: 0 + m_Name: 3D Model + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &8035186136109819211 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 63476987332307980} + m_LocalRotation: {x: 0.7071068, y: 0, z: 0, w: 0.7071068} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 0.05, y: 0.1, z: 0.05} + m_Children: [] + m_Father: {fileID: 24373266488650541} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0} +--- !u!33 &9118274893554935717 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 63476987332307980} + m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &69063397099238371 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 63476987332307980} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 1 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: cba1b63a0bccc4b12ac25f05d0ae2dd1, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 0 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!1 &5890560936853567077 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 24373266488650541} + - component: {fileID: 1713098107664522388} + - component: {fileID: 2355290524794870353} + - component: {fileID: 4629190479245867726} + - component: {fileID: 7082621516996595528} + m_Layer: 0 + m_Name: Projectile + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &24373266488650541 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5890560936853567077} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 8035186136109819211} + - {fileID: 7830988697844474908} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1713098107664522388 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5890560936853567077} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_ServerOnly: 0 + m_LocalPlayerAuthority: 0 + m_AssetId: b7dd46dbf38c643f09e206f9fa4be008 + m_SceneId: 0 +--- !u!136 &2355290524794870353 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5890560936853567077} + m_Material: {fileID: 0} + m_IsTrigger: 1 + m_Enabled: 1 + m_Radius: 0.05 + m_Height: 0.2 + m_Direction: 1 + m_Center: {x: 0, y: 0, z: 0} +--- !u!54 &4629190479245867726 +Rigidbody: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5890560936853567077} + serializedVersion: 2 + m_Mass: 1 + m_Drag: 0 + m_AngularDrag: 0.05 + m_UseGravity: 0 + m_IsKinematic: 0 + m_Interpolate: 1 + m_Constraints: 0 + m_CollisionDetection: 1 +--- !u!114 &7082621516996595528 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5890560936853567077} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 8f49b83f111a64bc7a5275af4f6f930b, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + destroyAfter: 5 + rigidBody: {fileID: 4629190479245867726} + force: 1000 +--- !u!1 &9126921595194253319 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7830988697844474908} + - component: {fileID: 4878977110396366525} + m_Layer: 0 + m_Name: Point Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &7830988697844474908 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 9126921595194253319} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 24373266488650541} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!108 &4878977110396366525 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 9126921595194253319} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 2 + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_Intensity: 5 + m_Range: 2 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 0 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 3 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 diff --git a/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Projectile.prefab.meta b/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Projectile.prefab.meta new file mode 100644 index 0000000..f6d4068 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Projectile.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b7dd46dbf38c643f09e206f9fa4be008 +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Tank.prefab b/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Tank.prefab new file mode 100644 index 0000000..f94b600 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Tank.prefab @@ -0,0 +1,312 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &1916082411674582 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 4492442352427800} + - component: {fileID: 114118589361100106} + - component: {fileID: 2240606817507776182} + - component: {fileID: 114250499875391520} + - component: {fileID: 6900008319038825817} + - component: {fileID: 5194388907919410155} + - component: {fileID: 114654712548978148} + m_Layer: 0 + m_Name: Tank + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4492442352427800 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1916082411674582} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 7831918942946891954} + - {fileID: 6564220120147636086} + - {fileID: 5718089106632469514} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &114118589361100106 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1916082411674582} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3} + m_Name: + m_EditorClassIdentifier: + m_ServerOnly: 0 + m_LocalPlayerAuthority: 1 + m_AssetId: 6f43bf5488a7443d19ab2a83c6b91f35 + m_SceneId: 0 +--- !u!95 &2240606817507776182 +Animator: + serializedVersion: 3 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1916082411674582} + m_Enabled: 1 + m_Avatar: {fileID: 9000000, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + m_Controller: {fileID: 9100000, guid: a7211483bbd794b6d85ed88576e7d85c, type: 2} + m_CullingMode: 0 + m_UpdateMode: 0 + m_ApplyRootMotion: 0 + m_LinearVelocityBlending: 0 + m_WarningMessage: + m_HasTransformHierarchy: 1 + m_AllowConstantClipSamplingOptimization: 1 + m_KeepAnimatorControllerStateOnDisable: 0 +--- !u!114 &114250499875391520 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1916082411674582} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2f74aedd71d9a4f55b3ce499326d45fb, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + compressRotation: 1 +--- !u!195 &6900008319038825817 +NavMeshAgent: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1916082411674582} + m_Enabled: 1 + m_AgentTypeID: 0 + m_Radius: 0.5 + m_Speed: 1 + m_Acceleration: 1 + avoidancePriority: 50 + m_AngularSpeed: 120 + m_StoppingDistance: 0 + m_AutoTraverseOffMeshLink: 1 + m_AutoBraking: 1 + m_AutoRepath: 1 + m_Height: 0.5 + m_BaseOffset: 0 + m_WalkableMask: 4294967295 + m_ObstacleAvoidanceType: 0 +--- !u!135 &5194388907919410155 +SphereCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1916082411674582} + m_Material: {fileID: 0} + m_IsTrigger: 1 + m_Enabled: 1 + serializedVersion: 2 + m_Radius: 0.5 + m_Center: {x: 0, y: 0.25, z: 0} +--- !u!114 &114654712548978148 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1916082411674582} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7deadf756194d461e9140e42d651693b, type: 3} + m_Name: + m_EditorClassIdentifier: + syncInterval: 0.1 + agent: {fileID: 6900008319038825817} + animator: {fileID: 2240606817507776182} + rotationSpeed: 80 + shootKey: 32 + projectilePrefab: {fileID: 5890560936853567077, guid: b7dd46dbf38c643f09e206f9fa4be008, + type: 3} + projectileMount: {fileID: 5718089106632469514} +--- !u!1 &4426914200102054949 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 6564220120147636086} + - component: {fileID: 7604806193092689376} + m_Layer: 0 + m_Name: Spot Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &6564220120147636086 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4426914200102054949} + m_LocalRotation: {x: 0.02281505, y: -0, z: -0, w: 0.9997397} + m_LocalPosition: {x: 0.07, y: 0.46, z: 0.126} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 4492442352427800} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 2.615, y: 0, z: 0} +--- !u!108 &7604806193092689376 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4426914200102054949} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 0 + m_Color: {r: 1, g: 0.9205329, b: 0.7877358, a: 1} + m_Intensity: 3 + m_Range: 15 + m_SpotAngle: 80 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!1 &4730779867780281009 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5718089106632469514} + m_Layer: 0 + m_Name: ProjectileMount + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &5718089106632469514 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4730779867780281009} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0.412, z: 0.936} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 4492442352427800} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1001 &7831918942947279416 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + m_TransformParent: {fileID: 4492442352427800} + m_Modifications: + - target: {fileID: 100010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_Name + value: 3D Model + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalPosition.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalPosition.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalPosition.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalRotation.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalRotation.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_RootOrder + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 13700000, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + propertyPath: m_Materials.Array.data[0] + value: + objectReference: {fileID: 2100000, guid: 2e67e42170aa64aa9a33424f8045ac89, type: 2} + m_RemovedComponents: + - {fileID: 9500000, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} + m_SourcePrefab: {fileID: 100100000, guid: 38b49695fc0a4418bbc350f2366660c5, type: 3} +--- !u!4 &7831918942946891954 stripped +Transform: + m_CorrespondingSourceObject: {fileID: 400010, guid: 38b49695fc0a4418bbc350f2366660c5, + type: 3} + m_PrefabInstance: {fileID: 7831918942947279416} + m_PrefabAsset: {fileID: 0} diff --git a/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Tank.prefab.meta b/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Tank.prefab.meta new file mode 100644 index 0000000..4454818 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Prefabs/Tank.prefab.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6f43bf5488a7443d19ab2a83c6b91f35 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 100100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scenes.meta b/Assets/Packages/Mirror/Examples/Tanks/Scenes.meta new file mode 100644 index 0000000..5665d39 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scenes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 91225a3fc58fe4a7f9e10718cd3bdc61 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene.meta b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene.meta new file mode 100644 index 0000000..01af532 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 81cfd31f234d94a0985fe946d2ce699f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene.unity b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene.unity new file mode 100644 index 0000000..fc8e49e --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene.unity @@ -0,0 +1,666 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 3 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 1 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 10 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 0 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 23800000, guid: 0bc607fa2e315482ebe98797e844e11f, type: 2} +--- !u!1 &88936773 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 88936777} + - component: {fileID: 88936776} + - component: {fileID: 88936775} + - component: {fileID: 88936774} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &88936774 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 88936773} + m_Enabled: 1 +--- !u!124 &88936775 +Behaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 88936773} + m_Enabled: 1 +--- !u!20 &88936776 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 88936773} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0, g: 0, b: 0, a: 0} + m_projectionMatrixMode: 1 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_GateFitMode: 2 + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &88936777 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 88936773} + m_LocalRotation: {x: 0, y: 0.92387956, z: -0.38268343, w: 0} + m_LocalPosition: {x: 0, y: 6.5, z: 8} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 45, y: 180, z: 0} +--- !u!1 &251893064 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 251893065} + - component: {fileID: 251893066} + m_Layer: 0 + m_Name: Spawn + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &251893065 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 251893064} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 3, y: 0, z: 3} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 6 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &251893066 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 251893064} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &535739935 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 535739936} + - component: {fileID: 535739937} + m_Layer: 0 + m_Name: Spawn + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &535739936 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 535739935} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 3, y: 0, z: -3} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &535739937 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 535739935} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1107091652 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1107091656} + - component: {fileID: 1107091655} + - component: {fileID: 1107091654} + - component: {fileID: 1107091653} + m_Layer: 0 + m_Name: Ground + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 4294967295 + m_IsActive: 1 +--- !u!23 &1107091653 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1107091652} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_RenderingLayerMask: 4294967295 + m_RendererPriority: 0 + m_Materials: + - {fileID: 2100000, guid: 29b49c27a74f145918356859bd7af511, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!64 &1107091654 +MeshCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1107091652} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Convex: 0 + m_CookingOptions: 14 + m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} +--- !u!33 &1107091655 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1107091652} + m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1107091656 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1107091652} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1282001517 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1282001518} + - component: {fileID: 1282001520} + - component: {fileID: 1282001519} + - component: {fileID: 1282001521} + m_Layer: 0 + m_Name: NetworkManager + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1282001518 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1282001517} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1282001519 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1282001517} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 6442dc8070ceb41f094e44de0bf87274, type: 3} + m_Name: + m_EditorClassIdentifier: + showGUI: 1 + offsetX: 0 + offsetY: 0 +--- !u!114 &1282001520 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1282001517} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 8aab4c8111b7c411b9b92cf3dbc5bd4e, type: 3} + m_Name: + m_EditorClassIdentifier: + dontDestroyOnLoad: 1 + runInBackground: 1 + startOnHeadless: 1 + serverTickRate: 30 + showDebugMessages: 0 + offlineScene: + onlineScene: + transport: {fileID: 1282001521} + networkAddress: localhost + maxConnections: 4 + playerPrefab: {fileID: 1916082411674582, guid: 6f43bf5488a7443d19ab2a83c6b91f35, + type: 3} + autoCreatePlayer: 1 + playerSpawnMethod: 1 + spawnPrefabs: + - {fileID: 5890560936853567077, guid: b7dd46dbf38c643f09e206f9fa4be008, type: 3} +--- !u!114 &1282001521 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1282001517} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c7424c1070fad4ba2a7a96b02fbeb4bb, type: 3} + m_Name: + m_EditorClassIdentifier: + OnClientConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnClientDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventByteArray, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnClientDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + OnServerConnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + OnServerDataReceived: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntByteArray, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerError: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventIntException, Mirror, Version=0.0.0.0, Culture=neutral, + PublicKeyToken=null + OnServerDisconnected: + m_PersistentCalls: + m_Calls: [] + m_TypeName: Mirror.UnityEventInt, Mirror, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + port: 7777 + NoDelay: 1 +--- !u!1 &1458789072 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1458789073} + - component: {fileID: 1458789074} + m_Layer: 0 + m_Name: Spawn + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1458789073 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1458789072} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -3, y: 0, z: 3} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 7 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1458789074 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1458789072} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1501912662 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1501912663} + - component: {fileID: 1501912664} + m_Layer: 0 + m_Name: Spawn + m_TagString: Untagged + m_Icon: {fileID: -964228994112308473, guid: 0000000000000000d000000000000000, type: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1501912663 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1501912662} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -3, y: 0, z: -3} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 5 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1501912664 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1501912662} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 41f84591ce72545258ea98cb7518d8b9, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &2054208274 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2054208276} + - component: {fileID: 2054208275} + m_Layer: 0 + m_Name: Directional light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &2054208275 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2054208274} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 1 + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &2054208276 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2054208274} + m_LocalRotation: {x: 0.10938167, y: 0.8754261, z: -0.40821788, w: 0.23456976} + m_LocalPosition: {x: 0, y: 10, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 50, y: 150, z: 0} diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene.unity.meta b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene.unity.meta new file mode 100644 index 0000000..c7f922e --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 83f9d2fb76f5742448c6e51f258327a2 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene/NavMesh.asset b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene/NavMesh.asset new file mode 100644 index 0000000..3acffc8 Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene/NavMesh.asset differ diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene/NavMesh.asset.meta b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene/NavMesh.asset.meta new file mode 100644 index 0000000..1997fe9 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scenes/Scene/NavMesh.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0bc607fa2e315482ebe98797e844e11f +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 23800000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scripts.meta b/Assets/Packages/Mirror/Examples/Tanks/Scripts.meta new file mode 100644 index 0000000..e6be7b6 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3815d4126f2934af187ce078c648bbc8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scripts/Projectile.cs b/Assets/Packages/Mirror/Examples/Tanks/Scripts/Projectile.cs new file mode 100644 index 0000000..ee1db26 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scripts/Projectile.cs @@ -0,0 +1,38 @@ +using UnityEngine; + +namespace Mirror.Examples.Tanks +{ + public class Projectile : NetworkBehaviour + { + public float destroyAfter = 5; + public Rigidbody rigidBody; + public float force = 1000; + + public override void OnStartServer() + { + Invoke(nameof(DestroySelf), destroyAfter); + } + + // set velocity for server and client. this way we don't have to sync the + // position, because both the server and the client simulate it. + void Start() + { + rigidBody.AddForce(transform.forward * force); + } + + // destroy for everyone on the server + [Server] + void DestroySelf() + { + NetworkServer.Destroy(gameObject); + } + + // ServerCallback because we don't want a warning if OnTriggerEnter is + // called on the client + [ServerCallback] + void OnTriggerEnter(Collider co) + { + NetworkServer.Destroy(gameObject); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scripts/Projectile.cs.meta b/Assets/Packages/Mirror/Examples/Tanks/Scripts/Projectile.cs.meta new file mode 100644 index 0000000..387ece6 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scripts/Projectile.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f49b83f111a64bc7a5275af4f6f930b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scripts/Tank.cs b/Assets/Packages/Mirror/Examples/Tanks/Scripts/Tank.cs new file mode 100644 index 0000000..cfda2a4 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scripts/Tank.cs @@ -0,0 +1,58 @@ +using UnityEngine; +using UnityEngine.AI; + +namespace Mirror.Examples.Tanks +{ + public class Tank : NetworkBehaviour + { + [Header("Components")] + public NavMeshAgent agent; + public Animator animator; + + [Header("Movement")] + public float rotationSpeed = 100; + + [Header("Firing")] + public KeyCode shootKey = KeyCode.Space; + public GameObject projectilePrefab; + public Transform projectileMount; + + void Update() + { + // movement for local player + if (!isLocalPlayer) return; + + // rotate + float horizontal = Input.GetAxis("Horizontal"); + transform.Rotate(0, horizontal * rotationSpeed * Time.deltaTime, 0); + + // move + float vertical = Input.GetAxis("Vertical"); + Vector3 forward = transform.TransformDirection(Vector3.forward); + agent.velocity = forward * Mathf.Max(vertical, 0) * agent.speed; + animator.SetBool("Moving", agent.velocity != Vector3.zero); + + // shoot + if (Input.GetKeyDown(shootKey)) + { + CmdFire(); + } + } + + // this is called on the server + [Command] + void CmdFire() + { + GameObject projectile = Instantiate(projectilePrefab, projectileMount.position, transform.rotation); + NetworkServer.Spawn(projectile); + RpcOnFire(); + } + + // this is called on the tank that fired for all observers + [ClientRpc] + void RpcOnFire() + { + animator.SetTrigger("Shoot"); + } + } +} diff --git a/Assets/Packages/Mirror/Examples/Tanks/Scripts/Tank.cs.meta b/Assets/Packages/Mirror/Examples/Tanks/Scripts/Tank.cs.meta new file mode 100644 index 0000000..b7874c4 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Scripts/Tank.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7deadf756194d461e9140e42d651693b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures.meta b/Assets/Packages/Mirror/Examples/Tanks/Textures.meta new file mode 100644 index 0000000..fad816b --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Textures.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8ce6821cc1c644d5595ce9fc1f61debc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture.meta b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture.meta new file mode 100644 index 0000000..a77c1ef --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4e08c21c1034445fc834851f9e4202fe +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt Hand Painted Texture - License.txt b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt Hand Painted Texture - License.txt new file mode 100644 index 0000000..6091137 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt Hand Painted Texture - License.txt @@ -0,0 +1,5 @@ +Dirt Hand Painted Textures created by 'KIIRA' +https://opengameart.org/content/dirt-hand-painted-texture + +Licensed as CC-BY-3.0: +https://creativecommons.org/licenses/by/3.0/ \ No newline at end of file diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt Hand Painted Texture - License.txt.meta b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt Hand Painted Texture - License.txt.meta new file mode 100644 index 0000000..4682e6c --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt Hand Painted Texture - License.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 422e9f56a29ae488e836a23d1e0f21d0 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt.mat b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt.mat new file mode 100644 index 0000000..443aaff --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt.mat @@ -0,0 +1,82 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Dirt + m_Shader: {fileID: 45, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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: 5, y: 5} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 2800000, guid: bcc8fc05f1f924531a65f39394c0b703, type: 3} + m_Scale: {x: 5, y: 5} + 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} + - _SpecGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 1, g: 1, b: 1, a: 1} + - _EmissionColor: {r: 0.13207549, g: 0.06631743, b: 0, a: 1} + - _SpecColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt.mat.meta b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt.mat.meta new file mode 100644 index 0000000..f571c8b --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/Dirt.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 29b49c27a74f145918356859bd7af511 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/dirt.png b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/dirt.png new file mode 100644 index 0000000..3174ecc Binary files /dev/null and b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/dirt.png differ diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/dirt.png.meta b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/dirt.png.meta new file mode 100644 index 0000000..b00a626 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Textures/(Public Domain) Dirt Hand Painted Texture/dirt.png.meta @@ -0,0 +1,88 @@ +fileFormatVersion: 2 +guid: bcc8fc05f1f924531a65f39394c0b703 +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 9 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures/ProjectileMaterial.mat b/Assets/Packages/Mirror/Examples/Tanks/Textures/ProjectileMaterial.mat new file mode 100644 index 0000000..d231b59 --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Textures/ProjectileMaterial.mat @@ -0,0 +1,77 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: ProjectileMaterial + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + 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_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0, g: 1, b: 0.8901961, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/Packages/Mirror/Examples/Tanks/Textures/ProjectileMaterial.mat.meta b/Assets/Packages/Mirror/Examples/Tanks/Textures/ProjectileMaterial.mat.meta new file mode 100644 index 0000000..84c957e --- /dev/null +++ b/Assets/Packages/Mirror/Examples/Tanks/Textures/ProjectileMaterial.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cba1b63a0bccc4b12ac25f05d0ae2dd1 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/License.txt b/Assets/Packages/Mirror/License.txt new file mode 100644 index 0000000..2925e86 --- /dev/null +++ b/Assets/Packages/Mirror/License.txt @@ -0,0 +1,3 @@ +The Mirror DLLs in the Plugins folder are MIT licensed: + +https://github.com/vis2k/Mirror \ No newline at end of file diff --git a/Assets/Packages/Mirror/License.txt.meta b/Assets/Packages/Mirror/License.txt.meta new file mode 100644 index 0000000..6129dfe --- /dev/null +++ b/Assets/Packages/Mirror/License.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: dbf30d11d3879431f87403d009e47bf7 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Plugins.meta b/Assets/Packages/Mirror/Plugins.meta new file mode 100644 index 0000000..9504239 --- /dev/null +++ b/Assets/Packages/Mirror/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 05eb4061e2eb94061b9a08c918fff99b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Plugins/Mono.Cecil.meta b/Assets/Packages/Mirror/Plugins/Mono.Cecil.meta new file mode 100644 index 0000000..a104e2e --- /dev/null +++ b/Assets/Packages/Mirror/Plugins/Mono.Cecil.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ce126b4e1a7d13b4c865cd92929f13c3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll new file mode 100644 index 0000000..f6815d3 Binary files /dev/null and b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll differ diff --git a/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll.meta b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll.meta new file mode 100644 index 0000000..f75f642 --- /dev/null +++ b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: a078fc7c0dc14d047a28dea9c93fd259 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll new file mode 100644 index 0000000..3b58436 Binary files /dev/null and b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll differ diff --git a/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll.meta b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll.meta new file mode 100644 index 0000000..773758f --- /dev/null +++ b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: 534d998d93b238041bddcd864f7f1088 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll new file mode 100644 index 0000000..7d820f0 Binary files /dev/null and b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll differ diff --git a/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll.meta b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll.meta new file mode 100644 index 0000000..a222084 --- /dev/null +++ b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: 7526641fb3ae25144aa0a96aad853745 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll new file mode 100644 index 0000000..c042418 Binary files /dev/null and b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll differ diff --git a/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll.meta b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll.meta new file mode 100644 index 0000000..73262f2 --- /dev/null +++ b/Assets/Packages/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: 307911e5ad044dd42b1649eb8637aaf3 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Readme.txt b/Assets/Packages/Mirror/Readme.txt new file mode 100644 index 0000000..857cbaf --- /dev/null +++ b/Assets/Packages/Mirror/Readme.txt @@ -0,0 +1,15 @@ +Mirror is a MMO Scale Networking library for Unity, used in uMMORPG, uSurvival +and several MMO projects in development. + +*** IMPORTANT -- You must restart Unity after importing Mirror for the Components Menu to update! *** + +Requirements: + Unity 2018.3.6+ + Runtime .Net 4.x (Project Settings > Player > Other Settings) + +Documentation: + https://vis2k.github.io/Mirror/ + +Support: + Discord: https://discordapp.com/invite/N9QVxbM + Bug Reports: https://github.com/vis2k/Mirror/issues diff --git a/Assets/Packages/Mirror/Readme.txt.meta b/Assets/Packages/Mirror/Readme.txt.meta new file mode 100644 index 0000000..d52ccce --- /dev/null +++ b/Assets/Packages/Mirror/Readme.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f6d84e019c68446f28415a923b460a03 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime.meta b/Assets/Packages/Mirror/Runtime.meta new file mode 100644 index 0000000..85ee3eb --- /dev/null +++ b/Assets/Packages/Mirror/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9f4328ccc5f724e45afe2215d275b5d5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/AssemblyInfo.cs b/Assets/Packages/Mirror/Runtime/AssemblyInfo.cs new file mode 100644 index 0000000..f0c4858 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Mirror.Tests")] \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/AssemblyInfo.cs.meta b/Assets/Packages/Mirror/Runtime/AssemblyInfo.cs.meta new file mode 100644 index 0000000..cf3201c --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e28d5f410e25b42e6a76a2ffc10e4675 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/ClientScene.cs b/Assets/Packages/Mirror/Runtime/ClientScene.cs new file mode 100644 index 0000000..fa5d099 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/ClientScene.cs @@ -0,0 +1,760 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using UnityEngine; +using Guid = System.Guid; +using Object = UnityEngine.Object; + +namespace Mirror +{ + /// + /// A client manager which contains static client information and functions. + /// This manager contains references to tracked static local objects such as spawner registrations. It also has the default message handlers used by clients when they registered none themselves. The manager handles adding/removing player objects to the game after a client connection has been set as ready. + /// The ClientScene is a singleton, and it has static convenience methods such as ClientScene.Ready(). + /// The ClientScene is used by the NetworkManager, but it can be used by itself. + /// As the ClientScene manages player objects on the client, it is where clients request to add players. The NetworkManager does this via the ClientScene automatically when auto-add-players is set, but it can be done through code using the function ClientScene.AddPlayer(). This sends an AddPlayer message to the server and will cause a player object to be created for this client. + /// Like NetworkServer, the ClientScene understands the concept of the local client. The function ClientScene.ConnectLocalServer() is used to become a host by starting a local client (when a server is already running). + /// + public static class ClientScene + { + static bool isSpawnFinished; + + /// + /// NetworkIdentity of the localPlayer + /// + public static NetworkIdentity localPlayer { get; private set; } + + /// + /// Returns true when a client's connection has been set to ready. + /// A client that is ready recieves state updates from the server, while a client that is not ready does not. This useful when the state of the game is not normal, such as a scene change or end-of-game. + /// This is read-only. To change the ready state of a client, use ClientScene.Ready(). The server is able to set the ready state of clients using NetworkServer.SetClientReady(), NetworkServer.SetClientNotReady() and NetworkServer.SetAllClientsNotReady(). + /// This is done when changing scenes so that clients don't receive state update messages during scene loading. + /// + public static bool ready { get; internal set; } + + /// + /// The NetworkConnection object that is currently "ready". This is the connection to the server where objects are spawned from. + /// This connection can be used to send messages to the server. There can only be one ready connection at a time. There can be multiple NetworkClient instances in existence, each with their own NetworkConnections, but there is only one ClientScene instance and corresponding ready connection. + /// + public static NetworkConnection readyConnection { get; private set; } + + /// + /// This is a dictionary of the prefabs that are registered on the client with ClientScene.RegisterPrefab(). + /// The key to the dictionary is the prefab asset Id. + /// + public static Dictionary prefabs = new Dictionary(); + + /// + /// This is dictionary of the disabled NetworkIdentity objects in the scene that could be spawned by messages from the server. + /// The key to the dictionary is the NetworkIdentity sceneId. + /// + public static Dictionary spawnableObjects; + + // spawn handlers + static readonly Dictionary spawnHandlers = new Dictionary(); + static readonly Dictionary unspawnHandlers = new Dictionary(); + + // this is never called, and if we do call it in NetworkClient.Shutdown + // then the client's player object won't be removed after disconnecting! + internal static void Shutdown() + { + ClearSpawners(); + spawnableObjects = null; + readyConnection = null; + ready = false; + isSpawnFinished = false; + DestroyAllClientObjects(); + } + + // this is called from message handler for Owner message + internal static void InternalAddPlayer(NetworkIdentity identity) + { + if (LogFilter.Debug) Debug.LogWarning("ClientScene.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; + if (readyConnection != null) + { + readyConnection.playerController = identity; + } + else + { + Debug.LogWarning("No ready connection found for setting player controller during InternalAddPlayer"); + } + } + + /// + /// This adds a player GameObject for this client. + /// This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer is called. + /// + /// True if player was added. + public static bool AddPlayer() => AddPlayer(null); + + /// + /// This adds a player GameObject for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer is called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message. + /// + /// The connection to become ready for this client. + /// True if player was added. + public static bool AddPlayer(NetworkConnection readyConn) => AddPlayer(readyConn, null); + + /// + /// This adds a player GameObject for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer is called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message. + /// extraMessage can contain character selection, etc. + /// + /// The connection to become ready for this client. + /// An extra message object that can be passed to the server for this player. + /// True if player was added. + public static bool AddPlayer(NetworkConnection readyConn, byte[] extraData) + { + // ensure valid ready connection + if (readyConn != null) + { + ready = true; + readyConnection = readyConn; + } + + if (!ready) + { + Debug.LogError("Must call AddPlayer() with a connection the first time to become ready."); + return false; + } + + if (readyConnection.playerController != null) + { + Debug.LogError("ClientScene.AddPlayer: a PlayerController was already added. Did you call AddPlayer twice?"); + return false; + } + + if (LogFilter.Debug) Debug.Log("ClientScene.AddPlayer() called with connection [" + readyConnection + "]"); + + AddPlayerMessage message = new AddPlayerMessage() + { + value = extraData + }; + readyConnection.Send(message); + return true; + } + + /// + /// Removes the player from the game. + /// + /// True if succcessful + public static bool RemovePlayer() + { + if (LogFilter.Debug) Debug.Log("ClientScene.RemovePlayer() called with connection [" + readyConnection + "]"); + + if (readyConnection.playerController != null) + { + readyConnection.Send(new RemovePlayerMessage()); + + Object.Destroy(readyConnection.playerController.gameObject); + + readyConnection.playerController = null; + localPlayer = null; + + return true; + } + return false; + } + + /// + /// Signal that the client connection is 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. + /// + /// The client connection which is ready. + /// True if succcessful + public static bool Ready(NetworkConnection conn) + { + if (ready) + { + Debug.LogError("A connection has already been set as ready. There can only be one."); + return false; + } + + if (LogFilter.Debug) Debug.Log("ClientScene.Ready() called with connection [" + conn + "]"); + + if (conn != null) + { + conn.Send(new ReadyMessage()); + ready = true; + readyConnection = conn; + readyConnection.isReady = true; + return true; + } + Debug.LogError("Ready() called with invalid connection object: conn=null"); + return false; + } + + internal static void HandleClientDisconnect(NetworkConnection conn) + { + if (readyConnection == conn && ready) + { + ready = false; + readyConnection = null; + } + } + + static bool ConsiderForSpawning(NetworkIdentity identity) + { + // not spawned yet, not hidden, etc.? + return !identity.gameObject.activeSelf && + identity.gameObject.hideFlags != HideFlags.NotEditable && + identity.gameObject.hideFlags != HideFlags.HideAndDontSave && + identity.sceneId != 0; + } + + /// + /// Call this after loading/unloading a scene in the client after connection to register the spawnable objects + /// + public static void PrepareToSpawnSceneObjects() + { + // add all unspawned NetworkIdentities to spawnable objects + spawnableObjects = Resources.FindObjectsOfTypeAll() + .Where(ConsiderForSpawning) + .ToDictionary(identity => identity.sceneId, identity => identity); + } + + static NetworkIdentity SpawnSceneObject(ulong sceneId) + { + if (spawnableObjects.TryGetValue(sceneId, out NetworkIdentity identity)) + { + spawnableObjects.Remove(sceneId); + return identity; + } + Debug.LogWarning("Could not find scene object with sceneid:" + sceneId.ToString("X")); + return null; + } + + // spawn handlers and prefabs + static bool GetPrefab(Guid assetId, out GameObject prefab) + { + prefab = null; + return assetId != Guid.Empty && + prefabs.TryGetValue(assetId, out prefab) && prefab != null; + } + + /// + /// Registers a prefab with the spawning system. + /// When a NetworkIdentity object is spawned on a server with NetworkServer.SpawnObject(), and the prefab that the object was created from was registered with RegisterPrefab(), the client will use that prefab to instantiate a corresponding client object with the same netId. + /// The NetworkManager has a list of spawnable prefabs, it uses this function to register those prefabs with the ClientScene. + /// The set of current spawnable object is available in the ClientScene static member variable ClientScene.prefabs, which is a dictionary of NetworkAssetIds and prefab references. + /// + /// A Prefab that will be spawned. + /// An assetId to be assigned to this prefab. This allows a dynamically created game object to be registered for an already known asset Id. + public static void RegisterPrefab(GameObject prefab, Guid newAssetId) + { + NetworkIdentity identity = prefab.GetComponent(); + if (identity) + { + identity.assetId = newAssetId; + + if (LogFilter.Debug) Debug.Log("Registering prefab '" + prefab.name + "' as asset:" + identity.assetId); + prefabs[identity.assetId] = prefab; + } + else + { + Debug.LogError("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component"); + } + } + + /// + /// Registers a prefab with the spawning system. + /// When a NetworkIdentity object is spawned on a server with NetworkServer.SpawnObject(), and the prefab that the object was created from was registered with RegisterPrefab(), the client will use that prefab to instantiate a corresponding client object with the same netId. + /// The NetworkManager has a list of spawnable prefabs, it uses this function to register those prefabs with the ClientScene. + /// The set of current spawnable object is available in the ClientScene static member variable ClientScene.prefabs, which is a dictionary of NetworkAssetIds and prefab references. + /// + /// A Prefab that will be spawned. + public static void RegisterPrefab(GameObject prefab) + { + NetworkIdentity identity = prefab.GetComponent(); + if (identity) + { + if (LogFilter.Debug) Debug.Log("Registering prefab '" + prefab.name + "' as asset:" + identity.assetId); + prefabs[identity.assetId] = prefab; + + NetworkIdentity[] identities = prefab.GetComponentsInChildren(); + if (identities.Length > 1) + { + Debug.LogWarning("The prefab '" + prefab.name + + "' has multiple NetworkIdentity components. There can only be one NetworkIdentity on a prefab, and it must be on the root object."); + } + } + else + { + Debug.LogError("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component"); + } + } + + /// + /// Registers a prefab with the spawning system. + /// When a NetworkIdentity object is spawned on a server with NetworkServer.SpawnObject(), and the prefab that the object was created from was registered with RegisterPrefab(), the client will use that prefab to instantiate a corresponding client object with the same netId. + /// The NetworkManager has a list of spawnable prefabs, it uses this function to register those prefabs with the ClientScene. + /// The set of current spawnable object is available in the ClientScene static member variable ClientScene.prefabs, which is a dictionary of NetworkAssetIds and prefab references. + /// + /// A Prefab that will be spawned. + /// A method to use as a custom spawnhandler on clients. + /// A method to use as a custom un-spawnhandler on clients. + public static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + NetworkIdentity identity = prefab.GetComponent(); + if (identity == null) + { + Debug.LogError("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component"); + return; + } + + if (spawnHandler == null || unspawnHandler == null) + { + Debug.LogError("RegisterPrefab custom spawn function null for " + identity.assetId); + return; + } + + if (identity.assetId == Guid.Empty) + { + Debug.LogError("RegisterPrefab game object " + prefab.name + " has no prefab. Use RegisterSpawnHandler() instead?"); + return; + } + + if (LogFilter.Debug) Debug.Log("Registering custom prefab '" + prefab.name + "' as asset:" + identity.assetId + " " + spawnHandler.GetMethodName() + "/" + unspawnHandler.GetMethodName()); + + spawnHandlers[identity.assetId] = spawnHandler; + unspawnHandlers[identity.assetId] = unspawnHandler; + } + + /// + /// Removes a registered spawn prefab that was setup with ClientScene.RegisterPrefab. + /// + /// The prefab to be removed from registration. + public static void UnregisterPrefab(GameObject prefab) + { + NetworkIdentity identity = prefab.GetComponent(); + if (identity == null) + { + Debug.LogError("Could not unregister '" + prefab.name + "' since it contains no NetworkIdentity component"); + return; + } + spawnHandlers.Remove(identity.assetId); + unspawnHandlers.Remove(identity.assetId); + } + + /// + /// This is an advanced spawning function that registers a custom assetId with the UNET 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. + /// + /// Custom assetId string. + /// A method to use as a custom spawnhandler on clients. + /// A method to use as a custom un-spawnhandler on clients. + public static void RegisterSpawnHandler(Guid assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (spawnHandler == null || unspawnHandler == null) + { + Debug.LogError("RegisterSpawnHandler custom spawn function null for " + assetId); + return; + } + + if (LogFilter.Debug) 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 ClientScene.RegisterHandler(). + /// + /// The assetId for the handler to be removed for. + public static void UnregisterSpawnHandler(Guid 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(); + } + + static bool InvokeUnSpawnHandler(Guid assetId, GameObject obj) + { + if (unspawnHandlers.TryGetValue(assetId, out UnSpawnDelegate handler) && handler != null) + { + handler(obj); + return true; + } + return false; + } + + /// + /// Destroys all networked objects on the client. + /// This can be used to clean up when a network connection is closed. + /// + public static void DestroyAllClientObjects() + { + foreach (NetworkIdentity identity in NetworkIdentity.spawned.Values) + { + if (identity != null && identity.gameObject != null) + { + if (!InvokeUnSpawnHandler(identity.assetId, identity.gameObject)) + { + if (identity.sceneId == 0) + { + Object.Destroy(identity.gameObject); + } + else + { + identity.MarkForReset(); + identity.gameObject.SetActive(false); + } + } + } + } + NetworkIdentity.spawned.Clear(); + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkIdentity.spawned[netId] instead.")] + public static GameObject FindLocalObject(uint netId) + { + if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity)) + { + return identity.gameObject; + } + return null; + } + + static void ApplySpawnPayload(NetworkIdentity identity, Vector3 position, Quaternion rotation, Vector3 scale, ArraySegment payload, uint netId) + { + if (!identity.gameObject.activeSelf) + { + identity.gameObject.SetActive(true); + } + + // apply local values for VR support + identity.transform.localPosition = position; + identity.transform.localRotation = rotation; + identity.transform.localScale = scale; + + // deserialize components if any payload + // (Count is 0 if there were no components) + if (payload.Count > 0) + { + NetworkReader payloadReader = new NetworkReader(payload); + identity.OnUpdateVars(payloadReader, true); + } + + identity.netId = netId; + NetworkIdentity.spawned[netId] = identity; + + // objects spawned as part of initial state are started on a second pass + if (isSpawnFinished) + { + identity.OnStartClient(); + CheckForOwner(identity); + } + } + + internal static void OnSpawnPrefab(NetworkConnection _, SpawnPrefabMessage msg) + { + if (msg.assetId == Guid.Empty) + { + Debug.LogError("OnObjSpawn netId: " + msg.netId + " has invalid asset Id"); + return; + } + if (LogFilter.Debug) Debug.Log("Client spawn handler instantiating [netId:" + msg.netId + " asset ID:" + msg.assetId + " pos:" + msg.position + "]"); + + // owner? + if (msg.owner) + { + OnSpawnMessageForOwner(msg.netId); + } + + if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null) + { + // this object already exists (was in the scene), just apply the update to existing object + localObject.Reset(); + ApplySpawnPayload(localObject, msg.position, msg.rotation, msg.scale, msg.payload, msg.netId); + return; + } + + if (GetPrefab(msg.assetId, out GameObject prefab)) + { + GameObject obj = Object.Instantiate(prefab, msg.position, msg.rotation); + if (LogFilter.Debug) + { + Debug.Log("Client spawn handler instantiating [netId:" + msg.netId + " asset ID:" + msg.assetId + " pos:" + msg.position + " rotation: " + msg.rotation + "]"); + } + + localObject = obj.GetComponent(); + if (localObject == null) + { + Debug.LogError("Client object spawned for " + msg.assetId + " does not have a NetworkIdentity"); + return; + } + localObject.Reset(); + localObject.pendingOwner = msg.owner; + ApplySpawnPayload(localObject, msg.position, msg.rotation, msg.scale, msg.payload, msg.netId); + } + // lookup registered factory for type: + else if (spawnHandlers.TryGetValue(msg.assetId, out SpawnDelegate handler)) + { + GameObject obj = handler(msg.position, msg.assetId); + if (obj == null) + { + Debug.LogWarning("Client spawn handler for " + msg.assetId + " returned null"); + return; + } + localObject = obj.GetComponent(); + if (localObject == null) + { + Debug.LogError("Client object spawned for " + msg.assetId + " does not have a network identity"); + return; + } + localObject.Reset(); + localObject.pendingOwner = msg.owner; + localObject.assetId = msg.assetId; + ApplySpawnPayload(localObject, msg.position, msg.rotation, msg.scale, msg.payload, msg.netId); + } + else + { + Debug.LogError("Failed to spawn server object, did you forget to add it to the NetworkManager? assetId=" + msg.assetId + " netId=" + msg.netId); + } + } + + internal static void OnSpawnSceneObject(NetworkConnection _, SpawnSceneObjectMessage msg) + { + if (LogFilter.Debug) Debug.Log("Client spawn scene handler instantiating [netId:" + msg.netId + " sceneId:" + msg.sceneId + " pos:" + msg.position); + + // owner? + if (msg.owner) + { + OnSpawnMessageForOwner(msg.netId); + } + + if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null) + { + // this object already exists (was in the scene) + localObject.Reset(); + ApplySpawnPayload(localObject, msg.position, msg.rotation, msg.scale, msg.payload, msg.netId); + return; + } + + NetworkIdentity spawnedId = SpawnSceneObject(msg.sceneId); + if (spawnedId == null) + { + Debug.LogError("Spawn scene object not found for " + msg.sceneId.ToString("X") + " SpawnableObjects.Count=" + spawnableObjects.Count); + + // dump the whole spawnable objects dict for easier debugging + if (LogFilter.Debug) + { + foreach (KeyValuePair kvp in spawnableObjects) + Debug.Log("Spawnable: SceneId=" + kvp.Key + " name=" + kvp.Value.name); + } + + return; + } + + if (LogFilter.Debug) Debug.Log("Client spawn for [netId:" + msg.netId + "] [sceneId:" + msg.sceneId + "] obj:" + spawnedId.gameObject.name); + spawnedId.Reset(); + spawnedId.pendingOwner = msg.owner; + ApplySpawnPayload(spawnedId, msg.position, msg.rotation, msg.scale, msg.payload, msg.netId); + } + + internal static void OnObjectSpawnStarted(NetworkConnection _, ObjectSpawnStartedMessage msg) + { + if (LogFilter.Debug) Debug.Log("SpawnStarted"); + + PrepareToSpawnSceneObjects(); + isSpawnFinished = false; + } + + internal static void OnObjectSpawnFinished(NetworkConnection _, ObjectSpawnFinishedMessage msg) + { + if (LogFilter.Debug) Debug.Log("SpawnFinished"); + + // 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 NetworkIdentity.spawned.Values.OrderBy(uv => uv.netId)) + { + if (!identity.isClient) + { + identity.OnStartClient(); + CheckForOwner(identity); + } + } + isSpawnFinished = true; + } + + internal static void OnObjectHide(NetworkConnection _, ObjectHideMessage msg) + { + DestroyObject(msg.netId); + } + + internal static void OnObjectDestroy(NetworkConnection _, ObjectDestroyMessage msg) + { + DestroyObject(msg.netId); + } + + static void DestroyObject(uint netId) + { + if (LogFilter.Debug) Debug.Log("ClientScene.OnObjDestroy netId:" + netId); + + if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity localObject) && localObject != null) + { + localObject.OnNetworkDestroy(); + + if (!InvokeUnSpawnHandler(localObject.assetId, localObject.gameObject)) + { + // default handling + if (localObject.sceneId == 0) + { + Object.Destroy(localObject.gameObject); + } + else + { + // scene object.. disable it in scene instead of destroying + localObject.gameObject.SetActive(false); + spawnableObjects[localObject.sceneId] = localObject; + } + } + NetworkIdentity.spawned.Remove(netId); + localObject.MarkForReset(); + } + else + { + if (LogFilter.Debug) Debug.LogWarning("Did not find target for destroy message for " + netId); + } + } + + internal static void OnLocalClientObjectDestroy(NetworkConnection _, ObjectDestroyMessage msg) + { + if (LogFilter.Debug) Debug.Log("ClientScene.OnLocalObjectObjDestroy netId:" + msg.netId); + + NetworkIdentity.spawned.Remove(msg.netId); + } + + internal static void OnLocalClientObjectHide(NetworkConnection _, ObjectHideMessage msg) + { + if (LogFilter.Debug) Debug.Log("ClientScene::OnLocalObjectObjHide netId:" + msg.netId); + + if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null) + { + localObject.OnSetLocalVisibility(false); + } + } + + internal static void OnLocalClientSpawnPrefab(NetworkConnection _, SpawnPrefabMessage msg) + { + if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null) + { + localObject.OnSetLocalVisibility(true); + } + } + + internal static void OnLocalClientSpawnSceneObject(NetworkConnection _, SpawnSceneObjectMessage msg) + { + if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null) + { + localObject.OnSetLocalVisibility(true); + } + } + + internal static void OnUpdateVarsMessage(NetworkConnection _, UpdateVarsMessage msg) + { + if (LogFilter.Debug) Debug.Log("ClientScene.OnUpdateVarsMessage " + msg.netId); + + if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null) + { + localObject.OnUpdateVars(new NetworkReader(msg.payload), false); + } + else + { + Debug.LogWarning("Did not find target for sync message for " + msg.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."); + } + } + + internal static void OnRPCMessage(NetworkConnection _, RpcMessage msg) + { + if (LogFilter.Debug) Debug.Log("ClientScene.OnRPCMessage hash:" + msg.functionHash + " netId:" + msg.netId); + + if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity identity)) + { + identity.HandleRPC(msg.componentIndex, msg.functionHash, new NetworkReader(msg.payload)); + } + } + + internal static void OnSyncEventMessage(NetworkConnection _, SyncEventMessage msg) + { + if (LogFilter.Debug) Debug.Log("ClientScene.OnSyncEventMessage " + msg.netId); + + if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity identity)) + { + identity.HandleSyncEvent(msg.componentIndex, msg.functionHash, new NetworkReader(msg.payload)); + } + else + { + Debug.LogWarning("Did not find target for SyncEvent message for " + msg.netId); + } + } + + internal static void OnClientAuthority(NetworkConnection _, ClientAuthorityMessage msg) + { + if (LogFilter.Debug) Debug.Log("ClientScene.OnClientAuthority for netId: " + msg.netId); + + if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity identity)) + { + identity.HandleClientAuthority(msg.authority); + } + } + + // called for the one object in the spawn message which is the owner! + internal static void OnSpawnMessageForOwner(uint netId) + { + if (LogFilter.Debug) Debug.Log("ClientScene.OnOwnerMessage - connectionId=" + readyConnection.connectionId + " netId: " + netId); + + // is there already an owner that is a different object?? + if (readyConnection.playerController != null) + { + readyConnection.playerController.SetNotLocalPlayer(); + } + + if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity localObject) && localObject != null) + { + // this object already exists + localObject.connectionToServer = readyConnection; + localObject.SetLocalPlayer(); + InternalAddPlayer(localObject); + } + } + + static void CheckForOwner(NetworkIdentity identity) + { + if (identity.pendingOwner) + { + // found owner, turn into a local player + + // Set isLocalPlayer to true on this NetworkIdentity and trigger OnStartLocalPlayer in all scripts on the same GO + identity.connectionToServer = readyConnection; + identity.SetLocalPlayer(); + + if (LogFilter.Debug) Debug.Log("ClientScene.OnOwnerMessage - player=" + identity.name); + if (readyConnection.connectionId < 0) + { + Debug.LogError("Owner message received on a local client."); + return; + } + InternalAddPlayer(identity); + + identity.pendingOwner = false; + } + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/ClientScene.cs.meta b/Assets/Packages/Mirror/Runtime/ClientScene.cs.meta new file mode 100644 index 0000000..c4f3a09 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/ClientScene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96fc7967f813e4960b9119d7c2118494 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/CustomAttributes.cs b/Assets/Packages/Mirror/Runtime/CustomAttributes.cs new file mode 100644 index 0000000..40bdd7d --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/CustomAttributes.cs @@ -0,0 +1,58 @@ +using System; +using System.ComponentModel; +using UnityEngine; + +namespace Mirror +{ + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkBehaviour.syncInterval field instead. Can be modified in the Inspector too.")] + [AttributeUsage(AttributeTargets.Class)] + public class NetworkSettingsAttribute : Attribute + { + public float sendInterval = 0.1f; + } + + [AttributeUsage(AttributeTargets.Field)] + public class SyncVarAttribute : Attribute + { + public string hook; + } + + [AttributeUsage(AttributeTargets.Method)] + public class CommandAttribute : Attribute + { + public int channel = Channels.DefaultReliable; // this is zero + } + + [AttributeUsage(AttributeTargets.Method)] + public class ClientRpcAttribute : Attribute + { + public int channel = Channels.DefaultReliable; // this is zero + } + + [AttributeUsage(AttributeTargets.Method)] + public class TargetRpcAttribute : Attribute + { + public int channel = Channels.DefaultReliable; // this is zero + } + + [AttributeUsage(AttributeTargets.Event)] + public class SyncEventAttribute : Attribute + { + public int channel = Channels.DefaultReliable; // this is zero + } + + [AttributeUsage(AttributeTargets.Method)] + public class ServerAttribute : Attribute {} + + [AttributeUsage(AttributeTargets.Method)] + public class ServerCallbackAttribute : Attribute {} + + [AttributeUsage(AttributeTargets.Method)] + public class ClientAttribute : Attribute {} + + [AttributeUsage(AttributeTargets.Method)] + public class ClientCallbackAttribute : Attribute {} + + // For Scene property Drawer + public class SceneAttribute : PropertyAttribute {} +} diff --git a/Assets/Packages/Mirror/Runtime/CustomAttributes.cs.meta b/Assets/Packages/Mirror/Runtime/CustomAttributes.cs.meta new file mode 100644 index 0000000..22a1db2 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/CustomAttributes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c04c722ee2ffd49c8a56ab33667b10b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/DotNetCompatibility.cs b/Assets/Packages/Mirror/Runtime/DotNetCompatibility.cs new file mode 100644 index 0000000..fe57e17 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/DotNetCompatibility.cs @@ -0,0 +1,16 @@ +using System; + +namespace Mirror +{ + internal static class DotNetCompatibility + { + internal static string GetMethodName(this Delegate func) + { +#if NETFX_CORE + return func.GetMethodInfo().Name; +#else + return func.Method.Name; +#endif + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/DotNetCompatibility.cs.meta b/Assets/Packages/Mirror/Runtime/DotNetCompatibility.cs.meta new file mode 100644 index 0000000..8742197 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/DotNetCompatibility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b307f850ccbbe450295acf24d70e5c28 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/ExponentialMovingAverage.cs b/Assets/Packages/Mirror/Runtime/ExponentialMovingAverage.cs new file mode 100644 index 0000000..f6ec793 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/ExponentialMovingAverage.cs @@ -0,0 +1,38 @@ +namespace Mirror +{ + // implementation of N-day EMA + // it calculates an exponential moving average roughy equivalent to the last n observations + // https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average + public class ExponentialMovingAverage + { + readonly float alpha; + bool initialized; + + public ExponentialMovingAverage(int n) + { + // standard N-day EMA alpha calculation + alpha = 2.0f / (n + 1); + } + + 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; + Var = (1 - alpha) * (Var + alpha * delta * delta); + } + else + { + Value = newValue; + initialized = true; + } + } + + public double Value { get; private set; } + + public double Var { get; private set; } + } +} diff --git a/Assets/Packages/Mirror/Runtime/ExponentialMovingAverage.cs.meta b/Assets/Packages/Mirror/Runtime/ExponentialMovingAverage.cs.meta new file mode 100644 index 0000000..5ce3055 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/ExponentialMovingAverage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 05e858cbaa54b4ce4a48c8c7f50c1914 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/FloatBytePacker.cs b/Assets/Packages/Mirror/Runtime/FloatBytePacker.cs new file mode 100644 index 0000000..2293d21 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/FloatBytePacker.cs @@ -0,0 +1,60 @@ +using UnityEngine; + +namespace Mirror +{ + public static class FloatBytePacker + { + // ScaleFloatToByte( -1f, -1f, 1f, byte.MinValue, byte.MaxValue) => 0 + // ScaleFloatToByte( 0f, -1f, 1f, byte.MinValue, byte.MaxValue) => 127 + // ScaleFloatToByte(0.5f, -1f, 1f, byte.MinValue, byte.MaxValue) => 191 + // ScaleFloatToByte( 1f, -1f, 1f, byte.MinValue, byte.MaxValue) => 255 + public static byte ScaleFloatToByte(float value, float minValue, float maxValue, byte minTarget, byte maxTarget) + { + // note: C# byte - byte => int, hence so many casts + int targetRange = maxTarget - minTarget; // max byte - min byte only fits into something bigger + float valueRange = maxValue - minValue; + float valueRelative = value - minValue; + return (byte)(minTarget + (byte)(valueRelative/valueRange * targetRange)); + } + + // ScaleByteToFloat( 0, byte.MinValue, byte.MaxValue, -1, 1) => -1 + // ScaleByteToFloat(127, byte.MinValue, byte.MaxValue, -1, 1) => -0.003921569 + // ScaleByteToFloat(191, byte.MinValue, byte.MaxValue, -1, 1) => 0.4980392 + // ScaleByteToFloat(255, byte.MinValue, byte.MaxValue, -1, 1) => 1 + public static float ScaleByteToFloat(byte value, byte minValue, byte maxValue, float minTarget, float maxTarget) + { + // note: C# byte - byte => int, hence so many casts + float targetRange = maxTarget - minTarget; + byte valueRange = (byte)(maxValue - minValue); + byte valueRelative = (byte)(value - minValue); + return minTarget + (valueRelative / (float)valueRange * targetRange); + } + + // eulerAngles have 3 floats, putting them into 2 bytes of [x,y],[z,0] + // would be a waste. instead we compress into 5 bits each => 15 bits. + // so a ushort. + public static ushort PackThreeFloatsIntoUShort(float u, float v, float w, float minValue, float maxValue) + { + // 5 bits max value = 1+2+4+8+16 = 31 = 0x1F + byte lower = ScaleFloatToByte(u, minValue, maxValue, 0x00, 0x1F); + byte middle = ScaleFloatToByte(v, minValue, maxValue, 0x00, 0x1F); + byte upper = ScaleFloatToByte(w, minValue, maxValue, 0x00, 0x1F); + ushort combined = (ushort)(upper << 10 | middle << 5 | lower); + return combined; + } + + // see PackThreeFloatsIntoUShort for explanation + public static Vector3 UnpackUShortIntoThreeFloats(ushort combined, float minTarget, float maxTarget) + { + byte lower = (byte)(combined & 0x1F); + byte middle = (byte)((combined >> 5) & 0x1F); + byte upper = (byte)(combined >> 10); // nothing on the left, no & needed + + // note: we have to use 4 bits per float, so between 0x00 and 0x0F + float u = ScaleByteToFloat(lower, 0x00, 0x1F, minTarget, maxTarget); + float v = ScaleByteToFloat(middle, 0x00, 0x1F, minTarget, maxTarget); + float w = ScaleByteToFloat(upper, 0x00, 0x1F, minTarget, maxTarget); + return new Vector3(u, v, w); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/FloatBytePacker.cs.meta b/Assets/Packages/Mirror/Runtime/FloatBytePacker.cs.meta new file mode 100644 index 0000000..92145fe --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/FloatBytePacker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: afd3cca6a786d4208b1d0f7f2b168901 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/LocalClient.cs b/Assets/Packages/Mirror/Runtime/LocalClient.cs new file mode 100644 index 0000000..20db50b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/LocalClient.cs @@ -0,0 +1,5 @@ +// 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/Packages/Mirror/Runtime/LocalClient.cs.meta b/Assets/Packages/Mirror/Runtime/LocalClient.cs.meta new file mode 100644 index 0000000..6c073e6 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/LocalClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c4d04450e91c438385de7300abef1b6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/LocalConnections.cs b/Assets/Packages/Mirror/Runtime/LocalConnections.cs new file mode 100644 index 0000000..33962d4 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/LocalConnections.cs @@ -0,0 +1,47 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + // a server's connection TO a LocalClient. + // sending messages on this connection causes the client's handler function to be invoked directly + class ULocalConnectionToClient : NetworkConnection + { + public ULocalConnectionToClient() : base ("localClient") + { + // local player always has connectionId == 0 + connectionId = 0; + } + + internal override bool SendBytes(byte[] bytes, int channelId = Channels.DefaultReliable) + { + NetworkClient.localClientPacketQueue.Enqueue(bytes); + return true; + } + } + + // a localClient's connection TO a server. + // send messages on this connection causes the server's handler function to be invoked directly. + internal class ULocalConnectionToServer : NetworkConnection + { + public ULocalConnectionToServer() : base("localServer") + { + // local player always has connectionId == 0 + connectionId = 0; + } + + internal override bool SendBytes(byte[] bytes, int channelId = Channels.DefaultReliable) + { + if (bytes.Length == 0) + { + Debug.LogError("LocalConnection.SendBytes cannot send zero bytes"); + return false; + } + + // handle the server's message directly + // TODO any way to do this without NetworkServer.localConnection? + NetworkServer.localConnection.TransportReceive(new ArraySegment(bytes)); + return true; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/LocalConnections.cs.meta b/Assets/Packages/Mirror/Runtime/LocalConnections.cs.meta new file mode 100644 index 0000000..2a332c4 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/LocalConnections.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a88758df7db2043d6a9d926e0b6d4191 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/LogFilter.cs b/Assets/Packages/Mirror/Runtime/LogFilter.cs new file mode 100644 index 0000000..3b225f7 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/LogFilter.cs @@ -0,0 +1,7 @@ +namespace Mirror +{ + public static class LogFilter + { + public static bool Debug = false; + } +} diff --git a/Assets/Packages/Mirror/Runtime/LogFilter.cs.meta b/Assets/Packages/Mirror/Runtime/LogFilter.cs.meta new file mode 100644 index 0000000..41cab50 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/LogFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f6928b080072948f7b2909b4025fcc79 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/MessagePacker.cs b/Assets/Packages/Mirror/Runtime/MessagePacker.cs new file mode 100644 index 0000000..e134465 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/MessagePacker.cs @@ -0,0 +1,136 @@ +using System; +using System.ComponentModel; +using UnityEngine; + +namespace Mirror +{ + // message packing all in one place, instead of constructing headers in all + // kinds of different places + // + // MsgType (1-n bytes) + // Content (ContentSize bytes) + // + // -> we use varint for headers because most messages will result in 1 byte + // type/size headers then instead of always + // using 2 bytes for shorts. + // -> this reduces bandwidth by 10% if average message size is 20 bytes + // (probably even shorter) + public static class MessagePacker + { + public static int GetId() where T : IMessageBase + { + // paul: 16 bits is enough to avoid collisions + // - keeps the message size small because it gets varinted + // - in case of collisions, Mirror will display an error + return typeof(T).FullName.GetStableHashCode() & 0xFFFF; + } + + // pack message before sending + // -> pass writer instead of byte[] so we can reuse it + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use Pack instead")] + public static byte[] PackMessage(int msgType, MessageBase msg) + { + NetworkWriter writer = NetworkWriterPool.GetWriter(); + try + { + // write message type + writer.WriteInt16((short)msgType); + + // serialize message into writer + msg.Serialize(writer); + + // return byte[] + return writer.ToArray(); + } + finally + { + NetworkWriterPool.Recycle(writer); + } + } + + // pack message before sending + public static byte[] Pack(T message) where T : IMessageBase + { + NetworkWriter writer = NetworkWriterPool.GetWriter(); + try + { + // write message type + int msgType = GetId(); + writer.WriteUInt16((ushort)msgType); + + // serialize message into writer + message.Serialize(writer); + + // return byte[] + return writer.ToArray(); + } + finally + { + NetworkWriterPool.Recycle(writer); + } + } + + // unpack a message we received + public static T Unpack(byte[] data) where T : IMessageBase, new() + { + NetworkReader reader = new NetworkReader(data); + + int msgType = GetId(); + + int id = reader.ReadUInt16(); + if (id != msgType) + throw new FormatException("Invalid message, could not unpack " + typeof(T).FullName); + + T message = new T(); + message.Deserialize(reader); + return message; + } + + // unpack message after receiving + // -> pass NetworkReader so it's less strange if we create it in here + // and pass it upwards. + // -> NetworkReader will point at content afterwards! + public static bool UnpackMessage(NetworkReader messageReader, out int msgType) + { + // read message type (varint) + try + { + msgType = messageReader.ReadUInt16(); + return true; + } + catch (System.IO.EndOfStreamException) + { + msgType = 0; + return false; + } + } + + internal static NetworkMessageDelegate MessageHandler(Action handler) where T : IMessageBase, new() => networkMessage => + { + // 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; + try + { + message = networkMessage.ReadMessage(); + } + catch (Exception exception) + { + Debug.LogError("Closed connection: " + networkMessage.conn.connectionId + ". This can happen if the other side accidentally (or an attacker intentionally) sent invalid data. Reason: " + exception); + networkMessage.conn.Disconnect(); + return; + } + handler(networkMessage.conn, message); + }; + } +} diff --git a/Assets/Packages/Mirror/Runtime/MessagePacker.cs.meta b/Assets/Packages/Mirror/Runtime/MessagePacker.cs.meta new file mode 100644 index 0000000..7ca61aa --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/MessagePacker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2db134099f0df4d96a84ae7a0cd9b4bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Messages.cs b/Assets/Packages/Mirror/Runtime/Messages.cs new file mode 100644 index 0000000..99c31ad --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Messages.cs @@ -0,0 +1,492 @@ +using System; +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace Mirror +{ + public interface IMessageBase + { + void Deserialize(NetworkReader reader); + + void Serialize(NetworkWriter writer); + } + + public abstract class MessageBase : IMessageBase + { + // De-serialize the contents of the reader into this message + public virtual void Deserialize(NetworkReader reader) {} + + // Serialize the contents of this message into the writer + public virtual void Serialize(NetworkWriter writer) {} + } + + #region General Typed Messages + public class StringMessage : MessageBase + { + public string value; + + public StringMessage() {} + + public StringMessage(string v) + { + value = v; + } + + public override void Deserialize(NetworkReader reader) + { + value = reader.ReadString(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.WriteString(value); + } + } + + public class ByteMessage : MessageBase + { + public byte value; + + public ByteMessage() {} + + public ByteMessage(byte v) + { + value = v; + } + + public override void Deserialize(NetworkReader reader) + { + value = reader.ReadByte(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.WriteByte(value); + } + } + + public class BytesMessage : MessageBase + { + public byte[] value; + + public BytesMessage() {} + + public BytesMessage(byte[] v) + { + value = v; + } + + public override void Deserialize(NetworkReader reader) + { + value = reader.ReadBytesAndSize(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.WriteBytesAndSize(value); + } + } + + public class IntegerMessage : MessageBase + { + public int value; + + public IntegerMessage() {} + + public IntegerMessage(int v) + { + value = v; + } + + public override void Deserialize(NetworkReader reader) + { + value = reader.ReadPackedInt32(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.WritePackedInt32(value); + } + } + + public class DoubleMessage : MessageBase + { + public double value; + + public DoubleMessage() {} + + public DoubleMessage(double v) + { + value = v; + } + + public override void Deserialize(NetworkReader reader) + { + value = reader.ReadDouble(); + } + + public override void Serialize(NetworkWriter writer) + { + writer.WriteDouble(value); + } + } + + public class EmptyMessage : MessageBase + { + public override void Deserialize(NetworkReader reader) {} + + public override void Serialize(NetworkWriter writer) {} + } + #endregion + + #region Public System Messages + public class ErrorMessage : ByteMessage {} + + public struct ReadyMessage : IMessageBase + { + public void Deserialize(NetworkReader reader) { } + + public void Serialize(NetworkWriter writer) { } + } + + public struct NotReadyMessage : IMessageBase + { + public void Deserialize(NetworkReader reader) { } + + public void Serialize(NetworkWriter writer) { } + } + + public struct AddPlayerMessage : IMessageBase + { + public byte[] value; + + public void Deserialize(NetworkReader reader) + { + value = reader.ReadBytesAndSize(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WriteBytesAndSize(value); + } + } + + public struct RemovePlayerMessage : IMessageBase + { + public void Deserialize(NetworkReader reader) { } + + public void Serialize(NetworkWriter writer) { } + } + + public struct DisconnectMessage : IMessageBase + { + public void Deserialize(NetworkReader reader) { } + + public void Serialize(NetworkWriter writer) { } + } + + public struct ConnectMessage : IMessageBase + { + public void Deserialize(NetworkReader reader) { } + + public void Serialize(NetworkWriter writer) { } + } + + public struct SceneMessage : IMessageBase + { + public string sceneName; + public LoadSceneMode sceneMode; // Single = 0, Additive = 1 + public LocalPhysicsMode physicsMode; // None = 0, Physics3D = 1, Physics2D = 2 + + public void Deserialize(NetworkReader reader) + { + sceneName = reader.ReadString(); + sceneMode = (LoadSceneMode)reader.ReadByte(); + physicsMode = (LocalPhysicsMode)reader.ReadByte(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WriteString(sceneName); + writer.WriteByte((byte)sceneMode); + writer.WriteByte((byte)physicsMode); + } + } + #endregion + + #region System Messages requried for code gen path + struct CommandMessage : IMessageBase + { + public uint netId; + public int componentIndex; + public int functionHash; + // the parameters for the Cmd function + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + + public void Deserialize(NetworkReader reader) + { + netId = reader.ReadPackedUInt32(); + componentIndex = (int)reader.ReadPackedUInt32(); + functionHash = reader.ReadInt32(); // hash is always 4 full bytes, WritePackedInt would send 1 extra byte here + payload = reader.ReadBytesAndSizeSegment(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(netId); + writer.WritePackedUInt32((uint)componentIndex); + writer.WriteInt32(functionHash); + writer.WriteBytesAndSizeSegment(payload); + } + } + + struct RpcMessage : IMessageBase + { + public uint netId; + public int componentIndex; + public int functionHash; + // the parameters for the Cmd function + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + + public void Deserialize(NetworkReader reader) + { + netId = reader.ReadPackedUInt32(); + componentIndex = (int)reader.ReadPackedUInt32(); + functionHash = reader.ReadInt32(); // hash is always 4 full bytes, WritePackedInt would send 1 extra byte here + payload = reader.ReadBytesAndSizeSegment(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(netId); + writer.WritePackedUInt32((uint)componentIndex); + writer.WriteInt32(functionHash); + writer.WriteBytesAndSizeSegment(payload); + } + } + + struct SyncEventMessage : IMessageBase + { + public uint netId; + public int componentIndex; + public int functionHash; + // the parameters for the Cmd function + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + + public void Deserialize(NetworkReader reader) + { + netId = reader.ReadPackedUInt32(); + componentIndex = (int)reader.ReadPackedUInt32(); + functionHash = reader.ReadInt32(); // hash is always 4 full bytes, WritePackedInt would send 1 extra byte here + payload = reader.ReadBytesAndSizeSegment(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(netId); + writer.WritePackedUInt32((uint)componentIndex); + writer.WriteInt32(functionHash); + writer.WriteBytesAndSizeSegment(payload); + } + } + #endregion + + #region Internal System Messages + struct SpawnPrefabMessage : IMessageBase + { + public uint netId; + public bool owner; + public Guid assetId; + public Vector3 position; + public Quaternion rotation; + public Vector3 scale; + // the serialized component data + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + + public void Deserialize(NetworkReader reader) + { + netId = reader.ReadPackedUInt32(); + owner = reader.ReadBoolean(); + assetId = reader.ReadGuid(); + position = reader.ReadVector3(); + rotation = reader.ReadQuaternion(); + scale = reader.ReadVector3(); + payload = reader.ReadBytesAndSizeSegment(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(netId); + writer.WriteBoolean(owner); + writer.WriteGuid(assetId); + writer.WriteVector3(position); + writer.WriteQuaternion(rotation); + writer.WriteVector3(scale); + writer.WriteBytesAndSizeSegment(payload); + } + } + + struct SpawnSceneObjectMessage : IMessageBase + { + public uint netId; + public bool owner; + public ulong sceneId; + public Vector3 position; + public Quaternion rotation; + public Vector3 scale; + // the serialized component data + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + + public void Deserialize(NetworkReader reader) + { + netId = reader.ReadPackedUInt32(); + owner = reader.ReadBoolean(); + sceneId = reader.ReadUInt64(); + position = reader.ReadVector3(); + rotation = reader.ReadQuaternion(); + scale = reader.ReadVector3(); + payload = reader.ReadBytesAndSizeSegment(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(netId); + writer.WriteBoolean(owner); + writer.WriteUInt64(sceneId); + writer.WriteVector3(position); + writer.WriteQuaternion(rotation); + writer.WriteVector3(scale); + writer.WriteBytesAndSizeSegment(payload); + } + } + + struct ObjectSpawnStartedMessage : IMessageBase + { + public void Deserialize(NetworkReader reader) { } + + public void Serialize(NetworkWriter writer) { } + } + + struct ObjectSpawnFinishedMessage : IMessageBase + { + public void Deserialize(NetworkReader reader) { } + + public void Serialize(NetworkWriter writer) { } + } + + struct ObjectDestroyMessage : IMessageBase + { + public uint netId; + + public void Deserialize(NetworkReader reader) + { + netId = reader.ReadPackedUInt32(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(netId); + } + } + + struct ObjectHideMessage : IMessageBase + { + public uint netId; + + public void Deserialize(NetworkReader reader) + { + netId = reader.ReadPackedUInt32(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(netId); + } + } + + struct ClientAuthorityMessage : IMessageBase + { + public uint netId; + public bool authority; + + public void Deserialize(NetworkReader reader) + { + netId = reader.ReadPackedUInt32(); + authority = reader.ReadBoolean(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(netId); + writer.WriteBoolean(authority); + } + } + + struct UpdateVarsMessage : IMessageBase + { + public uint netId; + // the serialized component data + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + + public void Deserialize(NetworkReader reader) + { + netId = reader.ReadPackedUInt32(); + payload = reader.ReadBytesAndSizeSegment(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WritePackedUInt32(netId); + writer.WriteBytesAndSizeSegment(payload); + } + } + + // A client sends this message to the server + // to calculate RTT and synchronize time + struct NetworkPingMessage : IMessageBase + { + public double clientTime; + + public NetworkPingMessage(double value) + { + clientTime = value; + } + + public void Deserialize(NetworkReader reader) + { + clientTime = reader.ReadDouble(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WriteDouble(clientTime); + } + } + + // The server responds with this message + // The client can use this to calculate RTT and sync time + struct NetworkPongMessage : IMessageBase + { + public double clientTime; + public double serverTime; + + public void Deserialize(NetworkReader reader) + { + clientTime = reader.ReadDouble(); + serverTime = reader.ReadDouble(); + } + + public void Serialize(NetworkWriter writer) + { + writer.WriteDouble(clientTime); + writer.WriteDouble(serverTime); + } + } + #endregion +} diff --git a/Assets/Packages/Mirror/Runtime/Messages.cs.meta b/Assets/Packages/Mirror/Runtime/Messages.cs.meta new file mode 100644 index 0000000..9afe21b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Messages.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 938f6f28a6c5b48a0bbd7782342d763b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Mirror.asmdef b/Assets/Packages/Mirror/Runtime/Mirror.asmdef new file mode 100644 index 0000000..4f3dbbd --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Mirror.asmdef @@ -0,0 +1,8 @@ +{ + "name": "Mirror", + "references": [], + "optionalUnityReferences": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Mirror.asmdef.meta b/Assets/Packages/Mirror/Runtime/Mirror.asmdef.meta new file mode 100644 index 0000000..202009b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Mirror.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 30817c1a0e6d646d99c048fc403f5979 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkBehaviour.cs b/Assets/Packages/Mirror/Runtime/NetworkBehaviour.cs new file mode 100644 index 0000000..aee1e10 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkBehaviour.cs @@ -0,0 +1,775 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using UnityEngine; + +namespace Mirror +{ + /// + /// Sync to everyone, or only to owner. + /// + public enum SyncMode { Observers, Owner } + + /// + /// Base class which should be inherited by scripts which contain networking functionality. + /// + /// + /// This is a MonoBehaviour class so scripts which need to use the networking feature should inherit this class instead of MonoBehaviour. It allows you to invoke networked actions, receive various callbacks, and automatically synchronize state from server-to-client. + /// The NetworkBehaviour component requires a NetworkIdentity on the game object. There can be multiple NetworkBehaviours on a single game object. For an object with sub-components in a hierarchy, the NetworkIdentity must be on the root object, and NetworkBehaviour scripts must also be on the root object. + /// Some of the built-in components of the networking system are derived from NetworkBehaviour, including NetworkTransport, NetworkAnimator and NetworkProximityChecker. + /// + [RequireComponent(typeof(NetworkIdentity))] + [AddComponentMenu("")] + public class NetworkBehaviour : MonoBehaviour + { + float lastSyncTime; + + // hidden because NetworkBehaviourInspector shows it only if has OnSerialize. + /// + /// sync mode for OnSerialize + /// + [HideInInspector] public SyncMode syncMode = SyncMode.Observers; + + // hidden because NetworkBehaviourInspector shows it only if has OnSerialize. + /// + /// sync interval for OnSerialize (in seconds) + /// + [HideInInspector] public float syncInterval = 0.1f; + + /// + /// This value is set on the NetworkIdentity and is accessible here for convenient access for scripts. + /// + public bool localPlayerAuthority => netIdentity.localPlayerAuthority; + + /// + /// Returns true if this object is active on an active server. + /// This is only true if the object 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; + + /// + /// Returns true if running as a client and this object was spawned by a server. + /// + public bool isClient => netIdentity.isClient; + + /// + /// This returns true if this object is the one that represents the player on the local machine. + /// In multiplayer games, there are multiple instances of the Player object. The client needs to know which one is for "themselves" so that only that player processes input and potentially has a camera attached. The IsLocalPlayer function will return true only for the player instance that belongs to the player on the local machine, so it can be used to filter out input for non-local players. + /// + public bool isLocalPlayer => netIdentity.isLocalPlayer; + + /// + /// 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; + + /// + /// This returns true if this object is the authoritative version of the object in the distributed network application. + /// The localPlayerAuthority value on the NetworkIdentity determines how authority is determined. For most objects, authority is held by the server / host. For objects with localPlayerAuthority set, authority is held by the client of that player. + /// + public bool hasAuthority => netIdentity.hasAuthority; + + /// + /// The unique network Id of this object. + /// This is assigned at runtime by the network server and will be unique for all objects for that network session. + /// + public uint netId => netIdentity.netId; + + /// + /// The NetworkConnection associated with this NetworkIdentity. This is only valid for player objects on the server. + /// + public NetworkConnection connectionToServer => netIdentity.connectionToServer; + + /// + /// The NetworkConnection associated with this NetworkIdentity. This is only valid for player objects on the server. + /// + public NetworkConnection connectionToClient => netIdentity.connectionToClient; + + protected ulong syncVarDirtyBits { get; private set; } + private ulong syncVarHookGuard; + + protected bool getSyncVarHookGuard(ulong dirtyBit) + { + return (syncVarHookGuard & dirtyBit) != 0UL; + } + protected void setSyncVarHookGuard(ulong dirtyBit, bool value) + { + if (value) + syncVarHookGuard |= dirtyBit; + else + syncVarHookGuard &= ~dirtyBit; + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use syncObjects instead.")] + protected List m_SyncObjects => syncObjects; + + /// + /// objects that can synchronize themselves, such as synclists + /// + protected readonly List syncObjects = new List(); + + /// + /// NetworkIdentity component caching for easier access + /// + NetworkIdentity netIdentityCache; + + /// + /// Returns the NetworkIdentity of this object + /// + public NetworkIdentity netIdentity + { + get + { + if (netIdentityCache == null) + { + netIdentityCache = GetComponent(); + } + if (netIdentityCache == null) + { + Debug.LogError("There is no NetworkIdentity on " + name + ". Please add one."); + } + return netIdentityCache; + } + } + + /// + /// Returns the index of the component on this object + /// + public int ComponentIndex + { + get + { + // note: FindIndex causes allocations, we search manually instead + for (int i = 0; i < netIdentity.NetworkBehaviours.Length; i++) + { + NetworkBehaviour component = netIdentity.NetworkBehaviours[i]; + if (component == this) + return i; + } + + // this should never happen + Debug.LogError("Could not find component in GameObject. You should not add/remove components in networked objects dynamically", this); + + return -1; + } + } + + // 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) + { + syncObjects.Add(syncObject); + } + + #region Commands + + private static int GetMethodHash(Type invokeClass, string methodName) + { + // (invokeClass + ":" + cmdName).GetStableHashCode() would cause allocations. + // so hash1 + hash2 is better. + unchecked + { + int hash = invokeClass.FullName.GetStableHashCode(); + return hash * 503 + methodName.GetStableHashCode(); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SendCommandInternal(Type invokeClass, string cmdName, NetworkWriter writer, int channelId) + { + // 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 Function " + cmdName + " called on server without an active client."); + return; + } + // local players can always send commands, regardless of authority, other objects must have authority. + if (!(isLocalPlayer || hasAuthority)) + { + Debug.LogWarning("Trying to send command for object without authority."); + return; + } + + if (ClientScene.readyConnection == null) + { + Debug.LogError("Send command attempted with no client running [client=" + connectionToServer + "]."); + return; + } + + // construct the message + CommandMessage message = new CommandMessage + { + netId = netId, + componentIndex = ComponentIndex, + functionHash = GetMethodHash(invokeClass, cmdName), // type+func so Inventory.RpcUse != Equipment.RpcUse + payload = writer.ToArraySegment() // segment to avoid reader allocations + }; + + ClientScene.readyConnection.Send(message, channelId); + } + + /// + /// Manually invoke a Command. + /// + /// Hash of the Command name. + /// Parameters to pass to the command. + /// Returns true if successful. + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual bool InvokeCommand(int cmdHash, NetworkReader reader) + { + return InvokeHandlerDelegate(cmdHash, MirrorInvokeType.Command, reader); + } + #endregion + + #region Client RPCs + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SendRPCInternal(Type invokeClass, string rpcName, NetworkWriter writer, int channelId) + { + // this was in Weaver before + if (!NetworkServer.active) + { + Debug.LogError("RPC Function " + rpcName + " called on Client."); + return; + } + // This cannot use NetworkServer.active, as that is not specific to this object. + if (!isServer) + { + Debug.LogWarning("ClientRpc " + rpcName + " called on un-spawned object: " + name); + return; + } + + // construct the message + RpcMessage message = new RpcMessage + { + netId = netId, + componentIndex = ComponentIndex, + functionHash = GetMethodHash(invokeClass, rpcName), // type+func so Inventory.RpcUse != Equipment.RpcUse + payload = writer.ToArraySegment() // segment to avoid reader allocations + }; + + NetworkServer.SendToReady(netIdentity, message, channelId); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SendTargetRPCInternal(NetworkConnection conn, Type invokeClass, string rpcName, NetworkWriter writer, int channelId) + { + // this was in Weaver before + if (!NetworkServer.active) + { + Debug.LogError("TargetRPC Function " + rpcName + " called on client."); + return; + } + // connection parameter is optional. assign if null. + if (conn == null) + { + conn = connectionToClient; + } + // this was in Weaver before + if (conn is ULocalConnectionToServer) + { + Debug.LogError("TargetRPC Function " + rpcName + " called on connection to server"); + return; + } + // This cannot use NetworkServer.active, as that is not specific to this object. + if (!isServer) + { + Debug.LogWarning("TargetRpc " + rpcName + " called on un-spawned object: " + name); + return; + } + + // construct the message + RpcMessage message = new RpcMessage + { + netId = netId, + componentIndex = ComponentIndex, + functionHash = GetMethodHash(invokeClass, rpcName), // type+func so Inventory.RpcUse != Equipment.RpcUse + payload = writer.ToArraySegment() // segment to avoid reader allocations + }; + + conn.Send(message, channelId); + } + + /// + /// Manually invoke an RPC function. + /// + /// Hash of the RPC name. + /// Parameters to pass to the RPC function. + /// Returns true if successful. + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual bool InvokeRPC(int rpcHash, NetworkReader reader) + { + return InvokeHandlerDelegate(rpcHash, MirrorInvokeType.ClientRpc, reader); + } + #endregion + + #region Sync Events + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SendEventInternal(Type invokeClass, string eventName, NetworkWriter writer, int channelId) + { + if (!NetworkServer.active) + { + Debug.LogWarning("SendEvent no server?"); + return; + } + + // construct the message + SyncEventMessage message = new SyncEventMessage + { + netId = netId, + componentIndex = ComponentIndex, + functionHash = GetMethodHash(invokeClass, eventName), // type+func so Inventory.RpcUse != Equipment.RpcUse + payload = writer.ToArraySegment() // segment to avoid reader allocations + }; + + NetworkServer.SendToReady(netIdentity, message, channelId); + } + + /// + /// Manually invoke a SyncEvent. + /// + /// Hash of the SyncEvent name. + /// Parameters to pass to the SyncEvent. + /// Returns true if successful. + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual bool InvokeSyncEvent(int eventHash, NetworkReader reader) + { + return InvokeHandlerDelegate(eventHash, MirrorInvokeType.SyncEvent, reader); + } + #endregion + + #region Code Gen Path Helpers + /// + /// Delegate for Command functions. + /// + /// + /// + public delegate void CmdDelegate(NetworkBehaviour obj, NetworkReader reader); + + protected class Invoker + { + public MirrorInvokeType invokeType; + public Type invokeClass; + public CmdDelegate invokeFunction; + } + + static readonly Dictionary cmdHandlerDelegates = new Dictionary(); + + // helper function register a Command/Rpc/SyncEvent delegate + [EditorBrowsable(EditorBrowsableState.Never)] + protected static void RegisterDelegate(Type invokeClass, string cmdName, MirrorInvokeType invokerType, CmdDelegate func) + { + int cmdHash = GetMethodHash(invokeClass, cmdName); // type+func so Inventory.RpcUse != Equipment.RpcUse + + if (cmdHandlerDelegates.ContainsKey(cmdHash)) + { + // something already registered this hash + Invoker oldInvoker = cmdHandlerDelegates[cmdHash]; + if (oldInvoker.invokeClass == invokeClass && oldInvoker.invokeType == invokerType && oldInvoker.invokeFunction == func) + { + // it's all right, it was the same function + return; + } + + Debug.LogError($"Function {oldInvoker.invokeClass}.{oldInvoker.invokeFunction.GetMethodName()} and {invokeClass}.{oldInvoker.invokeFunction.GetMethodName()} have the same hash. Please rename one of them"); + } + Invoker invoker = new Invoker + { + invokeType = invokerType, + invokeClass = invokeClass, + invokeFunction = func + }; + cmdHandlerDelegates[cmdHash] = invoker; + if (LogFilter.Debug) Debug.Log("RegisterDelegate hash:" + cmdHash + " invokerType: " + invokerType + " method:" + func.GetMethodName()); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected static void RegisterCommandDelegate(Type invokeClass, string cmdName, CmdDelegate func) + { + RegisterDelegate(invokeClass, cmdName, MirrorInvokeType.Command, func); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected static void RegisterRpcDelegate(Type invokeClass, string rpcName, CmdDelegate func) + { + RegisterDelegate(invokeClass, rpcName, MirrorInvokeType.ClientRpc, func); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected static void RegisterEventDelegate(Type invokeClass, string eventName, CmdDelegate func) + { + RegisterDelegate(invokeClass, eventName, MirrorInvokeType.SyncEvent, func); + } + + static bool GetInvokerForHash(int cmdHash, MirrorInvokeType invokeType, out Invoker invoker) + { + if (cmdHandlerDelegates.TryGetValue(cmdHash, out invoker) && + invoker != null && + invoker.invokeType == invokeType) + { + return true; + } + + // debug message if not found, or null, or mismatched type + // (no need to throw an error, an attacker might just be trying to + // call an cmd with an rpc's hash) + if (LogFilter.Debug) Debug.Log("GetInvokerForHash hash:" + cmdHash + " not found"); + return false; + } + + // InvokeCmd/Rpc/SyncEventDelegate can all use the same function here + internal bool InvokeHandlerDelegate(int cmdHash, MirrorInvokeType invokeType, NetworkReader reader) + { + if (GetInvokerForHash(cmdHash, invokeType, out Invoker invoker) && + invoker.invokeClass.IsInstanceOfType(this)) + { + invoker.invokeFunction(this, reader); + return true; + } + return false; + } + #endregion + + #region Helpers + // helper function for [SyncVar] GameObjects. + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, ulong dirtyBit, ref uint netIdField) + { + if (getSyncVarHookGuard(dirtyBit)) + return; + + uint newNetId = 0; + if (newGameObject != null) + { + NetworkIdentity identity = newGameObject.GetComponent(); + if (identity != null) + { + newNetId = identity.netId; + if (newNetId == 0) + { + Debug.LogWarning("SetSyncVarGameObject GameObject " + newGameObject + " has a zero netId. Maybe it is not spawned yet?"); + } + } + } + + // netId changed? + if (newNetId != netIdField) + { + if (LogFilter.Debug) Debug.Log("SetSyncVar GameObject " + GetType().Name + " bit [" + dirtyBit + "] netfieldId:" + netIdField + "->" + newNetId); + SetDirtyBit(dirtyBit); + gameObjectField = newGameObject; // assign new one on the server, and in case we ever need it on client too + netIdField = newNetId; + } + } + + // helper function for [SyncVar] GameObjects. + // -> ref GameObject as second argument makes OnDeserialize processing easier + [EditorBrowsable(EditorBrowsableState.Never)] + protected GameObject GetSyncVarGameObject(uint netId, ref GameObject gameObjectField) + { + // server always uses the field + if (isServer) + { + 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 (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null) + return identity.gameObject; + return null; + } + + // helper function for [SyncVar] NetworkIdentities. + [EditorBrowsable(EditorBrowsableState.Never)] + 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?"); + } + } + + // netId changed? + if (newNetId != netIdField) + { + if (LogFilter.Debug) Debug.Log("SetSyncVarNetworkIdentity NetworkIdentity " + GetType().Name + " bit [" + dirtyBit + "] netIdField:" + netIdField + "->" + newNetId); + SetDirtyBit(dirtyBit); + netIdField = newNetId; + identityField = newIdentity; // assign new one on the server, and in case we ever need it on client too + } + } + + // helper function for [SyncVar] NetworkIdentities. + // -> ref GameObject as second argument makes OnDeserialize processing easier + [EditorBrowsable(EditorBrowsableState.Never)] + protected NetworkIdentity GetSyncVarNetworkIdentity(uint netId, ref NetworkIdentity identityField) + { + // server always uses the field + if (isServer) + { + 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 + NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity); + return identity; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected void SetSyncVar(T value, ref T fieldValue, ulong dirtyBit) + { + // newly initialized or changed value? + if (!EqualityComparer.Default.Equals(value, fieldValue)) + { + if (LogFilter.Debug) Debug.Log("SetSyncVar " + GetType().Name + " bit [" + dirtyBit + "] " + fieldValue + "->" + value); + SetDirtyBit(dirtyBit); + fieldValue = value; + } + } + #endregion + + /// + /// Used to set the behaviour as dirty, so that a network update will be sent for the object. + /// these are masks, not bit numbers, ie. 0x004 not 2 + /// + /// Bit mask to set. + public void SetDirtyBit(ulong dirtyBit) + { + syncVarDirtyBits |= dirtyBit; + } + + /// + /// This clears all the dirty bits that were set on this script by SetDirtyBits(); + /// This is automatically invoked when an update is sent for this object, but can be called manually as well. + /// + public void ClearAllDirtyBits() + { + lastSyncTime = Time.time; + syncVarDirtyBits = 0L; + + // flush all unsynchronized changes in syncobjects + // note: don't use List.ForEach here, this is a hot path + // List.ForEach: 432b/frame + // for: 231b/frame + for (int i = 0; i < syncObjects.Count; ++i) + { + syncObjects[i].Flush(); + } + } + + bool AnySyncObjectDirty() + { + // note: don't use Linq here. 1200 networked objects: + // Linq: 187KB GC/frame;, 2.66ms time + // for: 8KB GC/frame; 1.28ms time + for (int i = 0; i < syncObjects.Count; ++i) + { + if (syncObjects[i].IsDirty) + { + return true; + } + } + return false; + } + + internal bool IsDirty() + { + if (Time.time - lastSyncTime >= syncInterval) + { + return syncVarDirtyBits != 0L || AnySyncObjectDirty(); + } + return false; + } + + /// + /// Virtual function to override to send custom serialization data. The corresponding function to send serialization data is OnDeserialize(). + /// + /// + /// The initialState flag is useful to differentiate between the first time an object is serialized and when incremental updates can be sent. The first time an object is sent to a client, it must include a full state snapshot, but subsequent updates can save on bandwidth by including only incremental changes. Note that SyncVar hook functions are not called when initialState is true, only for incremental updates. + /// If a class has SyncVars, then an implementation of this function and OnDeserialize() are added automatically to the class. So a class that has SyncVars cannot also have custom serialization functions. + /// The OnSerialize function should return true to indicate that an update should be sent. If it returns true, then the dirty bits for that script are set to zero, if it returns false then the dirty bits are not changed. This allows multiple changes to a script to be accumulated over time and sent when the system is ready, instead of every frame. + /// + /// Writer to use to write to the stream. + /// If this is being called to send initial state. + /// True if data was written. + public virtual bool OnSerialize(NetworkWriter writer, bool initialState) + { + if (initialState) + { + return SerializeObjectsAll(writer); + } + return SerializeObjectsDelta(writer); + } + + /// + /// Virtual function to override to receive custom serialization data. The corresponding function to send serialization data is OnSerialize(). + /// + /// Reader to read from the stream. + /// True if being sent initial state. + public virtual void OnDeserialize(NetworkReader reader, bool initialState) + { + if (initialState) + { + DeSerializeObjectsAll(reader); + } + else + { + DeSerializeObjectsDelta(reader); + } + } + + ulong DirtyObjectBits() + { + ulong dirtyObjects = 0; + for (int i = 0; i < syncObjects.Count; i++) + { + SyncObject syncObject = syncObjects[i]; + if (syncObject.IsDirty) + { + dirtyObjects |= 1UL << i; + } + } + return dirtyObjects; + } + + public bool SerializeObjectsAll(NetworkWriter writer) + { + bool dirty = false; + for (int i = 0; i < syncObjects.Count; i++) + { + SyncObject syncObject = syncObjects[i]; + syncObject.OnSerializeAll(writer); + dirty = true; + } + return dirty; + } + + public bool SerializeObjectsDelta(NetworkWriter writer) + { + bool dirty = false; + // write the mask + writer.WritePackedUInt64(DirtyObjectBits()); + // serializable objects, such as synclists + for (int i = 0; i < syncObjects.Count; i++) + { + SyncObject syncObject = syncObjects[i]; + if (syncObject.IsDirty) + { + syncObject.OnSerializeDelta(writer); + dirty = true; + } + } + return dirty; + } + + void DeSerializeObjectsAll(NetworkReader reader) + { + for (int i = 0; i < syncObjects.Count; i++) + { + SyncObject syncObject = syncObjects[i]; + syncObject.OnDeserializeAll(reader); + } + } + + void DeSerializeObjectsDelta(NetworkReader reader) + { + ulong dirty = reader.ReadPackedUInt64(); + for (int i = 0; i < syncObjects.Count; i++) + { + SyncObject syncObject = syncObjects[i]; + if ((dirty & (1UL << i)) != 0) + { + syncObject.OnDeserializeDelta(reader); + } + } + } + + /// + /// This is invoked on clients when the server has caused this object to be destroyed. + /// This can be used as a hook to invoke effects or do client specific cleanup. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual void OnNetworkDestroy() {} + + /// + /// This is invoked for NetworkBehaviour objects when they become active on the server. + /// This could be triggered by NetworkServer.Listen() for objects in the scene, or by NetworkServer.Spawn() for objects that are dynamically created. + /// This will be called for objects on a "host" as well as for object on a dedicated server. + /// + public virtual void OnStartServer() {} + + /// + /// Called on every NetworkBehaviour when it is activated on a client. + /// Objects on the host have this function called, as there is a local client on the host. The values of SyncVars on object are guaranteed to be initialized correctly with the latest state from the server when this function is called on the client. + /// + public virtual void OnStartClient() {} + + /// + /// Called when the local player object has been set up. + /// This happens after OnStartClient(), as it is triggered by an ownership message from the server. This is an appropriate place to activate components or functionality that should only be active for the local player, such as cameras and input. + /// + public virtual void OnStartLocalPlayer() {} + + /// + /// This is invoked on behaviours that have authority, based on context and 'NetworkIdentity.localPlayerAuthority.' + /// This is called after OnStartServer and OnStartClient. + /// When is called on the server, this will be called on the client that owns the object. When an object is spawned with NetworkServer.SpawnWithClientAuthority, this will be called on the client that owns the object. + /// + public virtual void OnStartAuthority() {} + + /// + /// This is invoked on behaviours when authority is removed. + /// When NetworkIdentity.RemoveClientAuthority is called on the server, this will be called on the client that owns the object. + /// + public virtual void OnStopAuthority() {} + + /// + /// 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. + /// true when overwriting so that Mirror knows that we wanted to rebuild observers ourselves. otherwise it uses built in rebuild. + public virtual bool OnRebuildObservers(HashSet observers, bool initialize) + { + return false; + } + + /// + /// 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 visibile 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. + /// + /// New visibility state. + public virtual void OnSetLocalVisibility(bool vis) {} + + /// + /// 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 virtual bool OnCheckObserver(NetworkConnection conn) + { + return true; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkBehaviour.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkBehaviour.cs.meta new file mode 100644 index 0000000..84e619d --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 655ee8cba98594f70880da5cc4dc442d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkClient.cs b/Assets/Packages/Mirror/Runtime/NetworkClient.cs new file mode 100644 index 0000000..07473b3 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkClient.cs @@ -0,0 +1,464 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using UnityEngine; + +namespace Mirror +{ + public enum ConnectState + { + None, + Connecting, + Connected, + Disconnected + } + + // TODO make fully static after removing obsoleted singleton! + /// + /// This is a network client class used by the networking system. It contains a NetworkConnection that is used to connect to a network server. + /// The NetworkClient handle connection state, messages handlers, and connection configuration. There can be many NetworkClient instances in a process at a time, but only one that is connected to a game server (NetworkServer) that uses spawned objects. + /// NetworkClient has an internal update function where it handles events from the transport layer. This includes asynchronous connect events, disconnect events and incoming data from a server. + /// The NetworkManager has a NetworkClient instance that it uses for games that it starts, but the NetworkClient may be used by itself. + /// + public class NetworkClient + { + /// + /// Obsolete: Use directly. + /// Singleton isn't needed anymore, all functions are static now. For example: NetworkClient.Send(message) instead of NetworkClient.singleton.Send(message). + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkClient directly. Singleton isn't needed anymore, all functions are static now. For example: NetworkClient.Send(message) instead of NetworkClient.singleton.Send(message).")] + public static NetworkClient singleton = new NetworkClient(); + + /// + /// A list of all the active network clients in the current process. + /// This is NOT a list of all clients that are connected to the remote server, it is client instances on the local game. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkClient directly instead. There is always exactly one client.")] + public static List allClients => new List { singleton }; + + /// + /// The registered network message handlers. + /// + public static readonly Dictionary handlers = new Dictionary(); + + /// + /// The NetworkConnection object this client is using. + /// + public static NetworkConnection connection { get; internal set; } + + internal static ConnectState connectState = ConnectState.None; + + /// + /// The IP address of the server that this client is connected to. + /// This will be empty if the client has not connected yet. + /// + public static string serverIp => connection.address; + + /// + /// active is true while a client is connecting/connected + /// (= while the network is active) + /// + public static bool active => connectState == ConnectState.Connecting || connectState == ConnectState.Connected; + + /// + /// This gives the current connection status of the client. + /// + public static bool isConnected => connectState == ConnectState.Connected; + + /// + /// NetworkClient can connect to local server in host mode too + /// + public static bool isLocalClient => connection is ULocalConnectionToServer; + + // local client in host mode might call Cmds/Rpcs during Update, but we + // want to apply them in LateUpdate like all other Transport messages + // to avoid race conditions. keep packets in Queue until LateUpdate. + internal static Queue localClientPacketQueue = new Queue(); + + /// + /// Connect client to a NetworkServer instance. + /// + /// + public static void Connect(string address) + { + if (LogFilter.Debug) Debug.Log("Client Connect: " + address); + + RegisterSystemHandlers(false); + Transport.activeTransport.enabled = true; + InitializeTransportHandlers(); + + connectState = ConnectState.Connecting; + Transport.activeTransport.ClientConnect(address); + + // setup all the handlers + connection = new NetworkConnection(address, 0); + connection.SetHandlers(handlers); + } + + /// + /// connect host mode + /// + internal static void ConnectLocalServer() + { + if (LogFilter.Debug) Debug.Log("Client Connect Local Server"); + + RegisterSystemHandlers(true); + + connectState = ConnectState.Connected; + + // create local connection to server + connection = new ULocalConnectionToServer(); + connection.SetHandlers(handlers); + + // create server connection to local client + ULocalConnectionToClient connectionToClient = new ULocalConnectionToClient(); + NetworkServer.SetLocalConnection(connectionToClient); + + localClientPacketQueue.Enqueue(MessagePacker.Pack(new ConnectMessage())); + } + + /// + /// Called by the server to set the LocalClient's LocalPlayer object during NetworkServer.AddPlayer() + /// + /// + internal static void AddLocalPlayer(NetworkIdentity localPlayer) + { + if (LogFilter.Debug) Debug.Log("Local client AddLocalPlayer " + localPlayer.gameObject.name + " conn=" + connection.connectionId); + connection.isReady = true; + connection.playerController = localPlayer; + if (localPlayer != null) + { + localPlayer.isClient = true; + NetworkIdentity.spawned[localPlayer.netId] = localPlayer; + localPlayer.connectionToServer = connection; + } + // there is no SystemOwnerMessage for local client. add to ClientScene here instead + ClientScene.InternalAddPlayer(localPlayer); + } + + static void InitializeTransportHandlers() + { + Transport.activeTransport.OnClientConnected.AddListener(OnConnected); + Transport.activeTransport.OnClientDataReceived.AddListener(OnDataReceived); + Transport.activeTransport.OnClientDisconnected.AddListener(OnDisconnected); + Transport.activeTransport.OnClientError.AddListener(OnError); + } + + static void OnError(Exception exception) + { + Debug.LogException(exception); + } + + static void OnDisconnected() + { + connectState = ConnectState.Disconnected; + + ClientScene.HandleClientDisconnect(connection); + + connection?.InvokeHandler(new DisconnectMessage()); + } + + internal static void OnDataReceived(ArraySegment data) + { + if (connection != null) + { + connection.TransportReceive(data); + } + else Debug.LogError("Skipped Data message handling because connection is null."); + } + + static void OnConnected() + { + if (connection != null) + { + // reset network time stats + NetworkTime.Reset(); + + // the handler may want to send messages to the client + // thus we should set the connected state before calling the handler + connectState = ConnectState.Connected; + NetworkTime.UpdateClient(); + connection.InvokeHandler(new ConnectMessage()); + } + else Debug.LogError("Skipped Connect message handling because connection is null."); + } + + /// + /// Disconnect from server. + /// The disconnect message will be invoked. + /// + public static void Disconnect() + { + connectState = ConnectState.Disconnected; + ClientScene.HandleClientDisconnect(connection); + + // local or remote connection? + if (isLocalClient) + { + if (isConnected) + { + localClientPacketQueue.Enqueue(MessagePacker.Pack(new DisconnectMessage())); + } + NetworkServer.RemoveLocalConnection(); + } + else + { + if (connection != null) + { + connection.Disconnect(); + connection.Dispose(); + connection = null; + RemoveTransportHandlers(); + } + } + } + + static void RemoveTransportHandlers() + { + // so that we don't register them more than once + Transport.activeTransport.OnClientConnected.RemoveListener(OnConnected); + Transport.activeTransport.OnClientDataReceived.RemoveListener(OnDataReceived); + Transport.activeTransport.OnClientDisconnected.RemoveListener(OnDisconnected); + Transport.activeTransport.OnClientError.RemoveListener(OnError); + } + + /// + /// Obsolete: Use instead with no message id instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use SendMessage instead with no message id instead")] + public static bool Send(short msgType, MessageBase msg) + { + if (connection != null) + { + if (connectState != ConnectState.Connected) + { + Debug.LogError("NetworkClient Send when not connected to a server"); + return false; + } + return connection.Send(msgType, msg); + } + Debug.LogError("NetworkClient Send with no connection"); + return false; + } + + /// + /// This sends a network message with a message Id to the server. This message is sent on channel zero, which by default is the reliable channel. + /// The message must be an instance of a class derived from MessageBase. + /// The message id passed to Send() is used to identify the handler function to invoke on the server when the message is received. + /// + /// The message type to unregister. + /// + /// + /// True if message was sent. + public static bool Send(T message, int channelId = Channels.DefaultReliable) where T : IMessageBase + { + if (connection != null) + { + if (connectState != ConnectState.Connected) + { + Debug.LogError("NetworkClient Send when not connected to a server"); + return false; + } + return connection.Send(message, channelId); + } + Debug.LogError("NetworkClient Send with no connection"); + return false; + } + + internal static void Update() + { + // local or remote connection? + if (isLocalClient) + { + // process internal messages so they are applied at the correct time + while (localClientPacketQueue.Count > 0) + { + byte[] packet = localClientPacketQueue.Dequeue(); + OnDataReceived(new ArraySegment(packet)); + } + } + else + { + // only update things while connected + if (active && connectState == ConnectState.Connected) + { + NetworkTime.UpdateClient(); + } + } + } + + /* TODO use or remove + void GenerateConnectError(byte error) + { + Debug.LogError("Mirror Client Error Connect Error: " + error); + GenerateError(error); + } + + void GenerateDataError(byte error) + { + NetworkError dataError = (NetworkError)error; + Debug.LogError("Mirror Client Data Error: " + dataError); + GenerateError(error); + } + + void GenerateDisconnectError(byte error) + { + NetworkError disconnectError = (NetworkError)error; + Debug.LogError("Mirror Client Disconnect Error: " + disconnectError); + GenerateError(error); + } + + void GenerateError(byte error) + { + int msgId = MessageBase.GetId(); + if (handlers.TryGetValue(msgId, out NetworkMessageDelegate msgDelegate)) + { + ErrorMessage msg = new ErrorMessage + { + value = error + }; + + // write the message to a local buffer + NetworkWriter writer = new NetworkWriter(); + msg.Serialize(writer); + + NetworkMessage netMsg = new NetworkMessage + { + msgType = msgId, + reader = new NetworkReader(writer.ToArray()), + conn = connection + }; + msgDelegate(netMsg); + } + } + */ + + /// + /// Obsolete: Use instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkTime.rtt instead")] + public static float GetRTT() + { + return (float)NetworkTime.rtt; + } + + internal static void RegisterSystemHandlers(bool localClient) + { + // local client / regular 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 (localClient) + { + RegisterHandler(ClientScene.OnLocalClientObjectDestroy); + RegisterHandler(ClientScene.OnLocalClientObjectHide); + RegisterHandler((conn, msg) => { }); + RegisterHandler(ClientScene.OnLocalClientSpawnPrefab); + RegisterHandler(ClientScene.OnLocalClientSpawnSceneObject); + RegisterHandler((conn, msg) => { }); // host mode doesn't need spawning + RegisterHandler((conn, msg) => { }); // host mode doesn't need spawning + RegisterHandler((conn, msg) => { }); + } + else + { + RegisterHandler(ClientScene.OnObjectDestroy); + RegisterHandler(ClientScene.OnObjectHide); + RegisterHandler(NetworkTime.OnClientPong); + RegisterHandler(ClientScene.OnSpawnPrefab); + RegisterHandler(ClientScene.OnSpawnSceneObject); + RegisterHandler(ClientScene.OnObjectSpawnStarted); + RegisterHandler(ClientScene.OnObjectSpawnFinished); + RegisterHandler(ClientScene.OnUpdateVarsMessage); + } + RegisterHandler(ClientScene.OnClientAuthority); + RegisterHandler(ClientScene.OnRPCMessage); + RegisterHandler(ClientScene.OnSyncEventMessage); + } + + /// + /// Obsolete: Use instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use RegisterHandler instead")] + public static void RegisterHandler(int msgType, NetworkMessageDelegate handler) + { + if (handlers.ContainsKey(msgType)) + { + if (LogFilter.Debug) Debug.Log("NetworkClient.RegisterHandler replacing " + handler + " - " + msgType); + } + handlers[msgType] = handler; + } + + /// + /// Obsolete: Use instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use RegisterHandler instead")] + public static void RegisterHandler(MsgType msgType, NetworkMessageDelegate handler) + { + RegisterHandler((int)msgType, handler); + } + + /// + /// Register a handler for a particular message type. + /// There are several system message types which you can add handlers for. You can also add your own message types. + /// + /// The message type to unregister. + /// + public static void RegisterHandler(Action handler) where T : IMessageBase, new() + { + int msgType = MessagePacker.GetId(); + if (handlers.ContainsKey(msgType)) + { + if (LogFilter.Debug) Debug.Log("NetworkClient.RegisterHandler replacing " + handler + " - " + msgType); + } + handlers[msgType] = MessagePacker.MessageHandler(handler); + } + + /// + /// Obsolete: Use instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use UnregisterHandler instead")] + public static void UnregisterHandler(int msgType) + { + handlers.Remove(msgType); + } + + /// + /// Obsolete: Use instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use UnregisterHandler instead")] + public static void UnregisterHandler(MsgType msgType) + { + UnregisterHandler((int)msgType); + } + + /// + /// Unregisters a network message handler. + /// + /// The message type to unregister. + public static void UnregisterHandler() where T : IMessageBase + { + // use int to minimize collisions + int msgType = MessagePacker.GetId(); + handlers.Remove(msgType); + } + + /// + /// Shut down a client. + /// This should be done when a client is no longer going to be used. + /// + public static void Shutdown() + { + if (LogFilter.Debug) Debug.Log("Shutting down client."); + ClientScene.Shutdown(); + connectState = ConnectState.None; + } + + /// + /// Obsolete: Call instead. There is only one client. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Call NetworkClient.Shutdown() instead. There is only one client.")] + public static void ShutdownAll() + { + Shutdown(); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkClient.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkClient.cs.meta new file mode 100644 index 0000000..b43b514 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: abe6be14204d94224a3e7cd99dd2ea73 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkConnection.cs b/Assets/Packages/Mirror/Runtime/NetworkConnection.cs new file mode 100644 index 0000000..613147b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkConnection.cs @@ -0,0 +1,375 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using UnityEngine; + +namespace Mirror +{ + /// + /// A High level network connection. This is used for connections from client-to-server and for connection from server-to-client. + /// + /// + /// A NetworkConnection corresponds to a specific connection for a host in the transport layer. It has a connectionId that is assigned by the transport layer and passed to the Initialize function. + /// A NetworkClient has one NetworkConnection. A NetworkServerSimple manages multiple NetworkConnections. The NetworkServer has multiple "remote" connections and a "local" connection for the local client. + /// The NetworkConnection class provides message sending and handling facilities. For sending data over a network, there are methods to send message objects, byte arrays, and NetworkWriter objects. To handle data arriving from the network, handler functions can be registered for message Ids, byte arrays can be processed by HandleBytes(), and NetworkReader object can be processed by HandleReader(). + /// NetworkConnection objects also act as observers for networked objects. When a connection is an observer of a networked object with a NetworkIdentity, then the object will be visible to corresponding client for the connection, and incremental state changes will be sent to the client. + /// NetworkConnection objects can "own" networked game objects. Owned objects will be destroyed on the server by default when the connection is destroyed. A connection owns the player objects created by its client, and other objects with client-authority assigned to the corresponding client. + /// There are many virtual functions on NetworkConnection that allow its behaviour to be customized. NetworkClient and NetworkServer can both be made to instantiate custom classes derived from NetworkConnection by setting their networkConnectionClass member variable. + /// + public class NetworkConnection : IDisposable + { + public readonly HashSet visList = new HashSet(); + + Dictionary messageHandlers; + + /// + /// Unique identifier for this connection that is assigned by the transport layer. + /// + /// + /// On a server, this Id is unique for every connection on the server. On a client this Id is local to the client, it is not the same as the Id on the server for this connection. + /// Transport layers connections begin at one. So on a client with a single connection to a server, the connectionId of that connection will be one. In NetworkServer, the connectionId of the local connection is zero. + /// Clients do not know their connectionId on the server, and do not know the connectionId of other clients on the server. + /// + public int connectionId = -1; + + /// + /// Flag that tells if the connection has been marked as "ready" by a client calling ClientScene.Ready(). + /// This property is read-only. It is set by the system on the client when ClientScene.Ready() is called, and set by the system on the server when a ready message is received from a client. + /// A client that is ready is sent spawned objects by the server and updates to the state of spawned objects. A client that is not ready is not sent spawned objects. + /// + public bool isReady; + + /// + /// The IP address / URL / FQDN associated with the connection. + /// + public string address; + + /// + /// The last time that a message was received on this connection. + /// This includes internal system messages (such as Commands and ClientRpc calls) and user messages. + /// + public float lastMessageTime; + + /// + /// The NetworkIdentity for this connection. + /// + public NetworkIdentity playerController { get; internal set; } + + /// + /// A list of the NetworkIdentity objects owned by this connection. This list is read-only. + /// This includes the player object for the connection - if it has localPlayerAutority set, and any objects spawned with local authority or set with AssignLocalAuthority. + /// This list can be used to validate messages from clients, to ensure that clients are only trying to control objects that they own. + /// + public readonly HashSet clientOwnedObjects = new HashSet(); + + /// + /// Setting this to true will log the contents of network message to the console. + /// + /// + /// Warning: this can be a lot of data and can be very slow. Both incoming and outgoing messages are logged. The format of the logs is: + /// ConnectionSend con:1 bytes:11 msgId:5 FB59D743FD120000000000 ConnectionRecv con:1 bytes:27 msgId:8 14F21000000000016800AC3FE090C240437846403CDDC0BD3B0000 + /// Note that these are application-level network messages, not protocol-level packets. There will typically be multiple network messages combined in a single protocol packet. + /// + public bool logNetworkMessages; + + // this is always true for regular connections, false for local + // connections because it's set in the constructor and never reset. + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("isConnected will be removed because it's pointless. A NetworkConnection is always connected.")] + public bool isConnected { get; protected set; } + + // this is always 0 for regular connections, -1 for local + // connections because it's set in the constructor and never reset. + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("hostId will be removed because it's not needed ever since we removed LLAPI as default. It's always 0 for regular connections and -1 for local connections. Use connection.GetType() == typeof(NetworkConnection) to check if it's a regular or local connection.")] + public int hostId = -1; + + /// + /// Creates a new NetworkConnection with the specified address + /// + /// + public NetworkConnection(string networkAddress) + { + address = networkAddress; + } + + /// + /// Creates a new NetworkConnection with the specified address and connectionId + /// + /// + /// + public NetworkConnection(string networkAddress, int networkConnectionId) + { + address = networkAddress; + connectionId = networkConnectionId; +#pragma warning disable 618 + isConnected = true; + hostId = 0; +#pragma warning restore 618 + } + + ~NetworkConnection() + { + Dispose(false); + } + + /// + /// Disposes of this connection, releasing channel buffers that it holds. + /// + public void Dispose() + { + Dispose(true); + // Take yourself off the Finalization queue + // to prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + foreach (uint netId in clientOwnedObjects) + { + if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity)) + { + identity.clientAuthorityOwner = null; + } + } + clientOwnedObjects.Clear(); + } + + /// + /// Disconnects this connection. + /// + public void Disconnect() + { + // don't clear address so we can still access it in NetworkManager.OnServerDisconnect + // => it's reset in Initialize anyway and there is no address empty check anywhere either + //address = ""; + + // set not ready and handle clientscene disconnect in any case + // (might be client or host mode here) + isReady = false; + ClientScene.HandleClientDisconnect(this); + + // server? then disconnect that client (not for host local player though) + if (Transport.activeTransport.ServerActive() && connectionId != 0) + { + Transport.activeTransport.ServerDisconnect(connectionId); + } + // not server and not host mode? then disconnect client + else + { + Transport.activeTransport.ClientDisconnect(); + } + + RemoveObservers(); + } + + internal void SetHandlers(Dictionary handlers) + { + messageHandlers = handlers; + } + + /// + /// Obsolete: Use NetworkClient/NetworkServer.RegisterHandler{T} instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkClient/NetworkServer.RegisterHandler instead")] + public void RegisterHandler(short msgType, NetworkMessageDelegate handler) + { + if (messageHandlers.ContainsKey(msgType)) + { + if (LogFilter.Debug) Debug.Log("NetworkConnection.RegisterHandler replacing " + msgType); + } + messageHandlers[msgType] = handler; + } + + /// + /// Obsolete: Use and instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkClient/NetworkServer.UnregisterHandler instead")] + public void UnregisterHandler(short msgType) + { + messageHandlers.Remove(msgType); + } + + /// + /// Obsolete: use instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("use Send instead")] + public virtual bool Send(int msgType, MessageBase msg, int channelId = Channels.DefaultReliable) + { + // pack message and send + byte[] message = MessagePacker.PackMessage(msgType, msg); + return SendBytes(message, channelId); + } + + /// + /// This sends a network message with a message ID on the connection. This message is sent on channel zero, which by default is the reliable channel. + /// + /// The message type to unregister. + /// The message to send. + /// The transport layer channel to send on. + /// + public virtual bool Send(T msg, int channelId = Channels.DefaultReliable) where T: IMessageBase + { + // pack message and send + byte[] message = MessagePacker.Pack(msg); + return SendBytes(message, channelId); + } + + // internal because no one except Mirror should send bytes directly to + // the client. they would be detected as a message. send messages instead. + internal virtual bool SendBytes(byte[] bytes, int channelId = Channels.DefaultReliable) + { + if (logNetworkMessages) Debug.Log("ConnectionSend con:" + connectionId + " bytes:" + BitConverter.ToString(bytes)); + + if (bytes.Length > Transport.activeTransport.GetMaxPacketSize(channelId)) + { + Debug.LogError("NetworkConnection.SendBytes cannot send packet larger than " + Transport.activeTransport.GetMaxPacketSize(channelId) + " bytes"); + return false; + } + + if (bytes.Length == 0) + { + // zero length packets getting into the packet queues are bad. + Debug.LogError("NetworkConnection.SendBytes cannot send zero bytes"); + return false; + } + + return TransportSend(channelId, bytes); + } + + public override string ToString() + { + return $"connectionId: {connectionId} isReady: {isReady}"; + } + + internal void AddToVisList(NetworkIdentity identity) + { + visList.Add(identity); + + // spawn identity for this conn + NetworkServer.ShowForConnection(identity, this); + } + + internal void RemoveFromVisList(NetworkIdentity identity, bool isDestroyed) + { + visList.Remove(identity); + + if (!isDestroyed) + { + // hide identity for this conn + NetworkServer.HideForConnection(identity, this); + } + } + + internal void RemoveObservers() + { + foreach (NetworkIdentity identity in visList) + { + identity.RemoveObserverInternal(this); + } + visList.Clear(); + } + + /// + /// Obsolete: Use instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use InvokeHandler instead")] + public bool InvokeHandlerNoData(int msgType) + { + return InvokeHandler(msgType, null); + } + + internal bool InvokeHandler(int msgType, NetworkReader reader) + { + if (messageHandlers.TryGetValue(msgType, out NetworkMessageDelegate msgDelegate)) + { + NetworkMessage message = new NetworkMessage + { + msgType = msgType, + reader = reader, + conn = this + }; + + msgDelegate(message); + return true; + } + Debug.LogError("Unknown message ID " + msgType + " connId:" + connectionId); + return false; + } + + /// + /// This function invokes the registered handler function for a message. + /// Network connections used by the NetworkClient and NetworkServer use this function for handling network messages. + /// + /// The message type to unregister. + /// The message object to process. + /// + public bool InvokeHandler(T msg) where T : IMessageBase + { + int msgType = MessagePacker.GetId(); + byte[] data = MessagePacker.Pack(msg); + return InvokeHandler(msgType, new NetworkReader(data)); + } + + // note: original HLAPI HandleBytes function handled >1 message in a while loop, but this wasn't necessary + // anymore because NetworkServer/NetworkClient Update both use while loops to handle >1 data events per + // frame already. + // -> in other words, we always receive 1 message per Receive call, never two. + // -> can be tested easily with a 1000ms send delay and then logging amount received in while loops here + // and in NetworkServer/Client Update. HandleBytes already takes exactly one. + /// + /// This virtual function allows custom network connection classes to process data from the network before it is passed to the application. + /// + /// The data recieved. + public virtual void TransportReceive(ArraySegment buffer) + { + // unpack message + NetworkReader reader = new NetworkReader(buffer); + if (MessagePacker.UnpackMessage(reader, out int msgType)) + { + // logging + if (logNetworkMessages) Debug.Log("ConnectionRecv con:" + connectionId + " msgType:" + msgType + " content:" + BitConverter.ToString(buffer.Array, buffer.Offset, buffer.Count)); + + // try to invoke the handler for that message + if (InvokeHandler(msgType, reader)) + { + lastMessageTime = Time.time; + } + } + else + { + Debug.LogError("Closed connection: " + connectionId + ". Invalid message header."); + Disconnect(); + } + } + + /// + /// This virtual function allows custom network connection classes to process data send by the application before it goes to the network transport layer. + /// + /// Channel to send data on. + /// Data to send. + /// + public virtual bool TransportSend(int channelId, byte[] bytes) + { + if (Transport.activeTransport.ClientConnected()) + { + return Transport.activeTransport.ClientSend(channelId, bytes); + } + else if (Transport.activeTransport.ServerActive()) + { + return Transport.activeTransport.ServerSend(connectionId, channelId, bytes); + } + return false; + } + + internal void AddOwnedObject(NetworkIdentity obj) + { + clientOwnedObjects.Add(obj.netId); + } + + internal void RemoveOwnedObject(NetworkIdentity obj) + { + clientOwnedObjects.Remove(obj.netId); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkConnection.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkConnection.cs.meta new file mode 100644 index 0000000..3688d9c --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkConnection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 11ea41db366624109af1f0834bcdde2f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkIdentity.cs b/Assets/Packages/Mirror/Runtime/NetworkIdentity.cs new file mode 100644 index 0000000..362b14c --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkIdentity.cs @@ -0,0 +1,1253 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Security.Cryptography; +using UnityEngine; +using UnityEngine.Serialization; +#if UNITY_EDITOR +using UnityEditor; +#if UNITY_2018_3_OR_NEWER +using UnityEditor.Experimental.SceneManagement; +#endif +#endif + +namespace Mirror +{ + /// + /// The NetworkIdentity identifies objects across the network, between server and clients. Its primary data is a NetworkInstanceId which is allocated by the server and then set on clients. This is used in network communications to be able to lookup game objects on different machines. + /// + /// + /// The NetworkIdentity is used to synchronize information in the object with the network. Only the server should create instances of objects which have NetworkIdentity as otherwise they will not be properly connected to the system. + /// For complex objects with a hierarchy of subcomponents, the NetworkIdentity must be on the root of the hierarchy. It is not supported to have multiple NetworkIdentity components on subcomponents of a hierarchy. + /// NetworkBehaviour scripts require a NetworkIdentity on the game object to be able to function. + /// The NetworkIdentity manages the dirty state of the NetworkBehaviours of the object. When it discovers that NetworkBehaviours are dirty, it causes an update packet to be created and sent to clients. + /// The flow for serialization updates managed by the NetworkIdentity is: + /// * Each NetworkBehaviour has a dirty mask. This mask is available inside OnSerialize as syncVarDirtyBits + /// * Each SyncVar in a NetworkBehaviour script is assigned a bit in the dirty mask. + /// * Changing the value of SyncVars causes the bit for that SyncVar to be set in the dirty mask + /// * Alternatively, calling SetDirtyBit() writes directly to the dirty mask + /// * NetworkIdentity objects are checked on the server as part of it's update loop + /// * If any NetworkBehaviours on a NetworkIdentity are dirty, then an UpdateVars packet is created for that object + /// * The UpdateVars packet is populated by calling OnSerialize on each NetworkBehaviour on the object + /// * NetworkBehaviours that are NOT dirty write a zero to the packet for their dirty bits + /// * NetworkBehaviours that are dirty write their dirty mask, then the values for the SyncVars that have changed + /// * If OnSerialize returns true for a NetworkBehaviour, the dirty mask is reset for that NetworkBehaviour, so it will not send again until its value changes. + /// * The UpdateVars packet is sent to ready clients that are observing the object + /// On the client: + /// * an UpdateVars packet is received for an object + /// * The OnDeserialize function is called for each NetworkBehaviour script on the object + /// * Each NetworkBehaviour script on the object reads a dirty mask. + /// * If the dirty mask for a NetworkBehaviour is zero, the OnDeserialize functions returns without reading any more + /// * If the dirty mask is non-zero value, then the OnDeserialize function reads the values for the SyncVars that correspond to the dirty bits that are set + /// * If there are SyncVar hook functions, those are invoked with the value read from the stream. + /// + [ExecuteInEditMode] + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkIdentity")] + [HelpURL("https://mirror-networking.com/xmldocs/articles/Components/NetworkIdentity.html")] + public sealed class NetworkIdentity : MonoBehaviour + { + // configuration + bool m_IsServer; + NetworkBehaviour[] networkBehavioursCache; + + // member used to mark a identity for future reset + // check MarkForReset for more information. + bool m_Reset; + + /// + /// Returns true if running as a client and this object was spawned by a server. + /// + public bool isClient { get; internal set; } + + /// + /// Returns true if NetworkServer.active and server is not stopped. + /// + public bool isServer + { + get => m_IsServer && NetworkServer.active && netId != 0; + internal set => m_IsServer = value; + } + + /// + /// This returns true if this object is the one that represents the player on the local machine. + /// This is set when the server has spawned an object for this particular client. + /// + public bool isLocalPlayer { get; private set; } + + internal bool pendingOwner { get; set; } + + /// + /// This returns true if this object is the authoritative version of the object in the distributed network application. + /// This value is determined at runtime, as opposed to localPlayerAuthority which is set on the prefab. For most objects, authority is held by the server / host. For objects with localPlayerAuthority set, authority is held by the client of that player. + /// For objects that had their authority set by AssignClientAuthority on the server, this will be true on the client that owns the object. NOT on other clients. + /// + public bool hasAuthority { get; private set; } + + /// + /// The set of network connections (players) that can see this object. + /// null until OnStartServer was called. this is necessary for SendTo* to work properly in server-only mode. + /// + public Dictionary observers; + + /// + /// Unique identifier for this particular object instance, used for tracking objects between networked clients and the server. + /// This is a unique identifier for this particular GameObject instance. Use it to track GameObjects between networked clients and the server. + /// + public uint netId { get; internal set; } + + /// + /// A unique identifier for NetworkIdentity objects within a scene. + /// This is used for spawning scene objects on clients. + /// + public ulong sceneId => m_SceneId; + + /// + /// Flag to make this object only exist when the game is running as a server (or host). + /// + [FormerlySerializedAs("m_ServerOnly")] + public bool serverOnly; + + /// + /// localPlayerAuthority means that the client of the "owning" player has authority over their own player object. + /// Authority for this object will be on the player's client. So hasAuthority will be true on that client - and false on the server and on other clients. + /// + [FormerlySerializedAs("m_LocalPlayerAuthority")] + public bool localPlayerAuthority; + + /// + /// The client that has authority for this object. This will be null if no client has authority. + /// This is set for player objects with localPlayerAuthority, and for objects set with AssignClientAuthority, and spawned with SpawnWithClientAuthority. + /// + public NetworkConnection clientAuthorityOwner { get; internal set; } + + /// + /// The NetworkConnection associated with this NetworkIdentity. This is only valid for player objects on a local client. + /// + public NetworkConnection connectionToServer { get; internal set; } + + /// + /// The NetworkConnection associated with this NetworkIdentity. This is only valid for player objects on the server. + /// Use it to return details such as the connection's identity, IP address and ready status. + /// + public NetworkConnection connectionToClient { get; internal set; } + + /// + /// All spawned NetworkIdentities by netId. Available on server and client. + /// + public static readonly Dictionary spawned = new Dictionary(); + + public NetworkBehaviour[] NetworkBehaviours => networkBehavioursCache = networkBehavioursCache ?? GetComponents(); + + [SerializeField] string m_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 + // - UNET used 'NetworkHash128' originally, with byte0, ..., byte16 + // which works, but it just unnecessary extra code + // - 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 + /// + /// Unique identifier used to find the source assets when server spawns the on clients. + /// + public Guid assetId + { + get + { +#if UNITY_EDITOR + // This is important because sometimes OnValidate does not run (like when adding view to prefab with no child links) + if (string.IsNullOrEmpty(m_AssetId)) + SetupIDs(); +#endif + // convert string to Guid and use .Empty to avoid exception if + // we would use 'new Guid("")' + return string.IsNullOrEmpty(m_AssetId) ? Guid.Empty : new Guid(m_AssetId); + } + internal set + { + string newAssetIdString = value.ToString("N"); + if (string.IsNullOrEmpty(m_AssetId) || m_AssetId == newAssetIdString) + { + m_AssetId = newAssetIdString; + } + else Debug.LogWarning("SetDynamicAssetId object already has an assetId <" + m_AssetId + ">"); + } + } + + // persistent scene id + // (see AssignSceneID comments) + // suppress "Field 'NetworkIdentity.m_SceneId' is never assigned to, and will always have its default value 0" + // when building standalone + #pragma warning disable CS0649 + [SerializeField] ulong m_SceneId; + #pragma warning restore CS0649 + + // keep track of all sceneIds to detect scene duplicates + static readonly Dictionary sceneIds = new Dictionary(); + + // used when adding players + internal void SetClientOwner(NetworkConnection conn) + { + if (clientAuthorityOwner != null) + { + Debug.LogError("SetClientOwner m_ClientAuthorityOwner already set!"); + } + clientAuthorityOwner = conn; + clientAuthorityOwner.AddOwnedObject(this); + } + + internal void ForceAuthority(bool authority) + { + if (hasAuthority == authority) + { + return; + } + + hasAuthority = authority; + if (authority) + { + OnStartAuthority(); + } + else + { + OnStopAuthority(); + } + } + + static uint nextNetworkId = 1; + internal static uint GetNextNetworkId() => nextNetworkId++; + + /// + /// Resets nextNetworkId = 1 + /// + public static void ResetNextNetworkId() => nextNetworkId = 1; + + /// + /// The delegate type for the clientAuthorityCallback. + /// + /// The network connection that is gaining or losing authority. + /// The object whose client authority status is being changed. + /// The new state of client authority of the object for the connection. + public delegate void ClientAuthorityCallback(NetworkConnection conn, NetworkIdentity identity, bool authorityState); + + /// + /// A callback that can be populated to be notified when the client-authority state of objects changes. + /// Whenever an object is spawned using SpawnWithClientAuthority, or the client authority status of an object is changed with AssignClientAuthority or RemoveClientAuthority, then this callback will be invoked. + /// This callback is used by the NetworkMigrationManager to distribute client authority state to peers for host migration. If the NetworkMigrationManager is not being used, this callback does not need to be populated. + /// + public static ClientAuthorityCallback clientAuthorityCallback; + + // used when the player object for a connection changes + internal void SetNotLocalPlayer() + { + isLocalPlayer = false; + + if (NetworkServer.active && NetworkServer.localClientActive) + { + // dont change authority for objects on the host + return; + } + hasAuthority = false; + } + + // this is used when a connection is destroyed, since the "observers" property is read-only + internal void RemoveObserverInternal(NetworkConnection conn) + { + observers?.Remove(conn.connectionId); + } + + void Awake() + { + // detect runtime sceneId duplicates, e.g. if a user tries to + // Instantiate a sceneId object at runtime. if we don't detect it, + // then the client won't know which of the two objects to use for a + // SpawnSceneObject message, and it's likely going to be the wrong + // object. + // + // This might happen if for example we have a Dungeon GameObject + // which contains a Skeleton monster as child, and when a player + // runs into the Dungeon we create a Dungeon Instance of that + // Dungeon, which would duplicate a scene object. + // + // see also: https://github.com/vis2k/Mirror/issues/384 + if (Application.isPlaying && sceneId != 0) + { + if (sceneIds.TryGetValue(sceneId, out NetworkIdentity existing) && existing != this) + { + Debug.LogError(name + "'s sceneId: " + sceneId.ToString("X") + " is already taken by: " + existing.name + ". 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."); + Destroy(gameObject); + } + else + { + sceneIds[sceneId] = this; + } + } + } + + void OnValidate() + { +#if UNITY_EDITOR + if (serverOnly && localPlayerAuthority) + { + Debug.LogWarning("Disabling Local Player Authority for " + gameObject + " because it is server-only."); + localPlayerAuthority = false; + } + + SetupIDs(); +#endif + } + +#if UNITY_EDITOR + void AssignAssetID(GameObject prefab) => AssignAssetID(AssetDatabase.GetAssetPath(prefab)); + void AssignAssetID(string path) => m_AssetId = AssetDatabase.AssetPathToGUID(path); + + bool ThisIsAPrefab() => PrefabUtility.IsPartOfPrefabAsset(gameObject); + + bool ThisIsASceneObjectWithPrefabParent(out GameObject prefab) + { + prefab = null; + + if (!PrefabUtility.IsPartOfPrefabInstance(gameObject)) + { + return false; + } + prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject); + + if (prefab == null) + { + Debug.LogError("Failed to find prefab parent for scene object [name:" + gameObject.name + "]"); + return false; + } + return true; + } + + static uint GetRandomUInt() + { + // 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); + } + } + + // 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(m_SceneId, out NetworkIdentity existing) && existing != null && existing != this; + if (m_SceneId == 0 || duplicate) + { + // clear in any case, because it might have been a duplicate + m_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 Exception("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 = GetRandomUInt(); + + // 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) + { + m_SceneId = randomId; + //Debug.Log(name + " in scene=" + gameObject.scene.name + " sceneId assigned to: " + m_SceneId.ToString("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[m_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! + [EditorBrowsable(EditorBrowsableState.Never)] + public void SetSceneIdSceneHashPartInternal() + { + // get deterministic scene hash + uint pathHash = (uint)gameObject.scene.path.GetStableHashCode(); + + // shift hash from 0x000000FFFFFFFF to 0xFFFFFFFF00000000 + ulong shiftedHash = (ulong)pathHash << 32; + + // OR into scene id + m_SceneId = (m_SceneId & 0xFFFFFFFF) | shiftedHash; + + // log it. this is incredibly useful to debug sceneId issues. + if (LogFilter.Debug) Debug.Log(name + " in scene=" + gameObject.scene.name + " scene index hash(" + pathHash.ToString("X") + ") copied into sceneId: " + m_SceneId.ToString("X")); + } + + void SetupIDs() + { + if (ThisIsAPrefab()) + { + m_SceneId = 0; // force 0 for prefabs + AssignAssetID(gameObject); + } + // check prefabstage BEFORE SceneObjectWithPrefabParent + // (fixes https://github.com/vis2k/Mirror/issues/976) + else if (PrefabStageUtility.GetCurrentPrefabStage() != null) + { + m_SceneId = 0; // force 0 for prefabs + string path = PrefabStageUtility.GetCurrentPrefabStage().prefabAssetPath; + AssignAssetID(path); + } + else if (ThisIsASceneObjectWithPrefabParent(out GameObject prefab)) + { + AssignSceneID(); + AssignAssetID(prefab); + } + else + { + AssignSceneID(); + m_AssetId = ""; + } + } +#endif + + void OnDestroy() + { + // remove from sceneIds + // -> remove with (0xFFFFFFFFFFFFFFFF) and without (0x00000000FFFFFFFF) + // sceneHash to be 100% safe. + sceneIds.Remove(sceneId); + sceneIds.Remove(sceneId & 0x00000000FFFFFFFF); + + if (m_IsServer && NetworkServer.active) + { + NetworkServer.Destroy(gameObject); + } + } + + internal void OnStartServer(bool allowNonZeroNetId) + { + if (m_IsServer) + { + return; + } + m_IsServer = true; + hasAuthority = !localPlayerAuthority; + + observers = new Dictionary(); + + // If the instance/net ID is invalid here then this is an object instantiated from a prefab and the server should assign a valid ID + if (netId == 0) + { + netId = GetNextNetworkId(); + } + else + { + if (!allowNonZeroNetId) + { + Debug.LogError("Object has non-zero netId " + netId + " for " + gameObject); + return; + } + } + + if (LogFilter.Debug) Debug.Log("OnStartServer " + this + " NetId:" + netId + " SceneId:" + sceneId); + + // add to spawned (note: the original EnableIsServer isn't needed + // because we already set m_isServer=true above) + spawned[netId] = this; + + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + try + { + comp.OnStartServer(); + } + catch (Exception e) + { + Debug.LogError("Exception in OnStartServer:" + e.Message + " " + e.StackTrace); + } + } + + if (NetworkClient.active && NetworkServer.localClientActive) + { + // there will be no spawn message, so start the client here too + OnStartClient(); + } + + if (hasAuthority) + { + OnStartAuthority(); + } + } + + internal void OnStartClient() + { + isClient = true; + + if (LogFilter.Debug) Debug.Log("OnStartClient " + gameObject + " netId:" + netId + " localPlayerAuthority:" + localPlayerAuthority); + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + try + { + comp.OnStartClient(); // user implemented startup + } + catch (Exception e) + { + Debug.LogError("Exception in OnStartClient:" + e.Message + " " + e.StackTrace); + } + } + } + + void OnStartAuthority() + { + if (networkBehavioursCache == null) + { + Debug.LogError("Network object " + name + " not initialized properly. Do you have more than one NetworkIdentity in the same object? Did you forget to spawn this object with NetworkServer?", this); + return; + } + + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + try + { + comp.OnStartAuthority(); + } + catch (Exception e) + { + Debug.LogError("Exception in OnStartAuthority:" + e.Message + " " + e.StackTrace); + } + } + } + + void OnStopAuthority() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + try + { + comp.OnStopAuthority(); + } + catch (Exception e) + { + Debug.LogError("Exception in OnStopAuthority:" + e.Message + " " + e.StackTrace); + } + } + } + + internal void OnSetLocalVisibility(bool vis) + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + try + { + comp.OnSetLocalVisibility(vis); + } + catch (Exception e) + { + Debug.LogError("Exception in OnSetLocalVisibility:" + e.Message + " " + e.StackTrace); + } + } + } + + internal bool OnCheckObserver(NetworkConnection conn) + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + try + { + if (!comp.OnCheckObserver(conn)) + return false; + } + catch (Exception e) + { + Debug.LogError("Exception in OnCheckObserver:" + e.Message + " " + e.StackTrace); + } + } + return true; + } + + // vis2k: readstring bug prevention: https://issuetracker.unity3d.com/issues/unet-networkwriter-dot-write-causing-readstring-slash-readbytes-out-of-range-errors-in-clients + // -> OnSerialize writes length,componentData,length,componentData,... + // -> OnDeserialize carefully extracts each data, then deserializes each component with separate readers + // -> it will be impossible to read too many or too few bytes in OnDeserialize + // -> we can properly track down errors + bool OnSerializeSafely(NetworkBehaviour comp, NetworkWriter writer, bool initialState) + { + // write placeholder length bytes + // (jumping back later is WAY faster than allocating a temporary + // writer for the payload, then writing payload.size, payload) + int headerPosition = writer.Position; + writer.WriteInt32(0); + int contentPosition = writer.Position; + + // write payload + bool result = false; + try + { + result = comp.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=" + comp.GetType() + " sceneId=" + m_SceneId.ToString("X") + "\n\n" + e); + } + int endPosition = writer.Position; + + // fill in length now + writer.Position = headerPosition; + writer.WriteInt32(endPosition - contentPosition); + writer.Position = endPosition; + + if (LogFilter.Debug) Debug.Log("OnSerializeSafely written for object=" + comp.name + " component=" + comp.GetType() + " sceneId=" + m_SceneId.ToString("X") + "header@" + headerPosition + " content@" + contentPosition + " end@" + endPosition + " contentSize=" + (endPosition - contentPosition)); + + return result; + } + + // serialize all components (or only dirty ones if not initial state) + // -> check ownerWritten/observersWritten to know if anything was written + internal void OnSerializeAllSafely(bool initialState, NetworkWriter ownerWriter, out int ownerWritten, NetworkWriter observersWriter, out int observersWritten) + { + // clear 'written' variables + ownerWritten = observersWritten = 0; + + if (NetworkBehaviours.Length > 64) + { + Debug.LogError("Only 64 NetworkBehaviour components are allowed for NetworkIdentity: " + name + " because of the dirtyComponentMask"); + return; + } + ulong dirtyComponentsMask = GetDirtyMask(initialState); + + if (dirtyComponentsMask == 0L) + return; + + // calculate syncMode mask at runtime. this allows users to change + // component.syncMode while the game is running, which can be a huge + // advantage over syncvar-based sync modes. e.g. if a player decides + // to share or not share his inventory, or to go invisible, etc. + // + // (this also lets the TestSynchronizingObjects test pass because + // otherwise if we were to cache it in Awake, then we would call + // GetComponents before all the test behaviours + // were added) + ulong syncModeObserversMask = GetSyncModeObserversMask(); + + // write regular dirty mask for owner, + // writer 'dirty mask & syncMode==Everyone' for everyone else + // (WritePacked64 so we don't write full 8 bytes if we don't have to) + ownerWriter.WritePackedUInt64(dirtyComponentsMask); + observersWriter.WritePackedUInt64(dirtyComponentsMask & syncModeObserversMask); + + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // is this component dirty? + // -> always serialize if initialState so all components are included in spawn packet + // -> note: IsDirty() is false if the component isn't dirty or sendInterval isn't elapsed yet + if (initialState || comp.IsDirty()) + { + if (LogFilter.Debug) Debug.Log("OnSerializeAllSafely: " + name + " -> " + comp.GetType() + " initial=" + initialState); + + // serialize into ownerWriter first + // (owner always gets everything!) + int startPosition = ownerWriter.Position; + OnSerializeSafely(comp, ownerWriter, initialState); + ++ownerWritten; + + // copy into observersWriter too if SyncMode.Observers + // -> we copy instead of calling OnSerialize again because + // we don't know what magic the user does in OnSerialize. + // -> it's not guaranteed that calling it twice gets the + // same result + // -> it's not guaranteed that calling it twice doesn't mess + // with the user's OnSerialize timing code etc. + // => so we just copy the result without touching + // OnSerialize again + if (comp.syncMode == SyncMode.Observers) + { + ArraySegment segment = ownerWriter.ToArraySegment(); + int length = ownerWriter.Position - startPosition; + observersWriter.WriteBytes(segment.Array, startPosition, length); + ++observersWritten; + } + } + } + } + + internal ulong GetDirtyMask(bool initialState) + { + // loop through all components only once and then write dirty+payload into the writer afterwards + ulong dirtyComponentsMask = 0L; + NetworkBehaviour[] components = NetworkBehaviours; + for (int i = 0; i < components.Length; ++i) + { + NetworkBehaviour comp = components[i]; + if (initialState || comp.IsDirty()) + { + dirtyComponentsMask |= (ulong)(1L << i); + } + } + + return dirtyComponentsMask; + } + + // a mask that contains all the components with SyncMode.Observers + internal ulong GetSyncModeObserversMask() + { + // loop through all components + ulong mask = 0UL; + NetworkBehaviour[] components = NetworkBehaviours; + for (int i = 0; i < NetworkBehaviours.Length; ++i) + { + NetworkBehaviour comp = components[i]; + if (comp.syncMode == SyncMode.Observers) + { + mask |= 1UL << i; + } + } + + return mask; + } + + void OnDeserializeSafely(NetworkBehaviour comp, NetworkReader reader, bool initialState) + { + // read header as 4 bytes and calculate this chunk's start+end + int contentSize = reader.ReadInt32(); + int chunkStart = reader.Position; + int chunkEnd = reader.Position + contentSize; + + // call OnDeserialize and wrap it in a try-catch block so there's no + // way to mess up another component's deserialization + try + { + if (LogFilter.Debug) Debug.Log("OnDeserializeSafely: " + comp.name + " component=" + comp.GetType() + " sceneId=" + m_SceneId.ToString("X") + " length=" + contentSize); + comp.OnDeserialize(reader, initialState); + } + catch (Exception e) + { + // show a detailed error and let the user know what went wrong + Debug.LogError("OnDeserialize failed for: object=" + name + " component=" + comp.GetType() + " sceneId=" + m_SceneId.ToString("X") + " length=" + contentSize + ". Possible Reasons:\n * Do " + comp.GetType() + "'s OnSerialize and OnDeserialize calls write the same amount of data(" + contentSize +" bytes)? \n * Was there an exception in " + comp.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" + e); + } + + // now the reader should be EXACTLY at 'before + size'. + // otherwise the component read too much / too less data. + if (reader.Position != chunkEnd) + { + // warn the user + int bytesRead = reader.Position - chunkStart; + Debug.LogWarning("OnDeserialize was expected to read " + contentSize + " instead of " + bytesRead + " bytes for object:" + name + " component=" + comp.GetType() + " sceneId=" + m_SceneId.ToString("X") + ". Make sure that OnSerialize and OnDeserialize write/read the same amount of data in all cases."); + + // fix the position, so the following components don't all fail + reader.Position = chunkEnd; + } + } + + internal void OnDeserializeAllSafely(NetworkReader reader, bool initialState) + { + // read component dirty mask + ulong dirtyComponentsMask = reader.ReadPackedUInt64(); + + NetworkBehaviour[] components = NetworkBehaviours; + // loop through all components and deserialize the dirty ones + for (int i = 0; i < components.Length; ++i) + { + // is the dirty bit at position 'i' set to 1? + ulong dirtyBit = (ulong)(1L << i); + if ((dirtyComponentsMask & dirtyBit) != 0L) + { + OnDeserializeSafely(components[i], reader, initialState); + } + } + } + + // happens on client + internal void HandleClientAuthority(bool authority) + { + if (!localPlayerAuthority) + { + Debug.LogError("HandleClientAuthority " + gameObject + " does not have localPlayerAuthority"); + return; + } + + ForceAuthority(authority); + } + + // helper function to handle SyncEvent/Command/Rpc + void HandleRemoteCall(int componentIndex, int functionHash, MirrorInvokeType invokeType, NetworkReader reader) + { + if (gameObject == null) + { + Debug.LogWarning(invokeType + " [" + functionHash + "] received for deleted object [netId=" + netId + "]"); + return; + } + + // find the right component to invoke the function on + if (0 <= componentIndex && componentIndex < networkBehavioursCache.Length) + { + NetworkBehaviour invokeComponent = networkBehavioursCache[componentIndex]; + if (!invokeComponent.InvokeHandlerDelegate(functionHash, invokeType, reader)) + { + Debug.LogError("Found no receiver for incoming " + invokeType + " [" + functionHash + "] on " + gameObject + ", the server and client should have the same NetworkBehaviour instances [netId=" + netId + "]."); + } + } + else + { + Debug.LogWarning("Component [" + componentIndex + "] not found for [netId=" + netId + "]"); + } + } + + // happens on client + internal void HandleSyncEvent(int componentIndex, int eventHash, NetworkReader reader) + { + HandleRemoteCall(componentIndex, eventHash, MirrorInvokeType.SyncEvent, reader); + } + + // happens on server + internal void HandleCommand(int componentIndex, int cmdHash, NetworkReader reader) + { + HandleRemoteCall(componentIndex, cmdHash, MirrorInvokeType.Command, reader); + } + + // happens on client + internal void HandleRPC(int componentIndex, int rpcHash, NetworkReader reader) + { + HandleRemoteCall(componentIndex, rpcHash, MirrorInvokeType.ClientRpc, reader); + } + + internal void OnUpdateVars(NetworkReader reader, bool initialState) + { + OnDeserializeAllSafely(reader, initialState); + } + + internal void SetLocalPlayer() + { + isLocalPlayer = true; + + // there is an ordering issue here that originAuthority solves. OnStartAuthority should only be called if m_HasAuthority was false when this function began, + // or it will be called twice for this object. But that state is lost by the time OnStartAuthority is called below, so the original value is cached + // here to be checked below. + bool originAuthority = hasAuthority; + if (localPlayerAuthority) + { + hasAuthority = true; + } + + foreach (NetworkBehaviour comp in networkBehavioursCache) + { + comp.OnStartLocalPlayer(); + + if (localPlayerAuthority && !originAuthority) + { + comp.OnStartAuthority(); + } + } + } + + internal void OnNetworkDestroy() + { + for (int i = 0; networkBehavioursCache != null && i < networkBehavioursCache.Length; i++) + { + NetworkBehaviour comp = networkBehavioursCache[i]; + comp.OnNetworkDestroy(); + } + m_IsServer = false; + } + + internal void ClearObservers() + { + if (observers != null) + { + foreach (NetworkConnection conn in observers.Values) + { + conn.RemoveFromVisList(this, true); + } + observers.Clear(); + } + } + + internal void AddObserver(NetworkConnection conn) + { + if (observers == null) + { + Debug.LogError("AddObserver for " + gameObject + " observer list is null"); + return; + } + + 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; + } + + if (LogFilter.Debug) Debug.Log("Added observer " + conn.address + " added for " + gameObject); + + observers[conn.connectionId] = conn; + conn.AddToVisList(this); + } + + static readonly HashSet newObservers = new HashSet(); + + /// + /// This causes the set of players that can see this object to be rebuild. The OnRebuildObservers callback function will be invoked on each NetworkBehaviour. + /// + /// True if this is the first time. + public void RebuildObservers(bool initialize) + { + if (observers == null) + return; + + bool changed = false; + bool result = false; + + newObservers.Clear(); + + // call OnRebuildObservers function in components + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + result |= comp.OnRebuildObservers(newObservers, initialize); + } + + // if player connection: ensure player always see himself no matter what. + // -> 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 (connectionToClient != null && connectionToClient.isReady) + { + newObservers.Add(connectionToClient); + } + + // if no component implemented OnRebuildObservers, then add all + // connections. + if (!result) + { + if (initialize) + { + foreach (NetworkConnection conn in NetworkServer.connections.Values) + { + if (conn.isReady) + AddObserver(conn); + } + + if (NetworkServer.localConnection != null && NetworkServer.localConnection.isReady) + { + AddObserver(NetworkServer.localConnection); + } + } + return; + } + + // apply changes from rebuild + foreach (NetworkConnection conn in newObservers) + { + if (conn == null) + { + continue; + } + + if (!conn.isReady) + { + if (LogFilter.Debug) Debug.Log("Observer is not ready for " + gameObject + " " + conn); + continue; + } + + if (initialize || !observers.ContainsKey(conn.connectionId)) + { + // new observer + conn.AddToVisList(this); + if (LogFilter.Debug) Debug.Log("New Observer for " + gameObject + " " + conn); + changed = true; + } + } + + foreach (NetworkConnection conn in observers.Values) + { + if (!newObservers.Contains(conn)) + { + // removed observer + conn.RemoveFromVisList(this, false); + if (LogFilter.Debug) Debug.Log("Removed Observer for " + gameObject + " " + conn); + changed = true; + } + } + + // special case for local client. + if (initialize) + { + if (!newObservers.Contains(NetworkServer.localConnection)) + { + OnSetLocalVisibility(false); + } + } + + if (changed) + { + observers.Clear(); + foreach (NetworkConnection conn in newObservers) + { + if (conn.isReady) + observers.Add(conn.connectionId, conn); + } + } + } + + /// + /// Removes ownership for an object for a client by its connection. + /// This applies to objects that had authority set by AssignClientAuthority, or NetworkServer.SpawnWithClientAuthority. Authority cannot be removed for player objects. + /// + /// The connection of the client to remove authority for. + /// True if authority is removed. + public bool RemoveClientAuthority(NetworkConnection conn) + { + if (!isServer) + { + Debug.LogError("RemoveClientAuthority can only be call on the server for spawned objects."); + return false; + } + + if (connectionToClient != null) + { + Debug.LogError("RemoveClientAuthority cannot remove authority for a player object"); + return false; + } + + if (clientAuthorityOwner == null) + { + Debug.LogError("RemoveClientAuthority for " + gameObject + " has no clientAuthority owner."); + return false; + } + + if (clientAuthorityOwner != conn) + { + Debug.LogError("RemoveClientAuthority for " + gameObject + " has different owner."); + return false; + } + + clientAuthorityOwner.RemoveOwnedObject(this); + clientAuthorityOwner = null; + + // server now has authority (this is only called on server) + ForceAuthority(true); + + // send msg to that client + ClientAuthorityMessage msg = new ClientAuthorityMessage + { + netId = netId, + authority = false + }; + conn.Send(msg); + + clientAuthorityCallback?.Invoke(conn, this, false); + return true; + } + + /// + /// 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. Only NetworkIdentities with localPlayerAuthority set can have client authority assigned. This does not need to be called for player objects, as their authority is setup automatically. + /// + /// The connection of the client to assign authority to. + /// True if authority was assigned. + public bool AssignClientAuthority(NetworkConnection conn) + { + if (!isServer) + { + Debug.LogError("AssignClientAuthority can only be called on the server for spawned objects."); + return false; + } + if (!localPlayerAuthority) + { + Debug.LogError("AssignClientAuthority can only be used for NetworkIdentity components with LocalPlayerAuthority set."); + return false; + } + + if (clientAuthorityOwner != null && conn != clientAuthorityOwner) + { + Debug.LogError("AssignClientAuthority for " + gameObject + " already has an owner. Use RemoveClientAuthority() first."); + return false; + } + + if (conn == null) + { + Debug.LogError("AssignClientAuthority for " + gameObject + " owner cannot be null. Use RemoveClientAuthority() instead."); + return false; + } + + clientAuthorityOwner = conn; + clientAuthorityOwner.AddOwnedObject(this); + + // server no longer has authority (this is called on server). Note that local client could re-acquire authority below + ForceAuthority(false); + + // send msg to that client + ClientAuthorityMessage msg = new ClientAuthorityMessage + { + netId = netId, + authority = true + }; + conn.Send(msg); + + clientAuthorityCallback?.Invoke(conn, this, true); + return true; + } + + // 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 MarkForReset() => m_Reset = true; + + // if we have marked an identity for reset we do the actual reset. + internal void Reset() + { + if (!m_Reset) + return; + + m_Reset = false; + m_IsServer = false; + isClient = false; + hasAuthority = false; + + netId = 0; + isLocalPlayer = false; + connectionToServer = null; + connectionToClient = null; + networkBehavioursCache = null; + + ClearObservers(); + clientAuthorityOwner = null; + } + + // MirrorUpdate is a hot path. Caching the vars msg is really worth it to + // avoid large amounts of allocations. + static UpdateVarsMessage varsMessage = new UpdateVarsMessage(); + + // invoked by NetworkServer during Update() + internal void MirrorUpdate() + { + if (observers != null && observers.Count > 0) + { + // one writer for owner, one for observers + NetworkWriter ownerWriter = NetworkWriterPool.GetWriter(); + NetworkWriter observersWriter = NetworkWriterPool.GetWriter(); + + // serialize all the dirty components and send (if any were dirty) + OnSerializeAllSafely(false, ownerWriter, out int ownerWritten, observersWriter, out int observersWritten); + if (ownerWritten > 0 || observersWritten > 0) + { + // populate cached UpdateVarsMessage and send + varsMessage.netId = netId; + + // send ownerWriter to owner + // (only if we serialized anything for owner) + // (only if there is a connection (e.g. if not a monster), + // and if connection is ready because we use SendToReady + // below too) + if (ownerWritten > 0) + { + varsMessage.payload = ownerWriter.ToArraySegment(); + if (connectionToClient != null && connectionToClient.isReady) + NetworkServer.SendToClientOfPlayer(this, varsMessage); + } + + // send observersWriter to everyone but owner + // (only if we serialized anything for observers) + if (observersWritten > 0) + { + varsMessage.payload = observersWriter.ToArraySegment(); + NetworkServer.SendToReady(this, varsMessage, false); + } + + // only clear bits if we sent something + ClearDirtyBits(); + } + NetworkWriterPool.Recycle(ownerWriter); + NetworkWriterPool.Recycle(observersWriter); + } + else + { + ClearDirtyBits(); + } + } + + private void ClearDirtyBits() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + comp.ClearAllDirtyBits(); + } + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkIdentity.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkIdentity.cs.meta new file mode 100644 index 0000000..85a8007 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkIdentity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9b91ecbcc199f4492b9a91e820070131 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkManager.cs b/Assets/Packages/Mirror/Runtime/NetworkManager.cs new file mode 100644 index 0000000..53e4534 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkManager.cs @@ -0,0 +1,1102 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.SceneManagement; +using UnityEngine.Serialization; + +namespace Mirror +{ + /// + /// Enumeration of methods of where to spawn player objects in multiplayer games. + /// + public enum PlayerSpawnMethod + { + Random, + RoundRobin + } + + [AddComponentMenu("Network/NetworkManager")] + [HelpURL("https://mirror-networking.com/xmldocs/articles/Components/NetworkManager.html")] + public class NetworkManager : MonoBehaviour + { + [Header("Configuration")] + + /// + /// A flag to control whether the NetworkManager object is destroyed when the scene changes. + /// 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. + /// + [FormerlySerializedAs("m_DontDestroyOnLoad")] + public bool dontDestroyOnLoad = true; + + /// + /// Controls whether the program runs when it is in the background. + /// This is required when multiple instances of a program using networking are running on the same machine, such as when testing using localhost. But this is not recommended when deploying to mobile platforms. + /// + [FormerlySerializedAs("m_RunInBackground")] + public bool runInBackground = true; + + /// + /// Automatically invoke StartServer() + /// If the application is a Server Build or run with the -batchMode command line arguement, StartServer is automatically invoked. + /// + public bool startOnHeadless = true; + + /// + /// 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 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.")] + public int serverTickRate = 30; + + /// + /// Enables verbose debug messages in the console + /// + [FormerlySerializedAs("m_ShowDebugMessages")] + public bool showDebugMessages; + + /// + /// The scene to switch to when offline. + /// Setting this makes the NetworkManager do scene management. This scene will be switched to when a network session is completed - such as a client disconnect, or a server shutdown. + /// + [Scene] + [FormerlySerializedAs("m_OfflineScene")] + public string offlineScene = ""; + + /// + /// The scene to switch to when online. + /// Setting this makes the NetworkManager do scene management. This scene will be switched to when a network session is started - such as a client connect, or a server listen. + /// + [Scene] + [FormerlySerializedAs("m_OnlineScene")] + public string onlineScene = ""; + + [Header("Network Info")] + + // transport layer + [SerializeField] + protected Transport transport; + + /// + /// The network address currently in use. + /// For clients, this is the address of the server that is connected to. For servers, this is the local address. + /// + [FormerlySerializedAs("m_NetworkAddress")] + public string networkAddress = "localhost"; + + /// + /// The maximum number of concurrent network connections to support. + /// This effects the memory usage of the network layer. + /// + [FormerlySerializedAs("m_MaxConnections")] + public int maxConnections = 4; + + [Header("Spawn Info")] + + /// + /// 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. + /// + [FormerlySerializedAs("m_PlayerPrefab")] + public GameObject playerPrefab; + + /// + /// A flag to control whether or not player objects are automatically created on connect, and on scene change. + /// + [FormerlySerializedAs("m_AutoCreatePlayer")] + public bool autoCreatePlayer = true; + + /// + /// The current method of spawning players used by the NetworkManager. + /// + [FormerlySerializedAs("m_PlayerSpawnMethod")] + public PlayerSpawnMethod playerSpawnMethod; + + /// + /// List of prefabs that will be registered with the spawning system. + /// For each of these prefabs, ClientManager.RegisterPrefab() will be automatically invoke. + /// + [FormerlySerializedAs("m_SpawnPrefabs"), HideInInspector] + public List spawnPrefabs = new List(); + + /// + /// List of transforms populted by NetworkStartPosition components found in the scene. + /// + public static List startPositions = new List(); + + /// + /// This is 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. + /// + [NonSerialized] + public bool clientLoadedScene; + + /// + /// Number of active player objects across all connections on the server. + /// This is only valid on the host / server. + /// + public int numPlayers => NetworkServer.connections.Count(kv => kv.Value.playerController != null); + + /// + /// The name of the current network scene. + /// + /// + /// This is populated if the NetworkManager is doing scene management. This should not be changed directly. Calls to ServerChangeScene() cause this to change. New clients that connect to a server will automatically load this scene. + /// This is used to make sure that all scene changes are initialized by Mirror. + /// Loading a scene manually wont set networkSceneName, so Mirror would still load it again on start. + /// + public static string networkSceneName = ""; + + /// + /// True if the server or client is started and running + /// This is set True in StartServer / StartClient, and set False in StopServer / StopClient + /// + [NonSerialized] + public bool isNetworkActive; + + /// + /// Obsolete: Use directly + /// For example, use NetworkClient.Send(message) instead of NetworkManager.client.Send(message) + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkClient directly, it will be made static soon. For example, use NetworkClient.Send(message) instead of NetworkManager.client.Send(message)")] + public NetworkClient client => NetworkClient.singleton; + + static int startPositionIndex; + + /// + /// NetworkManager singleton + /// + public static NetworkManager singleton; + + static UnityEngine.AsyncOperation loadingSceneAsync; + static NetworkConnection clientReadyConnection; + + /// + /// virtual so that inheriting classes' Awake() can call base.Awake() too + /// + public virtual void Awake() + { + Debug.Log("Thank you for using Mirror! https://mirror-networking.com"); + + // Set the networkSceneName to prevent a scene reload + // if client connection to server fails. + networkSceneName = offlineScene; + + InitializeSingleton(); + + // setup OnSceneLoaded callback + SceneManager.sceneLoaded += OnSceneLoaded; + } + + /// + /// headless mode detection + /// + public static bool isHeadless => SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null; + + /// + /// Obsolete: Use instead. + /// This is a static property now. This method will be removed by summer 2019. + /// + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use isHeadless instead of IsHeadless()")] + public static bool IsHeadless() + { + return isHeadless; + } + + void InitializeSingleton() + { + if (singleton != null && singleton == this) + { + return; + } + + // do this early + LogFilter.Debug = showDebugMessages; + + 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; + } + if (LogFilter.Debug) Debug.Log("NetworkManager created singleton (DontDestroyOnLoad)"); + singleton = this; + if (Application.isPlaying) DontDestroyOnLoad(gameObject); + } + else + { + if (LogFilter.Debug) Debug.Log("NetworkManager created singleton (ForScene)"); + singleton = this; + } + + // set active transport AFTER setting singleton. + // so only if we didn't destroy ourselves. + Transport.activeTransport = transport; + } + + /// + /// virtual so that inheriting classes' Start() can call base.Start() too + /// + public virtual void Start() + { + // headless mode? then start the server + // can't do this in Awake because Awake is for initialization. + // some transports might not be ready until Start. + // + // (tick rate is applied in StartServer!) + if (isHeadless && startOnHeadless) + { + StartServer(); + } + } + + // support additive scene loads: + // NetworkScenePostProcess disables all scene objects on load, and + // * NetworkServer.SpawnObjects enables them again on the server when + // calling OnStartServer + // * ClientScene.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) + { + ClientScene.PrepareToSpawnSceneObjects(); + Debug.Log("Rebuild Client spawnableObjects after additive scene load: " + scene.name); + } + } + } + + // NetworkIdentity.UNetStaticUpdate is called from UnityEngine while LLAPI network is active. + // If we want TCP then we need to call it manually. Probably best from NetworkManager, although this means that we can't use NetworkServer/NetworkClient without a NetworkManager invoking Update anymore. + /// + /// virtual so that inheriting classes' LateUpdate() can call base.LateUpdate() too + /// + public virtual void LateUpdate() + { + // call it while the NetworkManager exists. + // -> we don't only call while Client/Server.Connected, because then we would stop if disconnected and the + // NetworkClient wouldn't receive the last Disconnect event, result in all kinds of issues + NetworkServer.Update(); + NetworkClient.Update(); + UpdateScene(); + } + + /// + /// 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(); + print("OnApplicationQuit: stopped client"); + } + + // stop server after stopping client (for proper host mode stopping) + if (NetworkServer.active) + { + StopServer(); + print("OnApplicationQuit: stopped server"); + } + + // 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) + Transport.activeTransport.Shutdown(); + } + + /// + /// virtual so that inheriting classes' OnValidate() can call base.OnValidate() too + /// + public virtual void OnValidate() + { + // add transport if there is none yet. makes upgrading easier. + if (transport == null) + { + // was a transport added yet? if not, add one + transport = GetComponent(); + if (transport == null) + { + transport = gameObject.AddComponent(); + Debug.Log("NetworkManager: added default Transport because there was none yet."); + } +#if UNITY_EDITOR + UnityEditor.EditorUtility.SetDirty(gameObject); +#endif + } + + maxConnections = Mathf.Max(maxConnections, 0); // always >= 0 + + if (playerPrefab != null && playerPrefab.GetComponent() == null) + { + Debug.LogError("NetworkManager - playerPrefab must have a NetworkIdentity."); + playerPrefab = null; + } + } + + void RegisterServerMessages() + { + NetworkServer.RegisterHandler(OnServerConnectInternal); + NetworkServer.RegisterHandler(OnServerDisconnectInternal); + NetworkServer.RegisterHandler(OnServerReadyMessageInternal); + NetworkServer.RegisterHandler(OnServerAddPlayerInternal); + NetworkServer.RegisterHandler(OnServerRemovePlayerMessageInternal); + NetworkServer.RegisterHandler(OnServerErrorInternal); + } + + /// + /// Set the frame rate for a headless server. + /// Override if you wish to disable the behavior or set your own tick rate. + /// + public virtual void ConfigureServerFrameRate() + { + // set a fixed tick rate instead of updating as often as possible + // * if not in Editor (it doesn't work in the Editor) + // * if not in Host mode +#if !UNITY_EDITOR + if (!NetworkClient.active && isHeadless) + { + Application.targetFrameRate = serverTickRate; + Debug.Log("Server Tick Rate set to: " + Application.targetFrameRate + " Hz."); + } +#endif + } + + /// + /// This starts a new server. + /// This uses the networkPort property as the listen port. + /// + /// + public bool StartServer() + { + InitializeSingleton(); + + if (runInBackground) + Application.runInBackground = true; + + ConfigureServerFrameRate(); + + if (!NetworkServer.Listen(maxConnections)) + { + Debug.LogError("StartServer listen failed."); + return false; + } + + // 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(); + + // this must be after Listen(), since that registers the default message handlers + RegisterServerMessages(); + + if (LogFilter.Debug) Debug.Log("NetworkManager StartServer"); + isNetworkActive = true; + + // Only change scene if the requested online scene is not blank, and is not already loaded + string loadedSceneName = SceneManager.GetActiveScene().name; + if (!string.IsNullOrEmpty(onlineScene) && onlineScene != loadedSceneName && onlineScene != offlineScene) + { + ServerChangeScene(onlineScene); + } + else + { + NetworkServer.SpawnObjects(); + } + return true; + } + + void RegisterClientMessages() + { + NetworkClient.RegisterHandler(OnClientConnectInternal); + NetworkClient.RegisterHandler(OnClientDisconnectInternal); + NetworkClient.RegisterHandler(OnClientNotReadyMessageInternal); + NetworkClient.RegisterHandler(OnClientErrorInternal); + NetworkClient.RegisterHandler(OnClientSceneInternal); + + if (playerPrefab != null) + { + ClientScene.RegisterPrefab(playerPrefab); + } + for (int i = 0; i < spawnPrefabs.Count; i++) + { + GameObject prefab = spawnPrefabs[i]; + if (prefab != null) + { + ClientScene.RegisterPrefab(prefab); + } + } + } + + /// + /// This starts a network client. It uses the networkAddress and networkPort properties as the address to connect to. + /// This makes the newly created client connect to the server immediately. + /// + public void StartClient() + { + InitializeSingleton(); + + if (runInBackground) + Application.runInBackground = true; + + isNetworkActive = true; + + RegisterClientMessages(); + + if (string.IsNullOrEmpty(networkAddress)) + { + Debug.LogError("Must set the Network Address field in the manager"); + return; + } + if (LogFilter.Debug) Debug.Log("NetworkManager StartClient address:" + networkAddress); + + NetworkClient.Connect(networkAddress); + + OnStartClient(); + } + + /// + /// This starts a network "host" - a server and client in the same application. + /// The client returned from StartHost() is a special "local" client that communicates to the in-process server using a message queue instead of the real network. But in almost all other cases, it can be treated as a normal client. + /// + public virtual void StartHost() + { + OnStartHost(); + if (StartServer()) + { + ConnectLocalClient(); + OnStartClient(); + } + } + + void ConnectLocalClient() + { + if (LogFilter.Debug) Debug.Log("NetworkManager StartHost"); + networkAddress = "localhost"; + NetworkServer.ActivateLocalClientScene(); + NetworkClient.ConnectLocalServer(); + RegisterClientMessages(); + } + + /// + /// This stops both the client and the server that the manager is using. + /// + public void StopHost() + { + OnStopHost(); + + StopServer(); + StopClient(); + } + + /// + /// Stops the server that the manager is using. + /// + public void StopServer() + { + if (!NetworkServer.active) + return; + + OnStopServer(); + + if (LogFilter.Debug) Debug.Log("NetworkManager StopServer"); + isNetworkActive = false; + NetworkServer.Shutdown(); + if (!string.IsNullOrEmpty(offlineScene)) + { + ServerChangeScene(offlineScene); + } + CleanupNetworkIdentities(); + } + + /// + /// Stops the client that the manager is using. + /// + public void StopClient() + { + OnStopClient(); + + if (LogFilter.Debug) Debug.Log("NetworkManager StopClient"); + isNetworkActive = false; + + // shutdown client + NetworkClient.Disconnect(); + NetworkClient.Shutdown(); + + if (!string.IsNullOrEmpty(offlineScene)) + { + ClientChangeScene(offlineScene, LoadSceneMode.Single, LocalPhysicsMode.None); + } + CleanupNetworkIdentities(); + } + + /// + /// 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. + /// + /// + public virtual void ServerChangeScene(string newSceneName) + { + ServerChangeScene(newSceneName, LoadSceneMode.Single, LocalPhysicsMode.None); + } + + /// + /// 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. + /// + /// + /// + /// + public virtual void ServerChangeScene(string newSceneName, LoadSceneMode sceneMode, LocalPhysicsMode physicsMode) + { + if (string.IsNullOrEmpty(newSceneName)) + { + Debug.LogError("ServerChangeScene empty scene name"); + return; + } + + if (LogFilter.Debug) Debug.Log("ServerChangeScene " + newSceneName); + NetworkServer.SetAllClientsNotReady(); + networkSceneName = newSceneName; + + // Let server prepare for scene change + OnServerChangeScene(newSceneName); + + LoadSceneParameters loadSceneParameters = new LoadSceneParameters(sceneMode, physicsMode); + + loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName, loadSceneParameters); + + SceneMessage msg = new SceneMessage() + { + sceneName = newSceneName, + sceneMode = loadSceneParameters.loadSceneMode, + physicsMode = loadSceneParameters.localPhysicsMode + }; + + NetworkServer.SendToAll(msg); + + startPositionIndex = 0; + startPositions.Clear(); + } + + void CleanupNetworkIdentities() + { + foreach (NetworkIdentity identity in Resources.FindObjectsOfTypeAll()) + { + identity.MarkForReset(); + } + } + + internal void ClientChangeScene(string newSceneName, LoadSceneMode sceneMode, LocalPhysicsMode physicsMode) + { + if (string.IsNullOrEmpty(newSceneName)) + { + Debug.LogError("ClientChangeScene empty scene name"); + return; + } + + if (LogFilter.Debug) Debug.Log("ClientChangeScene newSceneName:" + newSceneName + " networkSceneName:" + networkSceneName); + + // vis2k: pause message handling while loading scene. otherwise we will 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.) + if (LogFilter.Debug) Debug.Log("ClientChangeScene: pausing handlers while scene is loading to avoid data loss after scene was loaded."); + Transport.activeTransport.enabled = false; + + // Let client prepare for scene change + OnClientChangeScene(newSceneName); + + loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName, new LoadSceneParameters() + { + loadSceneMode = sceneMode, + localPhysicsMode = physicsMode, + }); + networkSceneName = newSceneName; //This should probably not change if additive is used + } + + 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 + if (LogFilter.Debug) Debug.Log("FinishLoadScene: resuming handlers after scene was loading."); + Transport.activeTransport.enabled = true; + + if (clientReadyConnection != null) + { + clientLoadedScene = true; + OnClientConnect(clientReadyConnection); + clientReadyConnection = null; + } + + if (NetworkServer.active) + { + NetworkServer.SpawnObjects(); + OnServerSceneChanged(networkSceneName); + } + + if (NetworkClient.isConnected) + { + RegisterClientMessages(); + OnClientSceneChanged(NetworkClient.connection); + } + } + + static void UpdateScene() + { + if (singleton != null && loadingSceneAsync != null && loadingSceneAsync.isDone) + { + if (LogFilter.Debug) Debug.Log("ClientChangeScene done readyCon:" + clientReadyConnection); + singleton.FinishLoadScene(); + loadingSceneAsync.allowSceneActivation = true; + loadingSceneAsync = null; + } + } + + /// + /// virtual so that inheriting classes' OnDestroy() can call base.OnDestroy() too + /// + public virtual void OnDestroy() + { + if (LogFilter.Debug) Debug.Log("NetworkManager destroyed"); + } + + /// + /// 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. + public static void RegisterStartPosition(Transform start) + { + if (LogFilter.Debug) 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(); + } + + /// + /// Unregisters the transform of a game object as a player spawn location. + /// This is done automatically by the NetworkStartPosition component, but can be done manually from user code. + /// + /// Transform to unregister. + public static void UnRegisterStartPosition(Transform start) + { + if (LogFilter.Debug) Debug.Log("UnRegisterStartPosition: (" + start.gameObject.name + ") " + start.position); + startPositions.Remove(start); + } + + /// + /// Obsolete: Use instead + /// + /// Returns True if NetworkClient.isConnected + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkClient.isConnected instead")] + public bool IsClientConnected() + { + return NetworkClient.isConnected; + } + + /// + /// This is the only way to clear the singleton, so another instance can be created. + /// + public static void Shutdown() + { + if (singleton == null) + return; + + startPositions.Clear(); + startPositionIndex = 0; + clientReadyConnection = null; + + singleton.StopHost(); + singleton = null; + } + + #region Server Internal Message Handlers + + void OnServerConnectInternal(NetworkConnection conn, ConnectMessage connectMsg) + { + if (LogFilter.Debug) Debug.Log("NetworkManager.OnServerConnectInternal"); + + if (networkSceneName != "" && networkSceneName != offlineScene) + { + SceneMessage msg = new SceneMessage() { sceneName = networkSceneName }; + conn.Send(msg); + } + + OnServerConnect(conn); + } + + void OnServerDisconnectInternal(NetworkConnection conn, DisconnectMessage msg) + { + if (LogFilter.Debug) Debug.Log("NetworkManager.OnServerDisconnectInternal"); + OnServerDisconnect(conn); + } + + void OnServerReadyMessageInternal(NetworkConnection conn, ReadyMessage msg) + { + if (LogFilter.Debug) Debug.Log("NetworkManager.OnServerReadyMessageInternal"); + OnServerReady(conn); + } + + void OnServerAddPlayerInternal(NetworkConnection conn, AddPlayerMessage extraMessage) + { + if (LogFilter.Debug) 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.GetComponent() == null) + { + Debug.LogError("The PlayerPrefab does not have a NetworkIdentity. Please add a NetworkIdentity to the player prefab."); + return; + } + + if (conn.playerController != null) + { + Debug.LogError("There is already a player for this connection."); + return; + } + + OnServerAddPlayer(conn, extraMessage); + } + + void OnServerRemovePlayerMessageInternal(NetworkConnection conn, RemovePlayerMessage msg) + { + if (LogFilter.Debug) Debug.Log("NetworkManager.OnServerRemovePlayerMessageInternal"); + + if (conn.playerController != null) + { + OnServerRemovePlayer(conn, conn.playerController); + conn.playerController = null; + } + } + + void OnServerErrorInternal(NetworkConnection conn, ErrorMessage msg) + { + if (LogFilter.Debug) Debug.Log("NetworkManager.OnServerErrorInternal"); + OnServerError(conn, msg.value); + } + + #endregion + + #region Client Internal Message Handlers + + void OnClientConnectInternal(NetworkConnection conn, ConnectMessage message) + { + if (LogFilter.Debug) Debug.Log("NetworkManager.OnClientConnectInternal"); + + string loadedSceneName = SceneManager.GetActiveScene().name; + if (string.IsNullOrEmpty(onlineScene) || onlineScene == offlineScene || loadedSceneName == onlineScene) + { + clientLoadedScene = false; + OnClientConnect(conn); + } + else + { + // will wait for scene id to come from the server. + clientReadyConnection = conn; + } + } + + void OnClientDisconnectInternal(NetworkConnection conn, DisconnectMessage msg) + { + if (LogFilter.Debug) Debug.Log("NetworkManager.OnClientDisconnectInternal"); + OnClientDisconnect(conn); + } + + void OnClientNotReadyMessageInternal(NetworkConnection conn, NotReadyMessage msg) + { + if (LogFilter.Debug) Debug.Log("NetworkManager.OnClientNotReadyMessageInternal"); + + ClientScene.ready = false; + OnClientNotReady(conn); + + // NOTE: clientReadyConnection is not set here! don't want OnClientConnect to be invoked again after scene changes. + } + + void OnClientErrorInternal(NetworkConnection conn, ErrorMessage msg) + { + if (LogFilter.Debug) Debug.Log("NetworkManager:OnClientErrorInternal"); + OnClientError(conn, msg.value); + } + + void OnClientSceneInternal(NetworkConnection conn, SceneMessage msg) + { + if (LogFilter.Debug) Debug.Log("NetworkManager.OnClientSceneInternal"); + + if (NetworkClient.isConnected && !NetworkServer.active) + { + ClientChangeScene(msg.sceneName, msg.sceneMode, msg.physicsMode); + } + } + + #endregion + + #region Server System Callbacks + + /// + /// Called on the server when a new client connects. + /// 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 virtual void OnServerConnect(NetworkConnection conn) { } + + /// + /// Called on the server when a client disconnects. + /// 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 virtual void OnServerDisconnect(NetworkConnection conn) + { + NetworkServer.DestroyPlayerForConnection(conn); + if (LogFilter.Debug) Debug.Log("OnServerDisconnect: Client disconnected."); + } + + /// + /// 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 virtual void OnServerReady(NetworkConnection conn) + { + if (conn.playerController == null) + { + // this is now allowed (was not for a while) + if (LogFilter.Debug) Debug.Log("Ready with no player object"); + } + NetworkServer.SetClientReady(conn); + } + + /// + /// 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. + /// + /// Connection from client. + /// An extra message object passed for the new player. + public virtual void OnServerAddPlayer(NetworkConnection conn, AddPlayerMessage extraMessage) + { + Transform startPos = GetStartPosition(); + GameObject player = startPos != null + ? Instantiate(playerPrefab, startPos.position, startPos.rotation) + : Instantiate(playerPrefab); + + NetworkServer.AddPlayerForConnection(conn, player); + } + + /// + /// This finds a spawn position based on NetworkStartPosition objects in the scene. + /// This is used by the default implementation of OnServerAddPlayer. + /// + /// Returns the transform to spawn a player at, or null. + public 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; + } + } + + /// + /// Called on the server when a client removes a player. + /// The default implementation of this function destroys the corresponding player object. + /// + /// The connection to remove the player from. + /// The player controller to remove. + public virtual void OnServerRemovePlayer(NetworkConnection conn, NetworkIdentity player) + { + if (player.gameObject != null) + { + NetworkServer.Destroy(player.gameObject); + } + } + + /// + /// Called on the server when a network error occurs for a client connection. + /// + /// Connection from client. + /// Error code. + public virtual void OnServerError(NetworkConnection conn, int errorCode) { } + + /// + /// Called from ServerChangeScene immediately before SceneManager.LoadSceneAsync is executed + /// This allows server to do work / cleanup / prep before the scene changes. + /// + /// Name of the scene that's about to be loaded + public virtual void OnServerChangeScene(string newSceneName) { } + + /// + /// Called on the server when a scene is completed loaded, when the scene load was initiated by the server with ServerChangeScene(). + /// + /// The name of the new scene. + public virtual void OnServerSceneChanged(string sceneName) { } + + #endregion + + #region Client System Callbacks + + /// + /// 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. + /// + /// + public virtual void OnClientConnect(NetworkConnection conn) + { + if (!clientLoadedScene) + { + // Ready/AddPlayer is usually triggered by a scene load completing. if no scene was loaded, then Ready/AddPlayer it here instead. + if (!ClientScene.ready) ClientScene.Ready(conn); + if (autoCreatePlayer) + { + ClientScene.AddPlayer(); + } + } + } + + /// + /// 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 virtual void OnClientDisconnect(NetworkConnection conn) + { + StopClient(); + } + + /// + /// Called on clients when a network error occurs. + /// + /// Connection to a server. + /// Error code. + public virtual void OnClientError(NetworkConnection conn, int errorCode) { } + + /// + /// Called on clients when a servers tells the client it is no longer ready. + /// This is commonly used when switching scenes. + /// + /// Connection to a server. + public virtual void OnClientNotReady(NetworkConnection conn) { } + + /// + /// Called from ClientChangeScene immediately before SceneManager.LoadSceneAsync is executed + /// This allows client to do work / cleanup / prep before the scene changes. + /// + /// Name of the scene that's about to be loaded + public virtual void OnClientChangeScene(string newSceneName) { } + + /// + /// 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. + /// + /// The network connection that the scene change message arrived on. + public virtual void OnClientSceneChanged(NetworkConnection conn) + { + // always become ready. + if (!ClientScene.ready) ClientScene.Ready(conn); + + if (autoCreatePlayer && ClientScene.localPlayer == null) + { + // add player if existing one is null + ClientScene.AddPlayer(); + } + } + + #endregion + + #region Start & Stop callbacks + + // 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. + /// StartHost has multiple signatures, but they all cause this hook to be called. + /// + public virtual void OnStartHost() { } + + /// + /// This is invoked when a server is started - including when a host is started. + /// StartServer has multiple signatures, but they all cause this hook to be called. + /// + public virtual void OnStartServer() { } + + /// + /// Obsolete: Use instead of OnStartClient(NetworkClient client). + /// All NetworkClient functions are static now, so you can use NetworkClient.Send(message) instead of client.Send(message) directly now. + /// + /// The NetworkClient object that was started. + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use OnStartClient() instead of OnStartClient(NetworkClient client). All NetworkClient functions are static now, so you can use NetworkClient.Send(message) instead of client.Send(message) directly now.")] + public virtual void OnStartClient(NetworkClient client) { } + + /// + /// This is invoked when the client is started. + /// + public virtual void OnStartClient() + { +#pragma warning disable CS0618 // Type or member is obsolete + OnStartClient(NetworkClient.singleton); +#pragma warning restore CS0618 // Type or member is obsolete + } + + /// + /// 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() { } + + #endregion + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkManager.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkManager.cs.meta new file mode 100644 index 0000000..3ca7c55 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8aab4c8111b7c411b9b92cf3dbc5bd4e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkManagerHUD.cs b/Assets/Packages/Mirror/Runtime/NetworkManagerHUD.cs new file mode 100644 index 0000000..dab55d8 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkManagerHUD.cs @@ -0,0 +1,128 @@ +// vis2k: GUILayout instead of spacey += ...; removed Update hotkeys to avoid +// confusion if someone accidentally presses one. +using System.ComponentModel; +using UnityEngine; + +namespace Mirror +{ + /// + /// An extension for the NetworkManager that displays a default HUD for controlling the network state of the game. + /// This component also shows useful internal state for the networking system in the inspector window of the editor. It allows users to view connections, networked objects, message handlers, and packet statistics. This information can be helpful when debugging networked games. + /// + [AddComponentMenu("Network/NetworkManagerHUD")] + [RequireComponent(typeof(NetworkManager))] + [EditorBrowsable(EditorBrowsableState.Never)] + [HelpURL("https://mirror-networking.com/xmldocs/articles/Components/NetworkManagerHUD.html")] + public class NetworkManagerHUD : MonoBehaviour + { + NetworkManager manager; + + /// + /// Whether to show the default control HUD at runtime. + /// + public bool showGUI = true; + + /// + /// The horizontal offset in pixels to draw the HUD runtime GUI at. + /// + public int offsetX; + + /// + /// The vertical offset in pixels to draw the HUD runtime GUI at. + /// + public int offsetY; + + void Awake() + { + manager = GetComponent(); + } + + void OnGUI() + { + if (!showGUI) + return; + + GUILayout.BeginArea(new Rect(10 + offsetX, 40 + offsetY, 215, 9999)); + if (!NetworkClient.isConnected && !NetworkServer.active) + { + if (!NetworkClient.active) + { + // LAN Host + if (Application.platform != RuntimePlatform.WebGLPlayer) + { + if (GUILayout.Button("LAN Host")) + { + manager.StartHost(); + } + } + + // LAN Client + IP + GUILayout.BeginHorizontal(); + if (GUILayout.Button("LAN Client")) + { + manager.StartClient(); + } + manager.networkAddress = GUILayout.TextField(manager.networkAddress); + GUILayout.EndHorizontal(); + + // LAN Server Only + if (Application.platform == RuntimePlatform.WebGLPlayer) + { + // cant be a server in webgl build + GUILayout.Box("( WebGL cannot be server )"); + } + else + { + if (GUILayout.Button("LAN Server Only")) manager.StartServer(); + } + } + else + { + // Connecting + GUILayout.Label("Connecting to " + manager.networkAddress + ".."); + if (GUILayout.Button("Cancel Connection Attempt")) + { + manager.StopClient(); + } + } + } + else + { + // server / client status message + if (NetworkServer.active) + { + GUILayout.Label("Server: active. Transport: " + Transport.activeTransport); + } + if (NetworkClient.isConnected) + { + GUILayout.Label("Client: address=" + manager.networkAddress); + } + } + + // client ready + if (NetworkClient.isConnected && !ClientScene.ready) + { + if (GUILayout.Button("Client Ready")) + { + ClientScene.Ready(NetworkClient.connection); + + if (ClientScene.localPlayer == null) + { + ClientScene.AddPlayer(); + } + } + } + + // stop + if (NetworkServer.active || NetworkClient.isConnected) + { + if (GUILayout.Button("Stop")) + { + manager.StopHost(); + } + } + + GUILayout.EndArea(); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkManagerHUD.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkManagerHUD.cs.meta new file mode 100644 index 0000000..fa08c3d --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkManagerHUD.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6442dc8070ceb41f094e44de0bf87274 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkMessage.cs b/Assets/Packages/Mirror/Runtime/NetworkMessage.cs new file mode 100644 index 0000000..9e9613c --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkMessage.cs @@ -0,0 +1,25 @@ +namespace Mirror +{ + public struct NetworkMessage + { + public int msgType; + public NetworkConnection conn; + public NetworkReader reader; + + public TMsg ReadMessage() where TMsg : IMessageBase, new() + { + // Normally I would just do: + // TMsg msg = new TMsg(); + // but mono calls an expensive method Activator.CreateInstance + // For value types this is unnecesary, just use the default value + TMsg msg = typeof(TMsg).IsValueType ? default(TMsg) : new TMsg(); + msg.Deserialize(reader); + return msg; + } + + public void ReadMessage(TMsg msg) where TMsg : IMessageBase + { + msg.Deserialize(reader); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkMessage.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkMessage.cs.meta new file mode 100644 index 0000000..370b0a6 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eb04e4848a2e4452aa2dbd7adb801c51 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkReader.cs b/Assets/Packages/Mirror/Runtime/NetworkReader.cs new file mode 100644 index 0000000..7df6ad4 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkReader.cs @@ -0,0 +1,355 @@ +// Custom NetworkReader that doesn't use C#'s built in MemoryStream in order to +// avoid allocations. +// +// Benchmark: 100kb byte[] passed to NetworkReader constructor 1000x +// before with MemoryStream +// 0.8% CPU time, 250KB memory, 3.82ms +// now: +// 0.0% CPU time, 32KB memory, 0.02ms +using System; +using System.IO; +using System.Text; +using UnityEngine; + +namespace Mirror +{ + // 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. + public class NetworkReader + { + // internal buffer + // byte[] pointer would work, but we use ArraySegment to also support + // the ArraySegment constructor + ArraySegment 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; + public int Length => buffer.Count; + + + public NetworkReader(byte[] bytes) + { + buffer = new ArraySegment(bytes); + } + + public NetworkReader(ArraySegment segment) + { + buffer = segment; + } + + public byte ReadByte() + { + if (Position + 1 > buffer.Count) + { + throw new EndOfStreamException("ReadByte out of range:" + ToString()); + } + return buffer.Array[buffer.Offset + Position++]; + } + public int ReadInt32() => (int)ReadUInt32(); + public uint ReadUInt32() + { + uint value = 0; + value |= ReadByte(); + value |= (uint)(ReadByte() << 8); + value |= (uint)(ReadByte() << 16); + value |= (uint)(ReadByte() << 24); + return value; + } + public long ReadInt64() => (long)ReadUInt64(); + public ulong ReadUInt64() + { + ulong value = 0; + value |= ReadByte(); + value |= ((ulong)ReadByte()) << 8; + value |= ((ulong)ReadByte()) << 16; + value |= ((ulong)ReadByte()) << 24; + value |= ((ulong)ReadByte()) << 32; + value |= ((ulong)ReadByte()) << 40; + value |= ((ulong)ReadByte()) << 48; + value |= ((ulong)ReadByte()) << 56; + return value; + } + + // read bytes into the passed buffer + public byte[] ReadBytes(byte[] bytes, int count) + { + // 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); + } + + ArraySegment data = ReadBytesSegment(count); + Array.Copy(data.Array, data.Offset, bytes, 0, count); + return bytes; + } + + // useful to parse payloads etc. without allocating + public ArraySegment ReadBytesSegment(int count) + { + // check if within buffer limits + if (Position + count > buffer.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; + } + + public override string ToString() + { + return "NetworkReader pos=" + Position + " len=" + Length + " buffer=" + BitConverter.ToString(buffer.Array, buffer.Offset, buffer.Count); + } + } + + // Mirror's Weaver automatically detects all NetworkReader function types, + // but they do all need to be extensions. + public static class NetworkReaderExtensions + { + // cache encoding instead of creating it each time + // 1000 readers before: 1MB GC, 30ms + // 1000 readers after: 0.8MB GC, 18ms + static readonly UTF8Encoding encoding = new UTF8Encoding(false, true); + + public static byte ReadByte(this NetworkReader reader) => reader.ReadByte(); + public static sbyte ReadSByte(this NetworkReader reader) => (sbyte)reader.ReadByte(); + public static char ReadChar(this NetworkReader reader) => (char)reader.ReadUInt16(); + public static bool ReadBoolean(this NetworkReader reader) => reader.ReadByte() != 0; + public static short ReadInt16(this NetworkReader reader) => (short)reader.ReadUInt16(); + public static ushort ReadUInt16(this NetworkReader reader) + { + ushort value = 0; + value |= reader.ReadByte(); + value |= (ushort)(reader.ReadByte() << 8); + return value; + } + public static int ReadInt32(this NetworkReader reader) => (int)reader.ReadUInt32(); + public static uint ReadUInt32(this NetworkReader reader) + { + uint value = 0; + value |= reader.ReadByte(); + value |= (uint)(reader.ReadByte() << 8); + value |= (uint)(reader.ReadByte() << 16); + value |= (uint)(reader.ReadByte() << 24); + return value; + } + public static long ReadInt64(this NetworkReader reader) => (long)reader.ReadUInt64(); + public static ulong ReadUInt64(this NetworkReader reader) + { + ulong value = 0; + value |= reader.ReadByte(); + value |= ((ulong)reader.ReadByte()) << 8; + value |= ((ulong)reader.ReadByte()) << 16; + value |= ((ulong)reader.ReadByte()) << 24; + value |= ((ulong)reader.ReadByte()) << 32; + value |= ((ulong)reader.ReadByte()) << 40; + value |= ((ulong)reader.ReadByte()) << 48; + value |= ((ulong)reader.ReadByte()) << 56; + return value; + } + public static float ReadSingle(this NetworkReader reader) + { + UIntFloat converter = new UIntFloat(); + converter.intValue = reader.ReadUInt32(); + return converter.floatValue; + } + public static double ReadDouble(this NetworkReader reader) + { + UIntDouble converter = new UIntDouble(); + converter.longValue = reader.ReadUInt64(); + return converter.doubleValue; + } + public static decimal ReadDecimal(this NetworkReader reader) + { + UIntDecimal converter = new UIntDecimal(); + converter.longValue1 = reader.ReadUInt64(); + converter.longValue2 = reader.ReadUInt64(); + return converter.decimalValue; + } + + // note: this will throw an ArgumentException if an invalid utf8 string is sent + // null support, see NetworkWriter + public static string ReadString(this NetworkReader reader) + { + // read number of bytes + ushort size = reader.ReadUInt16(); + + if (size == 0) + return null; + + int realSize = size - 1; + + // make sure it's within limits to avoid allocation attacks etc. + if (realSize >= NetworkWriter.MaxStringLength) + { + throw new EndOfStreamException("ReadString too long: " + realSize + ". Limit is: " + NetworkWriter.MaxStringLength); + } + + ArraySegment data = reader.ReadBytesSegment(realSize); + + // convert directly from buffer to string via encoding + return encoding.GetString(data.Array, data.Offset, data.Count); + } + + // Use checked() to force it to throw OverflowException if data is invalid + // null support, see NetworkWriter + 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.ReadPackedUInt32(); + return count == 0 ? null : reader.ReadBytes(checked((int)(count - 1u))); + } + + public static ArraySegment ReadBytesAndSizeSegment(this NetworkReader reader) + { + // count = 0 means the array was null + // otherwise count - 1 is the length of the array + uint count = reader.ReadPackedUInt32(); + return count == 0 ? default : reader.ReadBytesSegment(checked((int)(count - 1u))); + } + + // zigzag decoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba + public static int ReadPackedInt32(this NetworkReader reader) + { + uint data = reader.ReadPackedUInt32(); + return (int)((data >> 1) ^ -(data & 1)); + } + + // http://sqlite.org/src4/doc/trunk/www/varint.wiki + // NOTE: big endian. + // Use checked() to force it to throw OverflowException if data is invalid + public static uint ReadPackedUInt32(this NetworkReader reader) => checked((uint)reader.ReadPackedUInt64()); + + // zigzag decoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba + public static long ReadPackedInt64(this NetworkReader reader) + { + ulong data = reader.ReadPackedUInt64(); + return ((long)(data >> 1)) ^ -((long)data & 1); + } + + public static ulong ReadPackedUInt64(this NetworkReader reader) + { + byte a0 = reader.ReadByte(); + if (a0 < 241) + { + return a0; + } + + byte a1 = reader.ReadByte(); + if (a0 >= 241 && 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("ReadPackedUInt64() failure: " + a0); + } + + public static Vector2 ReadVector2(this NetworkReader reader) => new Vector2(reader.ReadSingle(), reader.ReadSingle()); + public static Vector3 ReadVector3(this NetworkReader reader) => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + public static Vector4 ReadVector4(this NetworkReader reader) => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + public static Vector2Int ReadVector2Int(this NetworkReader reader) => new Vector2Int(reader.ReadPackedInt32(), reader.ReadPackedInt32()); + public static Vector3Int ReadVector3Int(this NetworkReader reader) => new Vector3Int(reader.ReadPackedInt32(), reader.ReadPackedInt32(), reader.ReadPackedInt32()); + public static Color ReadColor(this NetworkReader reader) => new Color(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + public static Color32 ReadColor32(this NetworkReader reader) => new Color32(reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), reader.ReadByte()); + public static Quaternion ReadQuaternion(this NetworkReader reader) => new Quaternion(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + public static Rect ReadRect(this NetworkReader reader) => new Rect(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + public static Plane ReadPlane(this NetworkReader reader) => new Plane(reader.ReadVector3(), reader.ReadSingle()); + public static Ray ReadRay(this NetworkReader reader) => new Ray(reader.ReadVector3(), reader.ReadVector3()); + + public static Matrix4x4 ReadMatrix4x4(this NetworkReader reader) + { + return new Matrix4x4 + { + m00 = reader.ReadSingle(), + m01 = reader.ReadSingle(), + m02 = reader.ReadSingle(), + m03 = reader.ReadSingle(), + m10 = reader.ReadSingle(), + m11 = reader.ReadSingle(), + m12 = reader.ReadSingle(), + m13 = reader.ReadSingle(), + m20 = reader.ReadSingle(), + m21 = reader.ReadSingle(), + m22 = reader.ReadSingle(), + m23 = reader.ReadSingle(), + m30 = reader.ReadSingle(), + m31 = reader.ReadSingle(), + m32 = reader.ReadSingle(), + m33 = reader.ReadSingle() + }; + } + + public static byte[] ReadBytes(this NetworkReader reader, int count) + { + byte[] bytes = new byte[count]; + reader.ReadBytes(bytes, count); + return bytes; + } + + public static Guid ReadGuid(this NetworkReader reader) => new Guid(reader.ReadBytes(16)); + public static Transform ReadTransform(this NetworkReader reader) => reader.ReadNetworkIdentity()?.transform; + public static GameObject ReadGameObject(this NetworkReader reader) => reader.ReadNetworkIdentity()?.gameObject; + + public static NetworkIdentity ReadNetworkIdentity(this NetworkReader reader) + { + uint netId = reader.ReadPackedUInt32(); + if (netId == 0) return null; + + if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity)) + { + return identity; + } + + if (LogFilter.Debug) Debug.Log("ReadNetworkIdentity netId:" + netId + " not found in spawned"); + return null; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkReader.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkReader.cs.meta new file mode 100644 index 0000000..f5b0c1e --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1610f05ec5bd14d6882e689f7372596a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkServer.cs b/Assets/Packages/Mirror/Runtime/NetworkServer.cs new file mode 100644 index 0000000..a413675 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkServer.cs @@ -0,0 +1,1414 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using UnityEngine; + +namespace Mirror +{ + /// + /// The NetworkServer uses a NetworkServerSimple for basic network functionality and adds more game-like functionality. + /// + /// + /// NetworkServer handles remote connections from remote clients via a NetworkServerSimple instance, and also has a local connection for a local client. + /// The NetworkServer is a singleton. It has static convenience functions such as NetworkServer.SendToAll() and NetworkServer.Spawn() which automatically use the singleton instance. + /// The NetworkManager uses the NetworkServer, but it can be used without the NetworkManager. + /// The set of networked objects that have been spawned is managed by NetworkServer. Objects are spawned with NetworkServer.Spawn() which adds them to this set, and makes them be created on clients. Spawned objects are removed automatically when they are destroyed, or than they can be removed from the spawned set by calling NetworkServer.UnSpawn() - this does not destroy the object. + /// There are a number of internal messages used by NetworkServer, these are setup when NetworkServer.Listen() is called. + /// + public static class NetworkServer + { + static bool initialized; + static int maxConnections; + + // original HLAPI has .localConnections list with only m_LocalConnection in it + // (for backwards compatibility because they removed the real localConnections list a while ago) + // => removed it for easier code. use .localConnection now! + public static NetworkConnection localConnection { get; private set; } + + /// + /// A list of local connections on the server. + /// + public static Dictionary connections = new Dictionary(); + + /// + /// Dictionary of the message handlers registered with the server. + /// The key to the dictionary is the message Id. + /// + public static Dictionary handlers = new Dictionary(); + + /// + /// If you enable this, the server will not listen for incoming connections on the regular network port. + /// This can be used if the game is running in host mode and does not want external players to be able to connect - making it like a single-player game. Also this can be useful when using AddExternalConnection(). + /// + public static bool dontListen; + + /// + /// Checks if the server has been started. + /// This will be true after NetworkServer.Listen() has been called. + /// + public static bool active { get; private set; } + + /// + /// True is a local client is currently active on the server. + /// This will be true for "Hosts" on hosted server games. + /// + public static bool localClientActive { get; private set; } + + /// + /// Reset the NetworkServer singleton. + /// + public static void Reset() + { + active = false; + } + + /// + /// This shuts down the server and disconnects all clients. + /// + public static void Shutdown() + { + if (initialized) + { + DisconnectAll(); + + if (dontListen) + { + // was never started, so dont stop + } + else + { + Transport.activeTransport.ServerStop(); + } + + Transport.activeTransport.OnServerDisconnected.RemoveListener(OnDisconnected); + Transport.activeTransport.OnServerConnected.RemoveListener(OnConnected); + Transport.activeTransport.OnServerDataReceived.RemoveListener(OnDataReceived); + Transport.activeTransport.OnServerError.RemoveListener(OnError); + + initialized = false; + } + dontListen = false; + active = false; + + NetworkIdentity.ResetNextNetworkId(); + } + + static void Initialize() + { + if (initialized) + return; + + initialized = true; + if (LogFilter.Debug) Debug.Log("NetworkServer Created version " + Version.Current); + + //Make sure connections are cleared in case any old connections references exist from previous sessions + connections.Clear(); + Transport.activeTransport.OnServerDisconnected.AddListener(OnDisconnected); + Transport.activeTransport.OnServerConnected.AddListener(OnConnected); + Transport.activeTransport.OnServerDataReceived.AddListener(OnDataReceived); + Transport.activeTransport.OnServerError.AddListener(OnError); + } + + internal static void RegisterMessageHandlers() + { + RegisterHandler(OnClientReadyMessage); + RegisterHandler(OnCommandMessage); + RegisterHandler(OnRemovePlayerMessage); + RegisterHandler(NetworkTime.OnServerPing); + } + + /// + /// Start the server, setting the maximum number of connections. + /// + /// Maximum number of allowed connections + /// + public static bool Listen(int maxConns) + { + Initialize(); + maxConnections = maxConns; + + // only start server if we want to listen + if (!dontListen) + { + Transport.activeTransport.ServerStart(); + if (LogFilter.Debug) Debug.Log("Server started listening"); + } + + active = true; + RegisterMessageHandlers(); + return true; + } + + /// + /// This accepts a network connection and adds it to the server. + /// This connection will use the callbacks registered with the server. + /// + /// Network connection to add. + /// True if added. + public static bool AddConnection(NetworkConnection conn) + { + if (!connections.ContainsKey(conn.connectionId)) + { + // connection cannot be null here or conn.connectionId + // would throw NRE + connections[conn.connectionId] = conn; + conn.SetHandlers(handlers); + return true; + } + // already a connection with this id + return false; + } + + /// + /// This removes an external connection added with AddExternalConnection(). + /// + /// The id of the connection to remove. + /// True if the removal succeeded + public static bool RemoveConnection(int connectionId) + { + return connections.Remove(connectionId); + } + + // called by LocalClient to add itself. dont call directly. + internal static void SetLocalConnection(ULocalConnectionToClient conn) + { + if (localConnection != null) + { + Debug.LogError("Local Connection already exists"); + return; + } + + localConnection = conn; + OnConnected(localConnection); + } + + internal static void RemoveLocalConnection() + { + if (localConnection != null) + { + localConnection.Disconnect(); + localConnection.Dispose(); + localConnection = null; + } + localClientActive = false; + RemoveConnection(0); + } + + internal static void ActivateLocalClientScene() + { + if (localClientActive) + return; + + // ClientScene for a local connection is becoming active. any spawned objects need to be started as client objects + localClientActive = true; + foreach (NetworkIdentity identity in NetworkIdentity.spawned.Values) + { + if (!identity.isClient) + { + if (LogFilter.Debug) Debug.Log("ActivateClientScene " + identity.netId + " " + identity); + + identity.OnStartClient(); + } + } + } + + // this is like SendToReady - but it doesn't check the ready flag on the connection. + // this is used for ObjectDestroy messages. + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("use SendToObservers instead")] + static bool SendToObservers(NetworkIdentity identity, short msgType, MessageBase msg) + { + if (LogFilter.Debug) Debug.Log("Server.SendToObservers id:" + msgType); + + if (identity != null && identity.observers != null) + { + // pack message into byte[] once + byte[] bytes = MessagePacker.PackMessage((ushort)msgType, msg); + + // send to all observers + bool result = true; + foreach (KeyValuePair kvp in identity.observers) + { + result &= kvp.Value.SendBytes(bytes); + } + return result; + } + return false; + } + + // this is like SendToReady - but it doesn't check the ready flag on the connection. + // this is used for ObjectDestroy messages. + static bool SendToObservers(NetworkIdentity identity, T msg) where T: IMessageBase + { + if (LogFilter.Debug) Debug.Log("Server.SendToObservers id:" + typeof(T)); + + if (identity != null && identity.observers != null) + { + // pack message into byte[] once + byte[] bytes = MessagePacker.Pack(msg); + + bool result = true; + foreach (KeyValuePair kvp in identity.observers) + { + result &= kvp.Value.SendBytes(bytes); + } + return result; + } + return false; + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use SendToAll instead.")] + public static bool SendToAll(int msgType, MessageBase msg, int channelId = Channels.DefaultReliable) + { + if (LogFilter.Debug) Debug.Log("Server.SendToAll id:" + msgType); + + // pack message into byte[] once + byte[] bytes = MessagePacker.PackMessage((ushort)msgType, msg); + + // send to all + bool result = true; + foreach (KeyValuePair kvp in connections) + { + result &= kvp.Value.SendBytes(bytes, channelId); + } + return result; + } + + /// + /// Send a message structure with the given type number to all connected clients. + /// This applies to clients that are ready and not-ready. + /// + /// Message type. + /// Message structure. + /// Transport channel to use + /// + public static bool SendToAll(T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase + { + if (LogFilter.Debug) Debug.Log("Server.SendToAll id:" + typeof(T)); + + // pack message into byte[] once + byte[] bytes = MessagePacker.Pack(msg); + + bool result = true; + foreach (KeyValuePair kvp in connections) + { + result &= kvp.Value.SendBytes(bytes, channelId); + } + return result; + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use SendToReady instead.")] + public static bool SendToReady(NetworkIdentity identity, short msgType, MessageBase msg, int channelId = Channels.DefaultReliable) + { + if (LogFilter.Debug) Debug.Log("Server.SendToReady msgType:" + msgType); + + if (identity != null && identity.observers != null) + { + // pack message into byte[] once + byte[] bytes = MessagePacker.PackMessage((ushort)msgType, msg); + + // send to all ready observers + bool result = true; + foreach (KeyValuePair kvp in identity.observers) + { + if (kvp.Value.isReady) + { + result &= kvp.Value.SendBytes(bytes, channelId); + } + } + return result; + } + return false; + } + + /// + /// Send a message structure with the given type number to only clients which are ready. + /// See Networking.NetworkClient.Ready. + /// + /// Message type. + /// + /// Message structure. + /// Send to observers including self.. + /// Transport channel to use + /// + public static bool SendToReady(NetworkIdentity identity, T msg, bool includeSelf = true, int channelId = Channels.DefaultReliable) where T : IMessageBase + { + if (LogFilter.Debug) Debug.Log("Server.SendToReady msgType:" + typeof(T)); + + if (identity != null && identity.observers != null) + { + // pack message into byte[] once + byte[] bytes = MessagePacker.Pack(msg); + + bool result = true; + foreach (KeyValuePair kvp in identity.observers) + { + bool isSelf = kvp.Value == identity.connectionToClient; + if ((!isSelf || includeSelf) && + kvp.Value.isReady) + { + result &= kvp.Value.SendBytes(bytes, channelId); + } + } + return result; + } + return false; + } + + /// + /// Send a message structure with the given type number to only clients which are ready. + /// See Networking.NetworkClient.Ready. + /// + /// Message type. + /// + /// Message structure. + /// Transport channel to use + /// + public static bool SendToReady(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase + { + return SendToReady(identity, msg, true, channelId); + } + + /// + /// Disconnect all currently connected clients, including the local connection. + /// This can only be called on the server. Clients will receive the Disconnect message. + /// + public static void DisconnectAll() + { + DisconnectAllConnections(); + localConnection = null; + + active = false; + localClientActive = false; + } + + /// + /// Disconnect all currently connected clients except the local connection. + /// This can only be called on the server. Clients will receive the Disconnect message. + /// + public static void DisconnectAllConnections() + { + foreach (NetworkConnection conn in connections.Values) + { + conn.Disconnect(); + // call OnDisconnected unless local player in host mode + if (conn.connectionId != 0) + OnDisconnected(conn); + conn.Dispose(); + } + connections.Clear(); + } + + // The user should never need to pump the update loop manually + internal static void Update() + { + if (!active) + return; + + // update all server objects + foreach (KeyValuePair kvp in NetworkIdentity.spawned) + { + if (kvp.Value != null && kvp.Value.gameObject != null) + { + kvp.Value.MirrorUpdate(); + } + else + { + // spawned list should have no null entries because we + // always call Remove in OnObjectDestroy everywhere. + Debug.LogWarning("Found 'null' entry in spawned list for netId=" + kvp.Key + ". Please call NetworkServer.Destroy to destroy networked objects. Don't use GameObject.Destroy."); + } + } + } + + static void OnConnected(int connectionId) + { + if (LogFilter.Debug) Debug.Log("Server accepted client:" + connectionId); + + // connectionId needs to be > 0 because 0 is reserved for local player + if (connectionId <= 0) + { + Debug.LogError("Server.HandleConnect: invalid connectionId: " + connectionId + " . Needs to be >0, because 0 is reserved for local player."); + Transport.activeTransport.ServerDisconnect(connectionId); + return; + } + + // connectionId not in use yet? + if (connections.ContainsKey(connectionId)) + { + Transport.activeTransport.ServerDisconnect(connectionId); + if (LogFilter.Debug) Debug.Log("Server connectionId " + connectionId + " already in use. kicked client:" + connectionId); + 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) + { + // get ip address from connection + string address = Transport.activeTransport.ServerGetClientAddress(connectionId); + + // add player info + NetworkConnection conn = new NetworkConnection(address, connectionId); + OnConnected(conn); + } + else + { + // kick + Transport.activeTransport.ServerDisconnect(connectionId); + if (LogFilter.Debug) Debug.Log("Server full, kicked client:" + connectionId); + } + } + + static void OnConnected(NetworkConnection conn) + { + if (LogFilter.Debug) Debug.Log("Server accepted client:" + conn.connectionId); + + // add connection and invoke connected event + AddConnection(conn); + conn.InvokeHandler(new ConnectMessage()); + } + + static void OnDisconnected(int connectionId) + { + if (LogFilter.Debug) Debug.Log("Server disconnect client:" + connectionId); + + if (connections.TryGetValue(connectionId, out NetworkConnection conn)) + { + conn.Disconnect(); + RemoveConnection(connectionId); + if (LogFilter.Debug) Debug.Log("Server lost client:" + connectionId); + + OnDisconnected(conn); + } + } + + static void OnDisconnected(NetworkConnection conn) + { + conn.InvokeHandler(new DisconnectMessage()); + if (LogFilter.Debug) Debug.Log("Server lost client:" + conn.connectionId); + } + + static void OnDataReceived(int connectionId, ArraySegment data) + { + if (connections.TryGetValue(connectionId, out NetworkConnection conn)) + { + conn.TransportReceive(data); + } + else + { + Debug.LogError("HandleData Unknown connectionId:" + connectionId); + } + } + + static void OnError(int connectionId, Exception exception) + { + // TODO Let's discuss how we will handle errors + Debug.LogException(exception); + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use RegisterHandler instead.")] + public static void RegisterHandler(int msgType, NetworkMessageDelegate handler) + { + if (handlers.ContainsKey(msgType)) + { + if (LogFilter.Debug) Debug.Log("NetworkServer.RegisterHandler replacing " + msgType); + } + handlers[msgType] = handler; + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use RegisterHandler instead.")] + public static void RegisterHandler(MsgType msgType, NetworkMessageDelegate handler) + { + RegisterHandler((int)msgType, handler); + } + + /// + /// Register a handler for a particular message type. + /// There are several system message types which you can add handlers for. You can also add your own message types. + /// + /// Message type + /// Function handler which will be invoked for when this message type is received. + public static void RegisterHandler(Action handler) where T: IMessageBase, new() + { + int msgType = MessagePacker.GetId(); + if (handlers.ContainsKey(msgType)) + { + if (LogFilter.Debug) Debug.Log("NetworkServer.RegisterHandler replacing " + msgType); + } + handlers[msgType] = MessagePacker.MessageHandler(handler); + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use UnregisterHandler instead.")] + public static void UnregisterHandler(int msgType) + { + handlers.Remove(msgType); + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use UnregisterHandler instead.")] + public static void UnregisterHandler(MsgType msgType) + { + UnregisterHandler((int)msgType); + } + + /// + /// Unregisters a handler for a particular message type. + /// + /// Message type + public static void UnregisterHandler() where T : IMessageBase + { + int msgType = MessagePacker.GetId(); + handlers.Remove(msgType); + } + + /// + /// Clear all registered callback handlers. + /// + public static void ClearHandlers() + { + handlers.Clear(); + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use SendToClient instead.")] + public static void SendToClient(int connectionId, int msgType, MessageBase msg) + { + if (connections.TryGetValue(connectionId, out NetworkConnection conn)) + { + conn.Send(msgType, msg); + return; + } + Debug.LogError("Failed to send message to connection ID '" + connectionId + ", not found in connection list"); + } + + /// + /// Send a message to the client which owns the given connection ID. + /// It accepts the connection ID as a parameter as well as a message and MsgType. Remember to set the client up for receiving the messages by using NetworkClient.RegisterHandler. Also, for user messages you must use a MsgType with a higher ID number than MsgType.Highest. + /// + /// Message type + /// Client connection ID. + /// Message struct to send + public static void SendToClient(int connectionId, T msg) where T : IMessageBase + { + if (connections.TryGetValue(connectionId, out NetworkConnection conn)) + { + conn.Send(msg); + return; + } + Debug.LogError("Failed to send message to connection ID '" + connectionId + ", not found in connection list"); + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use SendToClientOfPlayer instead.")] + public static void SendToClientOfPlayer(NetworkIdentity identity, int msgType, MessageBase msg) + { + if (identity != null) + { + identity.connectionToClient.Send(msgType, msg); + } + else + { + Debug.LogError("SendToClientOfPlayer: player has no NetworkIdentity: " + identity.name); + } + } + + /// + /// send this message to the player only + /// + /// Message type + /// + /// + public static void SendToClientOfPlayer(NetworkIdentity identity, T msg) where T: IMessageBase + { + if (identity != null) + { + identity.connectionToClient.Send(msg); + } + else + { + Debug.LogError("SendToClientOfPlayer: player has no NetworkIdentity: " + identity.name); + } + } + + /// + /// This replaces the player object for a connection with a different player object. The old player object is not destroyed. + /// If a connection already has a player object, this can be used to replace that object with a different player object. This does NOT change the ready state of the connection, so it can safely be used while changing scenes. + /// + /// Connection which is adding the player. + /// Player object spawned for the player. + /// + /// + public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, Guid assetId) + { + if (GetNetworkIdentity(player, out NetworkIdentity identity)) + { + identity.assetId = assetId; + } + return InternalReplacePlayerForConnection(conn, player); + } + + /// + /// This replaces the player object for a connection with a different player object. The old player object is not destroyed. + /// If a connection already has a player object, this can be used to replace that object with a different player object. This does NOT change the ready state of the connection, so it can safely be used while changing scenes. + /// + /// Connection which is adding the player. + /// Player object spawned for the player. + /// + public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player) + { + return InternalReplacePlayerForConnection(conn, player); + } + + /// + /// When an AddPlayer message handler has received a request from a player, the server calls this to associate the player object with 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. + /// + /// Connection which is adding the player. + /// Player object spawned for the player. + /// + /// + public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player, Guid assetId) + { + if (GetNetworkIdentity(player, out NetworkIdentity identity)) + { + identity.assetId = assetId; + } + return AddPlayerForConnection(conn, player); + } + + static void SpawnObserversForConnection(NetworkConnection conn) + { + if (LogFilter.Debug) Debug.Log("Spawning " + NetworkIdentity.spawned.Count + " objects for conn " + conn.connectionId); + + 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 NetworkIdentity.spawned.Values) + { + if (identity.gameObject.activeSelf) //TODO this is different // try with far away ones in ummorpg! + { + if (LogFilter.Debug) Debug.Log("Sending spawn message for current server objects name='" + identity.name + "' netId=" + identity.netId + " sceneId=" + identity.sceneId); + + bool visible = identity.OnCheckObserver(conn); + if (visible) + { + 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()); + } + + /// + /// When an AddPlayer message handler has received a request from a player, the server calls this to associate the player object with 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. + /// + /// Connection which is adding the player. + /// Player object spawned for the player. + /// + public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player) + { + NetworkIdentity identity = player.GetComponent(); + if (identity == null) + { + Debug.Log("AddPlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to " + player); + return false; + } + identity.Reset(); + + // cannot have a player object in "Add" version + if (conn.playerController != 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.playerController = identity; + + // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients) + identity.connectionToClient = conn; + + // set ready if not set yet + SetClientReady(conn); + + if (SetupLocalPlayerForConnection(conn, identity)) + { + return true; + } + + if (LogFilter.Debug) Debug.Log("Adding new playerGameObject object netId: " + identity.netId + " asset ID " + identity.assetId); + + FinishPlayerForConnection(identity, player); + if (identity.localPlayerAuthority) + { + identity.SetClientOwner(conn); + } + return true; + } + + static bool SetupLocalPlayerForConnection(NetworkConnection conn, NetworkIdentity identity) + { + if (LogFilter.Debug) Debug.Log("NetworkServer SetupLocalPlayerForConnection netID:" + identity.netId); + + if (conn is ULocalConnectionToClient) + { + if (LogFilter.Debug) Debug.Log("NetworkServer AddPlayer handling ULocalConnectionToClient"); + + // Spawn this player for other players, instead of SpawnObject: + if (identity.netId == 0) + { + // it is allowed to provide an already spawned object as the new player object. + // so dont spawn it again. + identity.OnStartServer(true); + } + identity.RebuildObservers(true); + SendSpawnMessage(identity, null); + + // Set up local player instance on the client instance and update local object map + NetworkClient.AddLocalPlayer(identity); + identity.SetClientOwner(conn); + + // Trigger OnAuthority + identity.ForceAuthority(true); + + // Trigger OnStartLocalPlayer + identity.SetLocalPlayer(); + return true; + } + return false; + } + + static void FinishPlayerForConnection(NetworkIdentity identity, GameObject playerGameObject) + { + if (identity.netId == 0) + { + // it is allowed to provide an already spawned object as the new player object. + // so dont spawn it again. + Spawn(playerGameObject); + } + } + + internal static bool InternalReplacePlayerForConnection(NetworkConnection conn, GameObject player) + { + NetworkIdentity identity = player.GetComponent(); + if (identity == null) + { + Debug.LogError("ReplacePlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to " + player); + return false; + } + + //NOTE: there can be an existing player + if (LogFilter.Debug) Debug.Log("NetworkServer ReplacePlayer"); + + // is there already an owner that is a different object?? + if (conn.playerController != null) + { + conn.playerController.SetNotLocalPlayer(); + conn.playerController.clientAuthorityOwner = null; + } + + conn.playerController = identity; + + // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients) + identity.connectionToClient = conn; + + //NOTE: DONT set connection ready. + + // 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); + + if (LogFilter.Debug) Debug.Log("NetworkServer ReplacePlayer setup local"); + + if (SetupLocalPlayerForConnection(conn, identity)) + { + return true; + } + + if (LogFilter.Debug) Debug.Log("Replacing playerGameObject object netId: " + player.GetComponent().netId + " asset ID " + player.GetComponent().assetId); + + FinishPlayerForConnection(identity, player); + if (identity.localPlayerAuthority) + { + identity.SetClientOwner(conn); + } + return true; + } + + static bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity) + { + identity = go.GetComponent(); + if (identity == null) + { + Debug.LogError("GameObject " + go.name + " doesn't have NetworkIdentity."); + return false; + } + return true; + } + + /// + /// Sets the client to be ready. + /// 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. + /// + /// The connection of the client to make ready. + public static void SetClientReady(NetworkConnection conn) + { + if (LogFilter.Debug) Debug.Log("SetClientReadyInternal for conn:" + conn.connectionId); + + // set ready + conn.isReady = true; + + // client is ready to start spawning objects + if (conn.playerController != null) + SpawnObserversForConnection(conn); + } + + 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); + } + + /// + /// 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 (NetworkConnection conn in connections.Values) + { + SetClientNotReady(conn); + } + } + + /// + /// Sets 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(). + /// + /// The connection of the client to make not ready. + public static void SetClientNotReady(NetworkConnection conn) + { + if (conn.isReady) + { + if (LogFilter.Debug) Debug.Log("PlayerNotReady " + conn); + conn.isReady = false; + conn.RemoveObservers(); + + conn.Send(new NotReadyMessage()); + } + } + + // default ready handler. + static void OnClientReadyMessage(NetworkConnection conn, ReadyMessage msg) + { + if (LogFilter.Debug) Debug.Log("Default handler for ready message from " + conn); + SetClientReady(conn); + } + + // default remove player handler + static void OnRemovePlayerMessage(NetworkConnection conn, RemovePlayerMessage msg) + { + if (conn.playerController != null) + { + Destroy(conn.playerController.gameObject); + conn.playerController = null; + } + else + { + Debug.LogError("Received remove player message but connection has no player"); + } + } + + // Handle command from specific player, this could be one of multiple players on a single client + static void OnCommandMessage(NetworkConnection conn, CommandMessage msg) + { + if (!NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity identity)) + { + 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 + if (conn.playerController != null && conn.playerController.netId != identity.netId) + { + if (identity.clientAuthorityOwner != conn) + { + Debug.LogWarning("Command for object without authority [netId=" + msg.netId + "]"); + return; + } + } + + if (LogFilter.Debug) Debug.Log("OnCommandMessage for netId=" + msg.netId + " conn=" + conn); + identity.HandleCommand(msg.componentIndex, msg.functionHash, new NetworkReader(msg.payload)); + } + + internal static void SpawnObject(GameObject obj) + { + if (!active) + { + Debug.LogError("SpawnObject for " + obj + ", NetworkServer is not active. Cannot spawn objects without an active server."); + return; + } + + NetworkIdentity identity = obj.GetComponent(); + if (identity == null) + { + Debug.LogError("SpawnObject " + obj + " has no NetworkIdentity. Please add a NetworkIdentity to " + obj); + return; + } + identity.Reset(); + + identity.OnStartServer(false); + + if (LogFilter.Debug) Debug.Log("SpawnObject instance ID " + identity.netId + " asset ID " + identity.assetId); + + identity.RebuildObservers(true); + //SendSpawnMessage(objNetworkIdentity, null); + } + + internal static void SendSpawnMessage(NetworkIdentity identity, NetworkConnection conn) + { + if (identity.serverOnly) + return; + + if (LogFilter.Debug) Debug.Log("Server SendSpawnMessage: name=" + identity.name + " sceneId=" + identity.sceneId.ToString("X") + " netid=" + identity.netId); // for easier debugging + + // one writer for owner, one for observers + NetworkWriter ownerWriter = NetworkWriterPool.GetWriter(); + NetworkWriter observersWriter = NetworkWriterPool.GetWriter(); + + + // serialize all components with initialState = true + // (can be null if has none) + identity.OnSerializeAllSafely(true, ownerWriter, out int ownerWritten, observersWriter, out int observersWritten); + + // convert to ArraySegment to avoid reader allocations + // (need to handle null case too) + ArraySegment ownerSegment = ownerWritten > 0 ? ownerWriter.ToArraySegment() : default; + ArraySegment observersSegment = observersWritten > 0 ? observersWriter.ToArraySegment() : default; + + // 'identity' is a prefab that should be spawned + if (identity.sceneId == 0) + { + SpawnPrefabMessage msg = new SpawnPrefabMessage + { + netId = identity.netId, + owner = conn?.playerController == identity, + assetId = identity.assetId, + // use local values for VR support + position = identity.transform.localPosition, + rotation = identity.transform.localRotation, + scale = identity.transform.localScale + }; + + // conn is != null when spawning it for a client + if (conn != null) + { + // use owner segment if 'conn' owns this identity, otherwise + // use observers segment + bool isOwner = identity.connectionToClient == conn; + msg.payload = isOwner ? ownerSegment : observersSegment; + + conn.Send(msg); + } + // conn is == null when spawning it for the local player + else + { + // send ownerWriter to owner + // (spawn no matter what, even if no components were + // serialized because the spawn message contains more data. + // components might still be updated later on.) + msg.payload = ownerSegment; + SendToClientOfPlayer(identity, msg); + + // send observersWriter to everyone but owner + // (spawn no matter what, even if no components were + // serialized because the spawn message contains more data. + // components might still be updated later on.) + msg.payload = observersSegment; + SendToReady(identity, msg, false); + } + } + // 'identity' is a scene object that should be spawned again + else + { + SpawnSceneObjectMessage msg = new SpawnSceneObjectMessage + { + netId = identity.netId, + owner = conn?.playerController == identity, + sceneId = identity.sceneId, + // use local values for VR support + position = identity.transform.localPosition, + rotation = identity.transform.localRotation, + scale = identity.transform.localScale + }; + + // conn is != null when spawning it for a client + if (conn != null) + { + // use owner segment if 'conn' owns this identity, otherwise + // use observers segment + bool isOwner = identity.connectionToClient == conn; + msg.payload = isOwner ? ownerSegment : observersSegment; + + conn.Send(msg); + } + // conn is == null when spawning it for the local player + else + { + // send ownerWriter to owner + // (spawn no matter what, even if no components were + // serialized because the spawn message contains more data. + // components might still be updated later on.) + msg.payload = ownerSegment; + SendToClientOfPlayer(identity, msg); + + // send observersWriter to everyone but owner + // (spawn no matter what, even if no components were + // serialized because the spawn message contains more data. + // components might still be updated later on.) + msg.payload = observersSegment; + SendToReady(identity, msg, false); + } + } + + NetworkWriterPool.Recycle(ownerWriter); + NetworkWriterPool.Recycle(observersWriter); + } + + /// + /// This destroys all the player objects associated with a NetworkConnections on a 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. + /// + /// The connections object to clean up for. + public static void DestroyPlayerForConnection(NetworkConnection conn) + { + // => destroy what we can destroy. + HashSet tmp = new HashSet(conn.clientOwnedObjects); + foreach (uint netId in tmp) + { + if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity)) + { + Destroy(identity.gameObject); + } + } + + if (conn.playerController != null) + { + DestroyObject(conn.playerController, true); + conn.playerController = null; + } + } + + /// + /// 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. + /// + /// Game object with NetworkIdentity to spawn. + public static void Spawn(GameObject obj) + { + if (VerifyCanSpawn(obj)) + { + SpawnObject(obj); + } + } + + static bool CheckForPrefab(GameObject obj) + { +#if UNITY_EDITOR +#if UNITY_2018_3_OR_NEWER + return UnityEditor.PrefabUtility.IsPartOfPrefabAsset(obj); +#elif UNITY_2018_2_OR_NEWER + return (UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(obj) == null) && (UnityEditor.PrefabUtility.GetPrefabObject(obj) != null); +#else + return (UnityEditor.PrefabUtility.GetPrefabParent(obj) == null) && (UnityEditor.PrefabUtility.GetPrefabObject(obj) != null); +#endif +#else + return false; +#endif + } + + static bool VerifyCanSpawn(GameObject obj) + { + if (CheckForPrefab(obj)) + { + Debug.LogErrorFormat("GameObject {0} is a prefab, it can't be spawned. This will cause errors in builds.", obj.name); + return false; + } + + return true; + } + + /// + /// This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client. + /// This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + /// + /// The object to spawn. + /// The player object to set Client Authority to. + /// + public static bool SpawnWithClientAuthority(GameObject obj, GameObject player) + { + NetworkIdentity identity = player.GetComponent(); + if (identity == null) + { + Debug.LogError("SpawnWithClientAuthority player object has no NetworkIdentity"); + return false; + } + + if (identity.connectionToClient == null) + { + Debug.LogError("SpawnWithClientAuthority player object is not a player."); + return false; + } + + return SpawnWithClientAuthority(obj, identity.connectionToClient); + } + + /// + /// This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client. + /// This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + /// + /// The object to spawn. + /// The connection to set Client Authority to. + /// + public static bool SpawnWithClientAuthority(GameObject obj, NetworkConnection conn) + { + if (!conn.isReady) + { + Debug.LogError("SpawnWithClientAuthority NetworkConnection is not ready!"); + return false; + } + + Spawn(obj); + + NetworkIdentity identity = obj.GetComponent(); + if (identity == null || !identity.isServer) + { + // spawning the object failed. + return false; + } + + return identity.AssignClientAuthority(conn); + } + + /// + /// This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client. + /// This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + /// + /// The object to spawn. + /// The assetId of the object to spawn. Used for custom spawn handlers. + /// The connection to set Client Authority to. + /// + public static bool SpawnWithClientAuthority(GameObject obj, Guid assetId, NetworkConnection conn) + { + Spawn(obj, assetId); + + NetworkIdentity identity = obj.GetComponent(); + if (identity == null || !identity.isServer) + { + // spawning the object failed. + return false; + } + + return identity.AssignClientAuthority(conn); + } + + /// + /// This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client. + /// This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + /// + /// The object to spawn. + /// The assetId of the object to spawn. Used for custom spawn handlers. + public static void Spawn(GameObject obj, Guid assetId) + { + if (VerifyCanSpawn(obj)) + { + if (GetNetworkIdentity(obj, out NetworkIdentity identity)) + { + identity.assetId = assetId; + } + SpawnObject(obj); + } + } + + static void DestroyObject(NetworkIdentity identity, bool destroyServerObject) + { + if (LogFilter.Debug) Debug.Log("DestroyObject instance:" + identity.netId); + NetworkIdentity.spawned.Remove(identity.netId); + + identity.clientAuthorityOwner?.RemoveOwnedObject(identity); + + ObjectDestroyMessage msg = new ObjectDestroyMessage + { + netId = identity.netId + }; + SendToObservers(identity, msg); + + identity.ClearObservers(); + if (NetworkClient.active && localClientActive) + { + identity.OnNetworkDestroy(); + } + + // when unspawning, dont destroy the server's object + if (destroyServerObject) + { + UnityEngine.Object.Destroy(identity.gameObject); + } + identity.MarkForReset(); + } + + /// + /// 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(). + /// + /// Game object to destroy. + public static void Destroy(GameObject obj) + { + if (obj == null) + { + if (LogFilter.Debug) Debug.Log("NetworkServer DestroyObject is null"); + return; + } + + if (GetNetworkIdentity(obj, out NetworkIdentity identity)) + { + DestroyObject(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. + /// + /// The spawned object to be unspawned. + public static void UnSpawn(GameObject obj) + { + if (obj == null) + { + if (LogFilter.Debug) Debug.Log("NetworkServer UnspawnObject is null"); + return; + } + + if (GetNetworkIdentity(obj, out NetworkIdentity identity)) + { + DestroyObject(identity, false); + } + } + + /// + /// Obsolete: Use instead. + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkIdentity.spawned[netId] instead.")] + public static GameObject FindLocalObject(uint netId) + { + if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity)) + { + return identity.gameObject; + } + return null; + } + + static bool ValidateSceneObject(NetworkIdentity identity) + { + if (identity.gameObject.hideFlags == HideFlags.NotEditable || identity.gameObject.hideFlags == HideFlags.HideAndDontSave) + return false; + +#if UNITY_EDITOR + if (UnityEditor.EditorUtility.IsPersistent(identity.gameObject)) + return false; +#endif + + // If not a scene object + return identity.sceneId != 0; + } + + /// + /// This causes NetworkIdentity objects in a scene to be spawned on a 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. + /// + /// Success if objects where spawned. + public static bool SpawnObjects() + { + if (!active) + return true; + + NetworkIdentity[] identities = Resources.FindObjectsOfTypeAll(); + foreach (NetworkIdentity identity in identities) + { + if (ValidateSceneObject(identity)) + { + if (LogFilter.Debug) Debug.Log("SpawnObjects sceneId:" + identity.sceneId.ToString("X") + " name:" + identity.gameObject.name); + identity.Reset(); + identity.gameObject.SetActive(true); + } + } + + foreach (NetworkIdentity identity in identities) + { + if (ValidateSceneObject(identity)) + { + Spawn(identity.gameObject); + + // these objects are server authority - even if "localPlayerAuthority" is set on them + identity.ForceAuthority(true); + } + } + return true; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkServer.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkServer.cs.meta new file mode 100644 index 0000000..4d44a26 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5f5ec068f5604c32b160bc49ee97b75 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkStartPosition.cs b/Assets/Packages/Mirror/Runtime/NetworkStartPosition.cs new file mode 100644 index 0000000..c7483b5 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkStartPosition.cs @@ -0,0 +1,24 @@ +using UnityEngine; + +namespace Mirror +{ + /// + /// This component is used to make a gameObject a starting position for spawning player objects in multiplayer games. + /// This object's transform will be automatically registered and unregistered with the NetworkManager as a starting position. + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/NetworkStartPosition")] + [HelpURL("https://mirror-networking.com/xmldocs/articles/Components/NetworkStartPosition.html")] + public class NetworkStartPosition : MonoBehaviour + { + public void Awake() + { + NetworkManager.RegisterStartPosition(transform); + } + + public void OnDestroy() + { + NetworkManager.UnRegisterStartPosition(transform); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkStartPosition.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkStartPosition.cs.meta new file mode 100644 index 0000000..97f5445 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkStartPosition.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41f84591ce72545258ea98cb7518d8b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkTime.cs b/Assets/Packages/Mirror/Runtime/NetworkTime.cs new file mode 100644 index 0000000..222d354 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkTime.cs @@ -0,0 +1,177 @@ +using System; +using UnityEngine; +using Stopwatch = System.Diagnostics.Stopwatch; + +namespace Mirror +{ + /// + /// Synchronize time between the server and the clients + /// + public static class NetworkTime + { + /// + /// how often are we sending ping messages + /// used to calculate network time and RTT + /// + public static float PingFrequency = 2.0f; + + /// + /// average out the last few results from Ping + /// + public static int PingWindowSize = 10; + + static double lastPingTime; + + + // Date and time when the application started + static readonly Stopwatch stopwatch = new Stopwatch(); + + static NetworkTime() + { + stopwatch.Start(); + } + + static ExponentialMovingAverage _rtt = new ExponentialMovingAverage(10); + static ExponentialMovingAverage _offset = new ExponentialMovingAverage(10); + + // the true offset guaranteed to be in this range + static double offsetMin = double.MinValue; + static double offsetMax = double.MaxValue; + + // returns the clock time _in this system_ + static double LocalTime() + { + return stopwatch.Elapsed.TotalSeconds; + } + + public static void Reset() + { + _rtt = new ExponentialMovingAverage(PingWindowSize); + _offset = new ExponentialMovingAverage(PingWindowSize); + offsetMin = double.MinValue; + offsetMax = double.MaxValue; + } + + internal static void UpdateClient() + { + if (Time.time - lastPingTime >= PingFrequency) + { + NetworkPingMessage pingMessage = new NetworkPingMessage(LocalTime()); + NetworkClient.Send(pingMessage); + lastPingTime = Time.time; + } + } + + // 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(NetworkConnection conn, NetworkPingMessage msg) + { + if (LogFilter.Debug) Debug.Log("OnPingServerMessage conn=" + conn); + + NetworkPongMessage pongMsg = new NetworkPongMessage + { + clientTime = msg.clientTime, + serverTime = LocalTime() + }; + + conn.Send(pongMsg); + } + + // 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 + internal static void OnClientPong(NetworkConnection _, NetworkPongMessage msg) + { + double now = LocalTime(); + + // how long did this message take to come back + double newRtt = now - msg.clientTime; + _rtt.Add(newRtt); + + // the difference in time between the client and the server + // but subtract half of the rtt to compensate for latency + // half of rtt is the best approximation we have + double newOffset = now - newRtt * 0.5f - msg.serverTime; + + double newOffsetMin = now - newRtt - msg.serverTime; + double newOffsetMax = now - msg.serverTime; + offsetMin = Math.Max(offsetMin, newOffsetMin); + offsetMax = Math.Min(offsetMax, newOffsetMax); + + if (_offset.Value < offsetMin || _offset.Value > offsetMax) + { + // the old offset was offrange, throw it away and use new one + _offset = new ExponentialMovingAverage(PingWindowSize); + _offset.Add(newOffset); + } + else if (newOffset >= offsetMin || newOffset <= offsetMax) + { + // new offset looks reasonable, add to the average + _offset.Add(newOffset); + } + } + + /// + /// The time in seconds since the server started. + /// + /// + /// + /// Note this value works in the client and the server + /// the value is synchronized accross the network with high accuracy + /// + /// You should not cast this down to a float because the it loses too much accuracy + /// when the server is up for a while + /// 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 => LocalTime() - _offset.Value; + + /// + /// Measurement of the variance of time. + /// The higher the variance, the less accurate the time is + /// + public static double timeVar => _offset.Var; + + /// + /// standard deviation of time. + /// The higher the variance, the less accurate the time is + /// + public static double timeSd => Math.Sqrt(timeVar); + + /// + /// Clock difference in seconds between the client and the server + /// + /// + /// Note this value is always 0 at the server + /// + public static double offset => _offset.Value; + + /// + /// how long in seconds does it take for a message to go + /// to the server and come back + /// + public static double rtt => _rtt.Value; + + /// + /// measure variance of rtt + /// the higher the number, the less accurate rtt is + /// + public static double rttVar => _rtt.Var; + + /// + /// Measure the standard deviation of rtt + /// the higher the number, the less accurate rtt is + /// + public static double rttSd => Math.Sqrt(rttVar); + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkTime.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkTime.cs.meta new file mode 100644 index 0000000..f5c2b6c --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkTime.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09a0c241fc4a5496dbf4a0ab6e9a312c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkWriter.cs b/Assets/Packages/Mirror/Runtime/NetworkWriter.cs new file mode 100644 index 0000000..1766b5d --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkWriter.cs @@ -0,0 +1,564 @@ +using System; +using System.IO; +using System.Text; +using UnityEngine; + +namespace Mirror +{ + // Binary stream Writer. Supports simple types, buffers, arrays, structs, and nested types + public class NetworkWriter + { + public const int MaxStringLength = 1024 * 32; + + // 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 + readonly MemoryStream stream = new MemoryStream(); + + // '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 { get { return (int)stream.Position; } set { stream.Position = value; } } + + // MemoryStream has 3 values: Position, Length and Capacity. + // Position is used to indicate where we are writing + // Length is how much data we have written + // capacity is how much memory we have allocated + // ToArray returns all the data we have written, regardless of the current position + public byte[] ToArray() + { + stream.Flush(); + return stream.ToArray(); + } + + // Gets the serialized data in an ArraySegment + // this is similar to ToArray(), but it gets the data in O(1) + // and without allocations. + // Do not write anything else or modify the NetworkWriter + // while you are using the ArraySegment + public ArraySegment ToArraySegment() + { + stream.Flush(); + if (stream.TryGetBuffer(out ArraySegment data)) + { + return data; + } + throw new Exception("Cannot expose contents of memory stream. Make sure that MemoryStream buffer is publicly visible (see MemoryStream source code)."); + } + + // reset both the position and length of the stream, but leaves the capacity the same + // so that we can reuse this writer without extra allocations + public void SetLength(long value) + { + stream.SetLength(value); + } + + public void WriteByte(byte value) => stream.WriteByte(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[] buffer, int offset, int count) + { + // no null check because we would need to write size info for that too (hence WriteBytesAndSize) + stream.Write(buffer, offset, count); + } + + public void WriteUInt32(uint value) + { + WriteByte((byte)(value & 0xFF)); + WriteByte((byte)((value >> 8) & 0xFF)); + WriteByte((byte)((value >> 16) & 0xFF)); + WriteByte((byte)((value >> 24) & 0xFF)); + } + + public void WriteInt32(int value) => WriteUInt32((uint)value); + + public void WriteUInt64(ulong value) + { + WriteByte((byte)(value & 0xFF)); + WriteByte((byte)((value >> 8) & 0xFF)); + WriteByte((byte)((value >> 16) & 0xFF)); + WriteByte((byte)((value >> 24) & 0xFF)); + WriteByte((byte)((value >> 32) & 0xFF)); + WriteByte((byte)((value >> 40) & 0xFF)); + WriteByte((byte)((value >> 48) & 0xFF)); + WriteByte((byte)((value >> 56) & 0xFF)); + } + + public void WriteInt64(long value) => WriteUInt64((ulong)value); + + #region Obsoletes + [Obsolete("Use WriteUInt16 instead")] + public void Write(ushort value) => this.WriteUInt16(value); + + [Obsolete("Use WriteUInt32 instead")] + public void Write(uint value) => WriteUInt32(value); + + [Obsolete("Use WriteUInt64 instead")] + public void Write(ulong value) => WriteUInt64(value); + + [Obsolete("Use WriteByte instead")] + public void Write(byte value) => stream.WriteByte(value); + + [Obsolete("Use WriteSByte instead")] + public void Write(sbyte value) => WriteByte((byte)value); + + // write char the same way that NetworkReader reads it (2 bytes) + [Obsolete("Use WriteChar instead")] + public void Write(char value) => this.WriteUInt16((ushort)value); + + [Obsolete("Use WriteBoolean instead")] + public void Write(bool value) => WriteByte((byte)(value ? 1 : 0)); + + [Obsolete("Use WriteInt16 instead")] + public void Write(short value) => this.WriteUInt16((ushort)value); + + [Obsolete("Use WriteInt32 instead")] + public void Write(int value) => WriteUInt32((uint)value); + + [Obsolete("Use WriteInt64 instead")] + public void Write(long value) => WriteUInt64((ulong)value); + + [Obsolete("Use WriteSingle instead")] + public void Write(float value) => this.WriteSingle(value); + + [Obsolete("Use WriteDouble instead")] + public void Write(double value) => this.WriteDouble(value); + + [Obsolete("Use WriteDecimal instead")] + public void Write(decimal value) => this.WriteDecimal(value); + + [Obsolete("Use WriteString instead")] + public void Write(string value) => this.WriteString(value); + + [Obsolete("Use WriteBytes instead")] + public void Write(byte[] buffer, int offset, int count) => WriteBytes(buffer, offset, count); + + [Obsolete("Use WriteVector2 instead")] + public void Write(Vector2 value) => this.WriteVector2(value); + + [Obsolete("Use WriteVector3 instead")] + public void Write(Vector3 value) => this.WriteVector3(value); + + [Obsolete("Use WriteVector4 instead")] + public void Write(Vector4 value) => this.WriteVector4(value); + + [Obsolete("Use WriteVector2Int instead")] + public void Write(Vector2Int value) => this.WriteVector2Int(value); + + [Obsolete("Use WriteVector3Int instead")] + public void Write(Vector3Int value) => this.WriteVector3Int(value); + + [Obsolete("Use WriteColor instead")] + public void Write(Color value) => this.WriteColor(value); + + [Obsolete("Use WriteColor32 instead")] + public void Write(Color32 value) => this.WriteColor32(value); + + [Obsolete("Use WriteQuaternion instead")] + public void Write(Quaternion value) => this.WriteQuaternion(value); + + [Obsolete("Use WriteRect instead")] + public void Write(Rect value) => this.WriteRect(value); + + [Obsolete("Use WritePlane instead")] + public void Write(Plane value) => this.WritePlane(value); + + [Obsolete("Use WriteRay instead")] + public void Write(Ray value) => this.WriteRay(value); + + [Obsolete("Use WriteMatrix4x4 instead")] + public void Write(Matrix4x4 value) => this.WriteMatrix4x4(value); + + [Obsolete("Use WriteGuid instead")] + public void Write(Guid value) => this.WriteGuid(value); + + [Obsolete("Use WriteNetworkIdentity instead")] + public void Write(NetworkIdentity value) => this.WriteNetworkIdentity(value); + + [Obsolete("Use WriteTransform instead")] + public void Write(Transform value) => this.WriteTransform(value); + + [Obsolete("Use WriteGameObject instead")] + public void Write(GameObject value) => this.WriteGameObject(value); + + #endregion + } + + + // Mirror's Weaver automatically detects all NetworkWriter function types, + // but they do all need to be extensions. + public static class NetworkWriterExtensions + { + // cache encoding instead of creating it with BinaryWriter each time + // 1000 readers before: 1MB GC, 30ms + // 1000 readers after: 0.8MB GC, 18ms + static readonly UTF8Encoding encoding = new UTF8Encoding(false, true); + static readonly byte[] stringBuffer = new byte[NetworkWriter.MaxStringLength]; + + public static void WriteByte(this NetworkWriter writer, byte value) => writer.WriteByte(value); + + public static void WriteSByte(this NetworkWriter writer, sbyte value) => writer.WriteByte((byte)value); + + public static void WriteChar(this NetworkWriter writer, char value) => writer.WriteUInt16((ushort)value); + + public static void WriteBoolean(this NetworkWriter writer, bool value) => writer.WriteByte((byte)(value ? 1 : 0)); + + public static void WriteUInt16(this NetworkWriter writer, ushort value) + { + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)(value >> 8)); + } + + public static void WriteInt16(this NetworkWriter writer, short value) => writer.WriteUInt16((ushort)value); + + public static void WriteSingle(this NetworkWriter writer, float value) + { + UIntFloat converter = new UIntFloat + { + floatValue = value + }; + writer.WriteUInt32(converter.intValue); + } + + public static void WriteDouble(this NetworkWriter writer, double value) + { + UIntDouble converter = new UIntDouble + { + doubleValue = value + }; + writer.WriteUInt64(converter.longValue); + } + + public static void WriteDecimal(this NetworkWriter writer, decimal value) + { + // the only way to read it without allocations is to both read and + // write it with the FloatConverter (which is not binary compatible + // to writer.Write(decimal), hence why we use it here too) + UIntDecimal converter = new UIntDecimal + { + decimalValue = value + }; + writer.WriteUInt64(converter.longValue1); + writer.WriteUInt64(converter.longValue2); + } + + 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.WriteUInt16((ushort)0); + return; + } + + // write string with same method as NetworkReader + // convert to byte[] + int size = encoding.GetBytes(value, 0, value.Length, stringBuffer, 0); + + // check if within max size + if (size >= NetworkWriter.MaxStringLength) + { + throw new IndexOutOfRangeException("NetworkWriter.Write(string) too long: " + size + ". Limit: " + NetworkWriter.MaxStringLength); + } + + // write size and bytes + writer.WriteUInt16(checked((ushort)(size + 1))); + writer.WriteBytes(stringBuffer, 0, size); + } + + // 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 bandwith + // (using size=-1 for null would limit max size to 32kb instead of 64kb) + if (buffer == null) + { + writer.WritePackedUInt32(0u); + return; + } + writer.WritePackedUInt32(checked((uint)count) + 1u); + writer.WriteBytes(buffer, offset, count); + } + + // 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); + } + + public static void WriteBytesAndSizeSegment(this NetworkWriter writer, ArraySegment buffer) + { + writer.WriteBytesAndSize(buffer.Array, buffer.Offset, buffer.Count); + } + + // zigzag encoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba + public static void WritePackedInt32(this NetworkWriter writer, int i) + { + uint zigzagged = (uint)((i >> 31) ^ (i << 1)); + writer.WritePackedUInt32(zigzagged); + } + + // http://sqlite.org/src4/doc/trunk/www/varint.wiki + public static void WritePackedUInt32(this NetworkWriter writer, uint value) + { + // for 32 bit values WritePackedUInt64 writes the + // same exact thing bit by bit + writer.WritePackedUInt64(value); + } + + // zigzag encoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba + public static void WritePackedInt64(this NetworkWriter writer, long i) + { + ulong zigzagged = (ulong)((i >> 63) ^ (i << 1)); + writer.WritePackedUInt64(zigzagged); + } + + public static void WritePackedUInt64(this NetworkWriter writer, ulong value) + { + 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)); + } + } + + public static void WriteVector2(this NetworkWriter writer, Vector2 value) + { + writer.WriteSingle(value.x); + writer.WriteSingle(value.y); + } + + public static void WriteVector3(this NetworkWriter writer, Vector3 value) + { + writer.WriteSingle(value.x); + writer.WriteSingle(value.y); + writer.WriteSingle(value.z); + } + + public static void WriteVector4(this NetworkWriter writer, Vector4 value) + { + writer.WriteSingle(value.x); + writer.WriteSingle(value.y); + writer.WriteSingle(value.z); + writer.WriteSingle(value.w); + } + + public static void WriteVector2Int(this NetworkWriter writer, Vector2Int value) + { + writer.WritePackedInt32(value.x); + writer.WritePackedInt32(value.y); + } + + public static void WriteVector3Int(this NetworkWriter writer, Vector3Int value) + { + writer.WritePackedInt32(value.x); + writer.WritePackedInt32(value.y); + writer.WritePackedInt32(value.z); + } + + public static void WriteColor(this NetworkWriter writer, Color value) + { + writer.WriteSingle(value.r); + writer.WriteSingle(value.g); + writer.WriteSingle(value.b); + writer.WriteSingle(value.a); + } + + public static void WriteColor32(this NetworkWriter writer, Color32 value) + { + writer.WriteByte(value.r); + writer.WriteByte(value.g); + writer.WriteByte(value.b); + writer.WriteByte(value.a); + } + + public static void WriteQuaternion(this NetworkWriter writer, Quaternion value) + { + writer.WriteSingle(value.x); + writer.WriteSingle(value.y); + writer.WriteSingle(value.z); + writer.WriteSingle(value.w); + } + + public static void WriteRect(this NetworkWriter writer, Rect value) + { + writer.WriteSingle(value.xMin); + writer.WriteSingle(value.yMin); + writer.WriteSingle(value.width); + writer.WriteSingle(value.height); + } + + public static void WritePlane(this NetworkWriter writer, Plane value) + { + writer.WriteVector3(value.normal); + writer.WriteSingle(value.distance); + } + + public static void WriteRay(this NetworkWriter writer, Ray value) + { + writer.WriteVector3(value.origin); + writer.WriteVector3(value.direction); + } + + public static void WriteMatrix4x4(this NetworkWriter writer, Matrix4x4 value) + { + writer.WriteSingle(value.m00); + writer.WriteSingle(value.m01); + writer.WriteSingle(value.m02); + writer.WriteSingle(value.m03); + writer.WriteSingle(value.m10); + writer.WriteSingle(value.m11); + writer.WriteSingle(value.m12); + writer.WriteSingle(value.m13); + writer.WriteSingle(value.m20); + writer.WriteSingle(value.m21); + writer.WriteSingle(value.m22); + writer.WriteSingle(value.m23); + writer.WriteSingle(value.m30); + writer.WriteSingle(value.m31); + writer.WriteSingle(value.m32); + writer.WriteSingle(value.m33); + } + + public static void WriteGuid(this NetworkWriter writer, Guid value) + { + byte[] data = value.ToByteArray(); + writer.WriteBytes(data, 0, data.Length); + } + + public static void WriteNetworkIdentity(this NetworkWriter writer, NetworkIdentity value) + { + if (value == null) + { + writer.WritePackedUInt32(0); + return; + } + writer.WritePackedUInt32(value.netId); + } + + public static void WriteTransform(this NetworkWriter writer, Transform value) + { + if (value == null || value.gameObject == null) + { + writer.WritePackedUInt32(0); + return; + } + NetworkIdentity identity = value.GetComponent(); + if (identity != null) + { + writer.WritePackedUInt32(identity.netId); + } + else + { + Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity"); + writer.WritePackedUInt32(0); + } + } + + public static void WriteGameObject(this NetworkWriter writer, GameObject value) + { + if (value == null) + { + writer.WritePackedUInt32(0); + return; + } + NetworkIdentity identity = value.GetComponent(); + if (identity != null) + { + writer.WritePackedUInt32(identity.netId); + } + else + { + Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity"); + writer.WritePackedUInt32(0); + } + } + + public static void Write(this NetworkWriter writer, T msg) where T : IMessageBase + { + msg.Serialize(writer); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/NetworkWriter.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkWriter.cs.meta new file mode 100644 index 0000000..240f74a --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 48d2207bcef1f4477b624725f075f9bd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/NetworkWriterPool.cs b/Assets/Packages/Mirror/Runtime/NetworkWriterPool.cs new file mode 100644 index 0000000..b3a32a5 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkWriterPool.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; + +namespace Mirror +{ + + public static class NetworkWriterPool + { + static readonly Stack pool = new Stack(); + + public static NetworkWriter GetWriter() + { + if (pool.Count != 0) + { + NetworkWriter writer = pool.Pop(); + // reset cached writer length and position + writer.SetLength(0); + return writer; + } + + return new NetworkWriter(); + } + + public static void Recycle(NetworkWriter writer) + { + pool.Push(writer); + } + } +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/NetworkWriterPool.cs.meta b/Assets/Packages/Mirror/Runtime/NetworkWriterPool.cs.meta new file mode 100644 index 0000000..d383901 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/NetworkWriterPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3f34b53bea38e4f259eb8dc211e4fdb6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/StringHash.cs b/Assets/Packages/Mirror/Runtime/StringHash.cs new file mode 100644 index 0000000..95e9b07 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/StringHash.cs @@ -0,0 +1,18 @@ +namespace Mirror +{ + public static class StringHash + { + // string.GetHashCode is not guaranteed to be the same on all machines, but + // we need one that is the same on all machines. simple and stupid: + public static int GetStableHashCode(this string text) + { + unchecked + { + int hash = 23; + foreach (char c in text) + hash = hash * 31 + c; + return hash; + } + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/StringHash.cs.meta b/Assets/Packages/Mirror/Runtime/StringHash.cs.meta new file mode 100644 index 0000000..6198581 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/StringHash.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 733f020f9b76d453da841089579fd7a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/SyncDictionary.cs b/Assets/Packages/Mirror/Runtime/SyncDictionary.cs new file mode 100644 index 0000000..930b8e5 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/SyncDictionary.cs @@ -0,0 +1,308 @@ +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; + +namespace Mirror +{ + [EditorBrowsable(EditorBrowsableState.Never)] + public abstract class SyncDictionary : IDictionary, SyncObject + { + public delegate void SyncDictionaryChanged(Operation op, TKey key, TValue item); + + readonly IDictionary objects; + + public int Count => objects.Count; + public bool IsReadOnly { get; private set; } + public event SyncDictionaryChanged Callback; + + public enum Operation : byte + { + OP_ADD, + OP_CLEAR, + OP_REMOVE, + OP_SET, + OP_DIRTY + } + + struct Change + { + internal Operation operation; + internal TKey key; + internal TValue item; + } + + 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; + + protected virtual void SerializeKey(NetworkWriter writer, TKey item) { } + protected virtual void SerializeItem(NetworkWriter writer, TValue item) { } + protected virtual TKey DeserializeKey(NetworkReader reader) => default; + protected virtual TValue DeserializeItem(NetworkReader reader) => default; + + public bool IsDirty => changes.Count > 0; + + public ICollection Keys => objects.Keys; + + public ICollection Values => objects.Values; + + // throw away all the changes + // this should be called after a successfull sync + public void Flush() => changes.Clear(); + + protected SyncDictionary() + { + objects = new Dictionary(); + } + + protected SyncDictionary(IEqualityComparer eq) + { + objects = new Dictionary(eq); + } + + protected SyncDictionary(IDictionary objects) + { + this.objects = objects; + } + + void AddOperation(Operation op, TKey key, TValue item) + { + if (IsReadOnly) + { + throw new System.InvalidOperationException("SyncDictionaries can only be modified by the server"); + } + + Change change = new Change + { + operation = op, + key = key, + item = item + }; + + changes.Add(change); + + Callback?.Invoke(op, key, item); + } + + public void OnSerializeAll(NetworkWriter writer) + { + // if init, write the full list content + writer.WritePackedUInt32((uint)objects.Count); + + foreach (KeyValuePair syncItem in objects) + { + SerializeKey(writer, syncItem.Key); + SerializeItem(writer, 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.WritePackedUInt32((uint)changes.Count); + } + + public void OnSerializeDelta(NetworkWriter writer) + { + // write all the queued up changes + writer.WritePackedUInt32((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_REMOVE: + case Operation.OP_SET: + case Operation.OP_DIRTY: + SerializeKey(writer, change.key); + SerializeItem(writer, change.item); + break; + case Operation.OP_CLEAR: + break; + } + } + } + + public void OnDeserializeAll(NetworkReader reader) + { + // This list can now only be modified by synchronization + IsReadOnly = true; + + // if init, write the full list content + int count = (int)reader.ReadPackedUInt32(); + + objects.Clear(); + changes.Clear(); + + for (int i = 0; i < count; i++) + { + TKey key = DeserializeKey(reader); + TValue obj = DeserializeItem(reader); + 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.ReadPackedUInt32(); + } + + public void OnDeserializeDelta(NetworkReader reader) + { + // This list can now only be modified by synchronization + IsReadOnly = true; + + int changesCount = (int)reader.ReadPackedUInt32(); + + 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: + case Operation.OP_DIRTY: + key = DeserializeKey(reader); + item = DeserializeItem(reader); + if (apply) + { + objects[key] = item; + } + break; + + case Operation.OP_CLEAR: + if (apply) + { + objects.Clear(); + } + break; + + case Operation.OP_REMOVE: + key = DeserializeKey(reader); + item = DeserializeItem(reader); + if (apply) + { + objects.Remove(key); + } + break; + } + + if (apply) + { + Callback?.Invoke(operation, key, item); + } + // we just skipped this change + else + { + changesAhead--; + } + } + } + + public void Clear() + { + objects.Clear(); + AddOperation(Operation.OP_CLEAR, default, default); + } + + public bool ContainsKey(TKey key) => objects.ContainsKey(key); + + public bool Remove(TKey key) + { + if (objects.TryGetValue(key, out TValue item) && objects.Remove(key)) + { + AddOperation(Operation.OP_REMOVE, key, item); + return true; + } + return false; + } + + public void Dirty(TKey index) + { + AddOperation(Operation.OP_DIRTY, index, objects[index]); + } + + public TValue this[TKey i] + { + get => objects[i]; + set + { + if (ContainsKey(i)) + { + AddOperation(Operation.OP_SET, i, value); + } + else + { + AddOperation(Operation.OP_ADD, i, value); + } + objects[i] = value; + } + } + + public bool TryGetValue(TKey key, out TValue value) => objects.TryGetValue(key, out value); + + public void Add(TKey key, TValue value) + { + objects.Add(key, value); + AddOperation(Operation.OP_ADD, key, value); + } + + public void Add(KeyValuePair item) => Add(item.Key, item.Value); + + public bool Contains(KeyValuePair item) + { + return TryGetValue(item.Key, out TValue val) && EqualityComparer.Default.Equals(val, item.Value); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + if (array == null) + { + throw new System.ArgumentNullException("Array Is Null"); + } + if (arrayIndex < 0 || arrayIndex > array.Length) + { + throw new System.ArgumentOutOfRangeException("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 bool Remove(KeyValuePair item) + { + bool result = objects.Remove(item.Key); + if (result) + { + AddOperation(Operation.OP_REMOVE, item.Key, item.Value); + } + return result; + } + + public IEnumerator> GetEnumerator() => ((IDictionary)objects).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => ((IDictionary)objects).GetEnumerator(); + } +} diff --git a/Assets/Packages/Mirror/Runtime/SyncDictionary.cs.meta b/Assets/Packages/Mirror/Runtime/SyncDictionary.cs.meta new file mode 100644 index 0000000..9b4ff53 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/SyncDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4b346c49cfdb668488a364c3023590e2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/SyncList.cs b/Assets/Packages/Mirror/Runtime/SyncList.cs new file mode 100644 index 0000000..83ddc02 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/SyncList.cs @@ -0,0 +1,353 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; + +namespace Mirror +{ + public class SyncListString : SyncList + { + protected override void SerializeItem(NetworkWriter writer, string item) => writer.WriteString(item); + protected override string DeserializeItem(NetworkReader reader) => reader.ReadString(); + } + + public class SyncListFloat : SyncList + { + protected override void SerializeItem(NetworkWriter writer, float item) => writer.WriteSingle(item); + protected override float DeserializeItem(NetworkReader reader) => reader.ReadSingle(); + } + + public class SyncListInt : SyncList + { + protected override void SerializeItem(NetworkWriter writer, int item) => writer.WritePackedInt32(item); + protected override int DeserializeItem(NetworkReader reader) => reader.ReadPackedInt32(); + } + + public class SyncListUInt : SyncList + { + protected override void SerializeItem(NetworkWriter writer, uint item) => writer.WritePackedUInt32(item); + protected override uint DeserializeItem(NetworkReader reader) => reader.ReadPackedUInt32(); + } + + public class SyncListBool : SyncList + { + protected override void SerializeItem(NetworkWriter writer, bool item) => writer.WriteBoolean(item); + protected override bool DeserializeItem(NetworkReader reader) => reader.ReadBoolean(); + } + + // Original UNET name is SyncListStruct and original Weaver weavers anything + // that contains the name 'SyncListStruct', without considering the name- + // space. + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use SyncList instead")] + public class SyncListSTRUCT : SyncList where T : struct + { + public T GetItem(int i) => base[i]; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public abstract class SyncList : IList, IReadOnlyList, SyncObject + { + public delegate void SyncListChanged(Operation op, int itemIndex, T item); + + readonly IList objects; + + public int Count => objects.Count; + public bool IsReadOnly { get; private set; } + public event SyncListChanged Callback; + + public enum Operation : byte + { + OP_ADD, + OP_CLEAR, + OP_INSERT, + OP_REMOVE, + OP_REMOVEAT, + OP_SET, + OP_DIRTY + } + + struct Change + { + internal Operation operation; + internal int index; + internal T item; + } + + 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; + + protected virtual void SerializeItem(NetworkWriter writer, T item) { } + protected virtual T DeserializeItem(NetworkReader reader) => default; + + + protected SyncList() + { + objects = new List(); + } + + protected SyncList(IList objects) + { + this.objects = objects; + } + + public bool IsDirty => changes.Count > 0; + + // throw away all the changes + // this should be called after a successfull sync + public void Flush() => changes.Clear(); + + void AddOperation(Operation op, int itemIndex, T item) + { + if (IsReadOnly) + { + throw new InvalidOperationException("Synclists can only be modified at the server"); + } + + Change change = new Change + { + operation = op, + index = itemIndex, + item = item + }; + + changes.Add(change); + + Callback?.Invoke(op, itemIndex, item); + } + + void AddOperation(Operation op, int itemIndex) => AddOperation(op, itemIndex, default); + + public void OnSerializeAll(NetworkWriter writer) + { + // if init, write the full list content + writer.WritePackedUInt32((uint)objects.Count); + + for (int i = 0; i < objects.Count; i++) + { + T obj = objects[i]; + SerializeItem(writer, 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.WritePackedUInt32((uint)changes.Count); + } + + public void OnSerializeDelta(NetworkWriter writer) + { + // write all the queued up changes + writer.WritePackedUInt32((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_REMOVE: + SerializeItem(writer, change.item); + break; + + case Operation.OP_CLEAR: + break; + + case Operation.OP_REMOVEAT: + writer.WritePackedUInt32((uint)change.index); + break; + + case Operation.OP_INSERT: + case Operation.OP_SET: + case Operation.OP_DIRTY: + writer.WritePackedUInt32((uint)change.index); + SerializeItem(writer, change.item); + break; + } + } + } + + public void OnDeserializeAll(NetworkReader reader) + { + // This list can now only be modified by synchronization + IsReadOnly = true; + + // if init, write the full list content + int count = (int)reader.ReadPackedUInt32(); + + objects.Clear(); + changes.Clear(); + + for (int i = 0; i < count; i++) + { + T obj = DeserializeItem(reader); + 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.ReadPackedUInt32(); + } + + public void OnDeserializeDelta(NetworkReader reader) + { + // This list can now only be modified by synchronization + IsReadOnly = true; + + int changesCount = (int)reader.ReadPackedUInt32(); + + 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 item = default; + + switch (operation) + { + case Operation.OP_ADD: + item = DeserializeItem(reader); + if (apply) + { + index = objects.Count; + objects.Add(item); + } + break; + + case Operation.OP_CLEAR: + if (apply) + { + objects.Clear(); + } + break; + + case Operation.OP_INSERT: + index = (int)reader.ReadPackedUInt32(); + item = DeserializeItem(reader); + if (apply) + { + objects.Insert(index, item); + } + break; + + case Operation.OP_REMOVE: + item = DeserializeItem(reader); + if (apply) + { + objects.Remove(item); + } + break; + + case Operation.OP_REMOVEAT: + index = (int)reader.ReadPackedUInt32(); + if (apply) + { + item = objects[index]; + objects.RemoveAt(index); + } + break; + + case Operation.OP_SET: + case Operation.OP_DIRTY: + index = (int)reader.ReadPackedUInt32(); + item = DeserializeItem(reader); + if (apply) + { + objects[index] = item; + } + break; + } + + if (apply) + { + Callback?.Invoke(operation, index, item); + } + // we just skipped this change + else + { + changesAhead--; + } + } + } + + public void Add(T item) + { + objects.Add(item); + AddOperation(Operation.OP_ADD, objects.Count - 1, item); + } + + public void Clear() + { + objects.Clear(); + AddOperation(Operation.OP_CLEAR, 0); + } + + public bool Contains(T item) => objects.Contains(item); + + public void CopyTo(T[] array, int index) => objects.CopyTo(array, index); + + public int IndexOf(T item) => objects.IndexOf(item); + + public int FindIndex(Predicate match) + { + for (int i = 0; i < objects.Count; ++i) + if (match(objects[i])) + return i; + return -1; + } + + public void Insert(int index, T item) + { + objects.Insert(index, item); + AddOperation(Operation.OP_INSERT, index, item); + } + + public bool Remove(T item) + { + bool result = objects.Remove(item); + if (result) + { + AddOperation(Operation.OP_REMOVE, 0, item); + } + return result; + } + + public void RemoveAt(int index) + { + objects.RemoveAt(index); + AddOperation(Operation.OP_REMOVEAT, index); + } + + public void Dirty(int index) + { + AddOperation(Operation.OP_DIRTY, index, objects[index]); + } + + public T this[int i] + { + get => objects[i]; + set + { + if (!EqualityComparer.Default.Equals(objects[i], value)) + { + objects[i] = value; + AddOperation(Operation.OP_SET, i, value); + } + } + } + + public IEnumerator GetEnumerator() => objects.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } +} diff --git a/Assets/Packages/Mirror/Runtime/SyncList.cs.meta b/Assets/Packages/Mirror/Runtime/SyncList.cs.meta new file mode 100644 index 0000000..9b9387d --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/SyncList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 744fc71f748fe40d5940e04bf42b29f3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/SyncObject.cs b/Assets/Packages/Mirror/Runtime/SyncObject.cs new file mode 100644 index 0000000..afaa508 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/SyncObject.cs @@ -0,0 +1,26 @@ +namespace Mirror +{ + // A sync object is an object that can synchronize it's state + // between server and client, such as a SyncList + public interface SyncObject + { + // true if there are changes since the last flush + bool IsDirty { get; } + + // Discard all the queued changes + // Consider the object fully synchronized with clients + void Flush(); + + // Write a full copy of the object + void OnSerializeAll(NetworkWriter writer); + + // Write the changes made to the object + void OnSerializeDelta(NetworkWriter writer); + + // deserialize all the data in the object + void OnDeserializeAll(NetworkReader reader); + + // deserialize changes since last sync + void OnDeserializeDelta(NetworkReader reader); + } +} diff --git a/Assets/Packages/Mirror/Runtime/SyncObject.cs.meta b/Assets/Packages/Mirror/Runtime/SyncObject.cs.meta new file mode 100644 index 0000000..a67485d --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/SyncObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae226d17a0c844041aa24cc2c023dd49 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/SyncSet.cs b/Assets/Packages/Mirror/Runtime/SyncSet.cs new file mode 100644 index 0000000..0a06352 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/SyncSet.cs @@ -0,0 +1,330 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; + +namespace Mirror +{ + + [EditorBrowsable(EditorBrowsableState.Never)] + public abstract class SyncSet : ISet, SyncObject + { + public delegate void SyncSetChanged(Operation op, T item); + + readonly ISet objects; + + public int Count => objects.Count; + public bool IsReadOnly { get; private set; } + public event SyncSetChanged Callback; + + public enum Operation : byte + { + OP_ADD, + OP_CLEAR, + OP_REMOVE + } + + struct Change + { + internal Operation operation; + internal T item; + } + + 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; + + protected SyncSet(ISet objects) + { + this.objects = objects; + } + + protected virtual void SerializeItem(NetworkWriter writer, T item) { } + protected virtual T DeserializeItem(NetworkReader reader) => default; + + public bool IsDirty => changes.Count > 0; + + // throw away all the changes + // this should be called after a successfull sync + public void Flush() => changes.Clear(); + + void AddOperation(Operation op, T item) + { + if (IsReadOnly) + { + throw new InvalidOperationException("SyncSets can only be modified at the server"); + } + + Change change = new Change + { + operation = op, + item = item + }; + + changes.Add(change); + + Callback?.Invoke(op, item); + } + + void AddOperation(Operation op) => AddOperation(op, default); + + public void OnSerializeAll(NetworkWriter writer) + { + // if init, write the full list content + writer.WritePackedUInt32((uint)objects.Count); + + foreach (T obj in objects) + { + SerializeItem(writer, 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.WritePackedUInt32((uint)changes.Count); + } + + public void OnSerializeDelta(NetworkWriter writer) + { + // write all the queued up changes + writer.WritePackedUInt32((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: + SerializeItem(writer, change.item); + break; + + case Operation.OP_CLEAR: + break; + + case Operation.OP_REMOVE: + SerializeItem(writer, change.item); + break; + } + } + } + + public void OnDeserializeAll(NetworkReader reader) + { + // This list can now only be modified by synchronization + IsReadOnly = true; + + // if init, write the full list content + int count = (int)reader.ReadPackedUInt32(); + + objects.Clear(); + changes.Clear(); + + for (int i = 0; i < count; i++) + { + T obj = DeserializeItem(reader); + 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.ReadPackedUInt32(); + } + + public void OnDeserializeDelta(NetworkReader reader) + { + // This list can now only be modified by synchronization + IsReadOnly = true; + + int changesCount = (int)reader.ReadPackedUInt32(); + + 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 item = default; + + switch (operation) + { + case Operation.OP_ADD: + item = DeserializeItem(reader); + if (apply) + { + objects.Add(item); + } + break; + + case Operation.OP_CLEAR: + if (apply) + { + objects.Clear(); + } + break; + + case Operation.OP_REMOVE: + item = DeserializeItem(reader); + if (apply) + { + objects.Remove(item); + } + break; + } + + if (apply) + { + Callback?.Invoke(operation, item); + } + // we just skipped this change + else + { + changesAhead--; + } + } + } + + public bool Add(T item) + { + if (objects.Add(item)) + { + AddOperation(Operation.OP_ADD, item); + return true; + } + return false; + } + + void ICollection.Add(T item) + { + if (objects.Add(item)) + { + AddOperation(Operation.OP_ADD, item); + } + } + + public void Clear() + { + objects.Clear(); + AddOperation(Operation.OP_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); + 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); + + public void SymmetricExceptWith(IEnumerable other) + { + if (other == this) + { + Clear(); + } + else + { + foreach (T element in other) + { + if (!Remove(element)) + { + Add(element); + } + } + } + } + + public void UnionWith(IEnumerable other) + { + if (other != this) + { + foreach (T element in other) + { + Add(element); + } + } + } + } + + public abstract class SyncHashSet : SyncSet + { + protected SyncHashSet() : base(new HashSet()) { } + } + + public abstract class SyncSortedSet : SyncSet + { + protected SyncSortedSet() : base(new SortedSet()) { } + + protected SyncSortedSet(IComparer comparer) : base(new SortedSet(comparer)) { } + } +} diff --git a/Assets/Packages/Mirror/Runtime/SyncSet.cs.meta b/Assets/Packages/Mirror/Runtime/SyncSet.cs.meta new file mode 100644 index 0000000..173523c --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/SyncSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8a31599d9f9dd4ef9999f7b9707c832c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport.meta b/Assets/Packages/Mirror/Runtime/Transport.meta new file mode 100644 index 0000000..fc29442 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7825d46cd73fe47938869eb5427b40fa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/LLAPITransport.cs b/Assets/Packages/Mirror/Runtime/Transport/LLAPITransport.cs new file mode 100644 index 0000000..bb6cfd8 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/LLAPITransport.cs @@ -0,0 +1,323 @@ +// Coburn: LLAPI is not available on UWP. There are a lot of compile directives here that we're checking against. +// Checking all of them may be overkill, but it's better to cover all the possible UWP directives. Sourced from +// https://docs.unity3d.com/Manual/PlatformDependentCompilation.html +// TODO: Check if LLAPI is supported on Xbox One? + +// LLAPITransport wraps UNET's LLAPI for use as a HLAPI TransportLayer, only if you're not on a UWP platform. +#if !(UNITY_WSA || UNITY_WSA_10_0 || UNITY_WINRT || UNITY_WINRT_10_0 || NETFX_CORE) + +using System; +using System.ComponentModel; +using UnityEngine; +using UnityEngine.Networking; +using UnityEngine.Networking.Types; + +namespace Mirror +{ + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("LLAPI is obsolete and will be removed from future versions of Unity")] + public class LLAPITransport : Transport + { + public ushort port = 7777; + + [Tooltip("Enable for WebGL games. Can only do either WebSockets or regular Sockets, not both (yet).")] + public bool useWebsockets; + + // settings copied from uMMORPG configuration for best results + public ConnectionConfig connectionConfig = new ConnectionConfig + { + PacketSize = 1500, + FragmentSize = 500, + ResendTimeout = 1200, + DisconnectTimeout = 6000, + ConnectTimeout = 6000, + MinUpdateTimeout = 1, + PingTimeout = 2000, + ReducedPingTimeout = 100, + AllCostTimeout = 20, + NetworkDropThreshold = 80, + OverflowDropThreshold = 80, + MaxConnectionAttempt = 10, + AckDelay = 33, + SendDelay = 10, + MaxCombinedReliableMessageSize = 100, + MaxCombinedReliableMessageCount = 10, + MaxSentMessageQueueSize = 512, + AcksType = ConnectionAcksType.Acks128, + InitialBandwidth = 0, + BandwidthPeakFactor = 2, + WebSocketReceiveBufferMaxSize = 0, + UdpSocketReceiveBufferMaxSize = 0 + }; + + // settings copied from uMMORPG configuration for best results + public GlobalConfig globalConfig = new GlobalConfig + { + ReactorModel = ReactorModel.SelectReactor, + ThreadAwakeTimeout = 1, + ReactorMaximumSentMessages = 4096, + ReactorMaximumReceivedMessages = 4096, + MaxPacketSize = 2000, + MaxHosts = 16, + ThreadPoolSize = 3, + MinTimerTimeout = 1, + MaxTimerTimeout = 12000 + }; + + readonly int channelId; // always use first channel + byte error; + + int clientId = -1; + int clientConnectionId = -1; + readonly byte[] clientReceiveBuffer = new byte[4096]; + + int serverHostId = -1; + readonly byte[] serverReceiveBuffer = new byte[4096]; + + void OnValidate() + { + // add connectionconfig channels if none + if (connectionConfig.Channels.Count == 0) + { + // channel 0 is reliable fragmented sequenced + connectionConfig.AddChannel(QosType.ReliableFragmentedSequenced); + // channel 1 is unreliable + connectionConfig.AddChannel(QosType.Unreliable); + } + } + + void Awake() + { + NetworkTransport.Init(globalConfig); + Debug.Log("LLAPITransport initialized!"); + } + + #region client + public override bool ClientConnected() + { + return clientConnectionId != -1; + } + + public override void ClientConnect(string address) + { + // LLAPI can't handle 'localhost' + if (address.ToLower() == "localhost") address = "127.0.0.1"; + + HostTopology hostTopology = new HostTopology(connectionConfig, 1); + + // important: + // AddHost(topology) doesn't work in WebGL. + // AddHost(topology, port) works in standalone and webgl if port=0 + clientId = NetworkTransport.AddHost(hostTopology, 0); + + clientConnectionId = NetworkTransport.Connect(clientId, address, port, 0, out error); + NetworkError networkError = (NetworkError)error; + if (networkError != NetworkError.Ok) + { + Debug.LogWarning("NetworkTransport.Connect failed: clientId=" + clientId + " address= " + address + " port=" + port + " error=" + error); + clientConnectionId = -1; + } + } + + public override bool ClientSend(int channelId, byte[] data) + { + return NetworkTransport.Send(clientId, clientConnectionId, channelId, data, data.Length, out error); + } + + public bool ProcessClientMessage() + { + if (clientId == -1) return false; + + NetworkEventType networkEvent = NetworkTransport.ReceiveFromHost(clientId, out int connectionId, out int channel, clientReceiveBuffer, clientReceiveBuffer.Length, out int receivedSize, out error); + + // note: 'error' is used for extra information, e.g. the reason for + // a disconnect. we don't necessarily have to throw an error if + // error != 0. but let's log it for easier debugging. + // + // DO NOT return after error != 0. otherwise Disconnect won't be + // registered. + NetworkError networkError = (NetworkError)error; + if (networkError != NetworkError.Ok) + { + string message = "NetworkTransport.Receive failed: hostid=" + clientId + " connId=" + connectionId + " channelId=" + channel + " error=" + networkError; + OnClientError.Invoke(new Exception(message)); + } + + // raise events + switch (networkEvent) + { + case NetworkEventType.ConnectEvent: + OnClientConnected.Invoke(); + break; + case NetworkEventType.DataEvent: + ArraySegment data = new ArraySegment(clientReceiveBuffer, 0, receivedSize); + OnClientDataReceived.Invoke(data); + break; + case NetworkEventType.DisconnectEvent: + OnClientDisconnected.Invoke(); + break; + default: + return false; + } + + return true; + } + + public string ClientGetAddress() + { + NetworkTransport.GetConnectionInfo(serverHostId, clientId, out string address, out int port, out NetworkID networkId, out NodeID node, out error); + return address; + } + + public override void ClientDisconnect() + { + if (clientId != -1) + { + NetworkTransport.RemoveHost(clientId); + clientId = -1; + } + } + #endregion + + #region server + public override bool ServerActive() + { + return serverHostId != -1; + } + + public override void ServerStart() + { + if (useWebsockets) + { + HostTopology topology = new HostTopology(connectionConfig, ushort.MaxValue - 1); + serverHostId = NetworkTransport.AddWebsocketHost(topology, port); + //Debug.Log("LLAPITransport.ServerStartWebsockets port=" + port + " max=" + maxConnections + " hostid=" + serverHostId); + } + else + { + HostTopology topology = new HostTopology(connectionConfig, ushort.MaxValue - 1); + serverHostId = NetworkTransport.AddHost(topology, port); + //Debug.Log("LLAPITransport.ServerStart port=" + port + " max=" + maxConnections + " hostid=" + serverHostId); + } + } + + public override bool ServerSend(int connectionId, int channelId, byte[] data) + { + return NetworkTransport.Send(serverHostId, connectionId, channelId, data, data.Length, out error); + } + + public bool ProcessServerMessage() + { + if (serverHostId == -1) return false; + + NetworkEventType networkEvent = NetworkTransport.ReceiveFromHost(serverHostId, out int connectionId, out int channel, serverReceiveBuffer, serverReceiveBuffer.Length, out int receivedSize, out error); + + // note: 'error' is used for extra information, e.g. the reason for + // a disconnect. we don't necessarily have to throw an error if + // error != 0. but let's log it for easier debugging. + // + // DO NOT return after error != 0. otherwise Disconnect won't be + // registered. + NetworkError networkError = (NetworkError)error; + if (networkError != NetworkError.Ok) + { + string message = "NetworkTransport.Receive failed: hostid=" + serverHostId + " connId=" + connectionId + " channelId=" + channel + " error=" + networkError; + + // TODO write a TransportException or better + OnServerError.Invoke(connectionId, new Exception(message)); + } + + // LLAPI client sends keep alive messages (75-6C-6C) on channel=110. + // ignore all messages that aren't for our selected channel. + /*if (channel != channelId) + { + return false; + }*/ + + switch (networkEvent) + { + case NetworkEventType.ConnectEvent: + OnServerConnected.Invoke(connectionId); + break; + case NetworkEventType.DataEvent: + ArraySegment data = new ArraySegment(serverReceiveBuffer, 0, receivedSize); + OnServerDataReceived.Invoke(connectionId, data); + break; + case NetworkEventType.DisconnectEvent: + OnServerDisconnected.Invoke(connectionId); + break; + default: + // nothing or a message we don't recognize + return false; + } + + return true; + } + + public override bool ServerDisconnect(int connectionId) + { + return NetworkTransport.Disconnect(serverHostId, connectionId, out error); + } + + public override string ServerGetClientAddress(int connectionId) + { + NetworkTransport.GetConnectionInfo(serverHostId, connectionId, out string address, out int port, out NetworkID networkId, out NodeID node, out error); + return address; + } + + public override void ServerStop() + { + NetworkTransport.RemoveHost(serverHostId); + serverHostId = -1; + Debug.Log("LLAPITransport.ServerStop"); + } + #endregion + + #region common + // IMPORTANT: set script execution order to >1000 to call Transport's + // LateUpdate after all others. Fixes race condition where + // e.g. in uSurvival Transport would apply Cmds before + // ShoulderRotation.LateUpdate, resulting in projectile + // spawns at the point before shoulder rotation. + public void LateUpdate() + { + // process all messages + while (ProcessClientMessage()) {} + while (ProcessServerMessage()) {} + } + + public override bool Available() + { + // websocket is available in all platforms (including webgl) + return useWebsockets || base.Available(); + } + + public override void Shutdown() + { + NetworkTransport.Shutdown(); + serverHostId = -1; + clientConnectionId = -1; + Debug.Log("LLAPITransport.Shutdown"); + } + + public override int GetMaxPacketSize(int channelId) + { + return globalConfig.MaxPacketSize; + } + + public override string ToString() + { + if (ServerActive()) + { + return "LLAPI Server port: " + port; + } + else if (ClientConnected()) + { + string ip = ClientGetAddress(); + return "LLAPI Client ip: " + ip + " port: " + port; + } + return "LLAPI (inactive/disconnected)"; + } + #endregion + } +} +#endif diff --git a/Assets/Packages/Mirror/Runtime/Transport/LLAPITransport.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/LLAPITransport.cs.meta new file mode 100644 index 0000000..2ddc7da --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/LLAPITransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d333dcc8c7bd34f35896f5a9b4c9e759 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 1001 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/MultiplexTransport.cs b/Assets/Packages/Mirror/Runtime/Transport/MultiplexTransport.cs new file mode 100644 index 0000000..c59a6a1 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/MultiplexTransport.cs @@ -0,0 +1,191 @@ +using System; +using System.Linq; +using System.Text; +using UnityEngine; + +namespace Mirror +{ + // a transport that can listen to multiple underlying transport at the same time + public class MultiplexTransport : Transport + { + public Transport[] transports; + + public void Awake() + { + if (transports == null || transports.Length == 0) + { + Debug.LogError("Multiplex transport requires at least 1 underlying transport"); + } + InitClient(); + InitServer(); + } + + #region Client + // clients always pick the first transport + void InitClient() + { + // wire all the base transports to my events + foreach (Transport transport in transports) + { + transport.OnClientConnected.AddListener(OnClientConnected.Invoke ); + transport.OnClientDataReceived.AddListener(OnClientDataReceived.Invoke); + transport.OnClientError.AddListener(OnClientError.Invoke ); + transport.OnClientDisconnected.AddListener(OnClientDisconnected.Invoke); + } + } + + // The client just uses the first transport available + Transport GetAvailableTransport() + { + foreach (Transport transport in transports) + { + if (transport.Available()) + { + return transport; + } + } + throw new Exception("No transport suitable for this platform"); + } + + public override void ClientConnect(string address) + { + GetAvailableTransport().ClientConnect(address); + } + + public override bool ClientConnected() + { + return GetAvailableTransport().ClientConnected(); + } + + public override void ClientDisconnect() + { + GetAvailableTransport().ClientDisconnect(); + } + + public override bool ClientSend(int channelId, byte[] data) + { + return GetAvailableTransport().ClientSend(channelId, data); + } + + public override int GetMaxPacketSize(int channelId = 0) + { + return GetAvailableTransport().GetMaxPacketSize(channelId); + } + + #endregion + + + #region Server + // connection ids get mapped to base transports + // if we have 3 transports, then + // transport 0 will produce connection ids [0, 3, 6, 9, ...] + // transport 1 will produce connection ids [1, 4, 7, 10, ...] + // transport 2 will produce connection ids [2, 5, 8, 11, ...] + int FromBaseId(int transportId, int connectionId) + { + return connectionId * transports.Length + transportId; + } + + int ToBaseId(int connectionId) + { + return connectionId / transports.Length; + } + + int ToTransportId(int connectionId) + { + return connectionId % transports.Length; + } + + void InitServer() + { + // wire all the base transports to my events + for (int i = 0; i < transports.Length; i++) + { + // this is required for the handlers, if I use i directly + // then all the handlers will use the last i + int locali = i; + Transport transport = transports[i]; + + transport.OnServerConnected.AddListener(baseConnectionId => + { + OnServerConnected.Invoke(FromBaseId(locali, baseConnectionId)); + }); + + transport.OnServerDataReceived.AddListener((baseConnectionId, data) => + { + OnServerDataReceived.Invoke(FromBaseId(locali, baseConnectionId), data); + }); + + transport.OnServerError.AddListener((baseConnectionId, error) => + { + OnServerError.Invoke(FromBaseId(locali, baseConnectionId), error); + }); + transport.OnServerDisconnected.AddListener(baseConnectionId => + { + OnServerDisconnected.Invoke(FromBaseId(locali, baseConnectionId)); + }); + } + } + + public override bool ServerActive() + { + return transports.All(t => t.ServerActive()); + } + + public override string ServerGetClientAddress(int connectionId) + { + int baseConnectionId = ToBaseId(connectionId); + int transportId = ToTransportId(connectionId); + return transports[transportId].ServerGetClientAddress(baseConnectionId); + } + + public override bool ServerDisconnect(int connectionId) + { + int baseConnectionId = ToBaseId(connectionId); + int transportId = ToTransportId(connectionId); + return transports[transportId].ServerDisconnect(baseConnectionId); + } + + public override bool ServerSend(int connectionId, int channelId, byte[] data) + { + int baseConnectionId = ToBaseId(connectionId); + int transportId = ToTransportId(connectionId); + return transports[transportId].ServerSend(baseConnectionId, channelId, data); + } + + public override void ServerStart() + { + foreach (Transport transport in transports) + { + transport.ServerStart(); + } + } + + public override void ServerStop() + { + foreach (Transport transport in transports) + { + transport.ServerStop(); + } + } + #endregion + + public override void Shutdown() + { + foreach (Transport transport in transports) + { + transport.Shutdown(); + } + } + + public override string ToString() + { + StringBuilder builder = new StringBuilder(); + foreach (Transport transport in transports) + { + builder.AppendLine(transport.ToString()); + } + return builder.ToString().Trim(); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/MultiplexTransport.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/MultiplexTransport.cs.meta new file mode 100644 index 0000000..40394aa --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/MultiplexTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 929e3234c7db540b899f00183fc2b1fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy.meta new file mode 100644 index 0000000..ede2d0e --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 552b3d8382916438d81fe7f39e18db72 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Client.cs b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Client.cs new file mode 100644 index 0000000..50be684 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Client.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Concurrent; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace Telepathy +{ + public class Client : Common + { + public TcpClient client; + Thread receiveThread; + Thread sendThread; + + // TcpClient.Connected doesn't check if socket != null, which + // results in NullReferenceExceptions if connection was closed. + // -> let's check it manually instead + public bool Connected => client != null && + client.Client != null && + client.Client.Connected; + + // TcpClient has no 'connecting' state to check. We need to keep track + // of it manually. + // -> checking 'thread.IsAlive && !Connected' is not enough because the + // thread is alive and connected is false for a short moment after + // disconnecting, so this would cause race conditions. + // -> we use a threadsafe bool wrapper so that ThreadFunction can remain + // static (it needs a common lock) + // => Connecting is true from first Connect() call in here, through the + // thread start, until TcpClient.Connect() returns. Simple and clear. + // => bools are atomic according to + // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables + // made volatile so the compiler does not reorder access to it + volatile bool _Connecting; + public bool Connecting => _Connecting; + + // send queue + // => SafeQueue is twice as fast as ConcurrentQueue, see SafeQueue.cs! + SafeQueue sendQueue = new SafeQueue(); + + // ManualResetEvent to wake up the send thread. better than Thread.Sleep + // -> call Set() if everything was sent + // -> call Reset() if there is something to send again + // -> call WaitOne() to block until Reset was called + ManualResetEvent sendPending = new ManualResetEvent(false); + + // the thread function + void ReceiveThreadFunction(string ip, int port) + { + // absolutely must wrap with try/catch, otherwise thread + // exceptions are silent + try + { + // connect (blocking) + client.Connect(ip, port); + _Connecting = false; + + // set socket options after the socket was created in Connect() + // (not after the constructor because we clear the socket there) + client.NoDelay = NoDelay; + client.SendTimeout = SendTimeout; + + // start send thread only after connected + sendThread = new Thread(() => { SendLoop(0, client, sendQueue, sendPending); }); + sendThread.IsBackground = true; + sendThread.Start(); + + // run the receive loop + ReceiveLoop(0, client, receiveQueue, MaxMessageSize); + } + catch (SocketException exception) + { + // this happens if (for example) the ip address is correct + // but there is no server running on that ip/port + Logger.Log("Client Recv: failed to connect to ip=" + ip + " port=" + port + " reason=" + exception); + + // add 'Disconnected' event to message queue so that the caller + // knows that the Connect failed. otherwise they will never know + receiveQueue.Enqueue(new Message(0, EventType.Disconnected, null)); + } + catch (Exception exception) + { + // something went wrong. probably important. + Logger.LogError("Client Recv Exception: " + exception); + } + + // sendthread might be waiting on ManualResetEvent, + // so let's make sure to end it if the connection + // closed. + // otherwise the send thread would only end if it's + // actually sending data while the connection is + // closed. + sendThread?.Interrupt(); + + // Connect might have failed. thread might have been closed. + // let's reset connecting state no matter what. + _Connecting = false; + + // if we got here then we are done. ReceiveLoop cleans up already, + // but we may never get there if connect fails. so let's clean up + // here too. + client.Close(); + } + + public void Connect(string ip, int port) + { + // not if already started + if (Connecting || Connected) return; + + // We are connecting from now until Connect succeeds or fails + _Connecting = true; + + // create a TcpClient with perfect IPv4, IPv6 and hostname resolving + // support. + // + // * TcpClient(hostname, port): works but would connect (and block) + // already + // * TcpClient(AddressFamily.InterNetworkV6): takes Ipv4 and IPv6 + // addresses but only connects to IPv6 servers (e.g. Telepathy). + // does NOT connect to IPv4 servers (e.g. Mirror Booster), even + // with DualMode enabled. + // * TcpClient(): creates IPv4 socket internally, which would force + // Connect() to only use IPv4 sockets. + // + // => the trick is to clear the internal IPv4 socket so that Connect + // resolves the hostname and creates either an IPv4 or an IPv6 + // socket as needed (see TcpClient source) + client = new TcpClient(); // creates IPv4 socket + client.Client = null; // clear internal IPv4 socket until Connect() + + // clear old messages in queue, just to be sure that the caller + // doesn't receive data from last time and gets out of sync. + // -> calling this in Disconnect isn't smart because the caller may + // still want to process all the latest messages afterwards + receiveQueue = new ConcurrentQueue(); + sendQueue.Clear(); + + // client.Connect(ip, port) is blocking. let's call it in the thread + // and return immediately. + // -> this way the application doesn't hang for 30s if connect takes + // too long, which is especially good in games + // -> this way we don't async client.BeginConnect, which seems to + // fail sometimes if we connect too many clients too fast + receiveThread = new Thread(() => { ReceiveThreadFunction(ip, port); }); + receiveThread.IsBackground = true; + receiveThread.Start(); + } + + public void Disconnect() + { + // only if started + if (Connecting || Connected) + { + // close client + client.Close(); + + // wait until thread finished. this is the only way to guarantee + // that we can call Connect() again immediately after Disconnect + receiveThread?.Join(); + + // clear send queues. no need to hold on to them. + // (unlike receiveQueue, which is still needed to process the + // latest Disconnected message, etc.) + sendQueue.Clear(); + + // let go of this one completely. the thread ended, no one uses + // it anymore and this way Connected is false again immediately. + client = null; + } + } + + public bool Send(byte[] data) + { + if (Connected) + { + // respect max message size to avoid allocation attacks. + if (data.Length <= MaxMessageSize) + { + // add to send queue and return immediately. + // calling Send here would be blocking (sometimes for long times + // if other side lags or wire was disconnected) + sendQueue.Enqueue(data); + sendPending.Set(); // interrupt SendThread WaitOne() + return true; + } + Logger.LogError("Client.Send: message too big: " + data.Length + ". Limit: " + MaxMessageSize); + return false; + } + Logger.LogWarning("Client.Send: not connected!"); + return false; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Client.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Client.cs.meta new file mode 100644 index 0000000..1b6d222 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Client.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5b95294cc4ec4b15aacba57531c7985 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Common.cs b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Common.cs new file mode 100644 index 0000000..2d68162 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Common.cs @@ -0,0 +1,289 @@ +// common code used by server and client +using System; +using System.Collections.Concurrent; +using System.Net.Sockets; +using System.Threading; + +namespace Telepathy +{ + public abstract class Common + { + // common code ///////////////////////////////////////////////////////// + // incoming message queue of + // (not a HashSet because one connection can have multiple new messages) + protected ConcurrentQueue receiveQueue = new ConcurrentQueue(); + + // queue count, useful for debugging / benchmarks + public int ReceiveQueueCount => receiveQueue.Count; + + // warning if message queue gets too big + // if the average message is about 20 bytes then: + // - 1k messages are 20KB + // - 10k messages are 200KB + // - 100k messages are 1.95MB + // 2MB are not that much, but it is a bad sign if the caller process + // can't call GetNextMessage faster than the incoming messages. + public static int messageQueueSizeWarning = 100000; + + // removes and returns the oldest message from the message queue. + // (might want to call this until it doesn't return anything anymore) + // -> Connected, Data, Disconnected events are all added here + // -> bool return makes while (GetMessage(out Message)) easier! + // -> no 'is client connected' check because we still want to read the + // Disconnected message after a disconnect + public bool GetNextMessage(out Message message) + { + return receiveQueue.TryDequeue(out message); + } + + // NoDelay disables nagle algorithm. lowers CPU% and latency but + // increases bandwidth + public bool NoDelay = true; + + // Prevent allocation attacks. Each packet is prefixed with a length + // header, so an attacker could send a fake packet with length=2GB, + // causing the server to allocate 2GB and run out of memory quickly. + // -> simply increase max packet size if you want to send around bigger + // files! + // -> 16KB per message should be more than enough. + public int MaxMessageSize = 16 * 1024; + + // Send would stall forever if the network is cut off during a send, so + // we need a timeout (in milliseconds) + public int SendTimeout = 5000; + + // avoid header[4] allocations but don't use one buffer for all threads + [ThreadStatic] static byte[] header; + + // avoid payload[packetSize] allocations but don't use one buffer for + // all threads + [ThreadStatic] static byte[] payload; + + // static helper functions ///////////////////////////////////////////// + // send message (via stream) with the message structure + // this function is blocking sometimes! + // (e.g. if someone has high latency or wire was cut off) + protected static bool SendMessagesBlocking(NetworkStream stream, byte[][] messages) + { + // stream.Write throws exceptions if client sends with high + // frequency and the server stops + try + { + // we might have multiple pending messages. merge into one + // packet to avoid TCP overheads and improve performance. + int packetSize = 0; + for (int i = 0; i < messages.Length; ++i) + packetSize += sizeof(int) + messages[i].Length; // header + content + + // create payload buffer if not created yet or previous one is + // too small + // IMPORTANT: payload.Length might be > packetSize! don't use it! + if (payload == null || payload.Length < packetSize) + payload = new byte[packetSize]; + + // create the packet + int position = 0; + for (int i = 0; i < messages.Length; ++i) + { + // create header buffer if not created yet + if (header == null) + header = new byte[4]; + + // construct header (size) + Utils.IntToBytesBigEndianNonAlloc(messages[i].Length, header); + + // copy header + message into buffer + Array.Copy(header, 0, payload, position, header.Length); + Array.Copy(messages[i], 0, payload, position + header.Length, messages[i].Length); + position += header.Length + messages[i].Length; + } + + // write the whole thing + stream.Write(payload, 0, packetSize); + + return true; + } + catch (Exception exception) + { + // log as regular message because servers do shut down sometimes + Logger.Log("Send: stream.Write exception: " + exception); + return false; + } + } + + // read message (via stream) with the message structure + protected static bool ReadMessageBlocking(NetworkStream stream, int MaxMessageSize, out byte[] content) + { + content = null; + + // create header buffer if not created yet + if (header == null) + header = new byte[4]; + + // read exactly 4 bytes for header (blocking) + if (!stream.ReadExactly(header, 4)) + return false; + + // convert to int + int size = Utils.BytesToIntBigEndian(header); + + // protect against allocation attacks. an attacker might send + // multiple fake '2GB header' packets in a row, causing the server + // to allocate multiple 2GB byte arrays and run out of memory. + if (size <= MaxMessageSize) + { + // read exactly 'size' bytes for content (blocking) + content = new byte[size]; + return stream.ReadExactly(content, size); + } + Logger.LogWarning("ReadMessageBlocking: possible allocation attack with a header of: " + size + " bytes."); + return false; + } + + // thread receive function is the same for client and server's clients + // (static to reduce state for maximum reliability) + protected static void ReceiveLoop(int connectionId, TcpClient client, ConcurrentQueue receiveQueue, int MaxMessageSize) + { + // get NetworkStream from client + NetworkStream stream = client.GetStream(); + + // keep track of last message queue warning + DateTime messageQueueLastWarning = DateTime.Now; + + // absolutely must wrap with try/catch, otherwise thread exceptions + // are silent + try + { + // add connected event to queue with ip address as data in case + // it's needed + receiveQueue.Enqueue(new Message(connectionId, EventType.Connected, null)); + + // let's talk about reading data. + // -> normally we would read as much as possible and then + // extract as many , messages + // as we received this time. this is really complicated + // and expensive to do though + // -> instead we use a trick: + // Read(2) -> size + // Read(size) -> content + // repeat + // Read is blocking, but it doesn't matter since the + // best thing to do until the full message arrives, + // is to wait. + // => this is the most elegant AND fast solution. + // + no resizing + // + no extra allocations, just one for the content + // + no crazy extraction logic + while (true) + { + // read the next message (blocking) or stop if stream closed + byte[] content; + if (!ReadMessageBlocking(stream, MaxMessageSize, out content)) + break; // break instead of return so stream close still happens! + + // queue it + receiveQueue.Enqueue(new Message(connectionId, EventType.Data, content)); + + // and show a warning if the queue gets too big + // -> we don't want to show a warning every single time, + // because then a lot of processing power gets wasted on + // logging, which will make the queue pile up even more. + // -> instead we show it every 10s, so that the system can + // use most it's processing power to hopefully process it. + if (receiveQueue.Count > messageQueueSizeWarning) + { + TimeSpan elapsed = DateTime.Now - messageQueueLastWarning; + if (elapsed.TotalSeconds > 10) + { + Logger.LogWarning("ReceiveLoop: messageQueue is getting big(" + receiveQueue.Count + "), try calling GetNextMessage more often. You can call it more than once per frame!"); + messageQueueLastWarning = DateTime.Now; + } + } + } + } + catch (Exception exception) + { + // something went wrong. the thread was interrupted or the + // connection closed or we closed our own connection or ... + // -> either way we should stop gracefully + Logger.Log("ReceiveLoop: finished receive function for connectionId=" + connectionId + " reason: " + exception); + } + finally + { + // clean up no matter what + stream.Close(); + client.Close(); + + // add 'Disconnected' message after disconnecting properly. + // -> always AFTER closing the streams to avoid a race condition + // where Disconnected -> Reconnect wouldn't work because + // Connected is still true for a short moment before the stream + // would be closed. + receiveQueue.Enqueue(new Message(connectionId, EventType.Disconnected, null)); + } + } + + // thread send function + // note: we really do need one per connection, so that if one connection + // blocks, the rest will still continue to get sends + protected static void SendLoop(int connectionId, TcpClient client, SafeQueue sendQueue, ManualResetEvent sendPending) + { + // get NetworkStream from client + NetworkStream stream = client.GetStream(); + + try + { + while (client.Connected) // try this. client will get closed eventually. + { + // reset ManualResetEvent before we do anything else. this + // way there is no race condition. if Send() is called again + // while in here then it will be properly detected next time + // -> otherwise Send might be called right after dequeue but + // before .Reset, which would completely ignore it until + // the next Send call. + sendPending.Reset(); // WaitOne() blocks until .Set() again + + // dequeue all + // SafeQueue.TryDequeueAll is twice as fast as + // ConcurrentQueue, see SafeQueue.cs! + byte[][] messages; + if (sendQueue.TryDequeueAll(out messages)) + { + // send message (blocking) or stop if stream is closed + if (!SendMessagesBlocking(stream, messages)) + break; // break instead of return so stream close still happens! + } + + // don't choke up the CPU: wait until queue not empty anymore + sendPending.WaitOne(); + } + } + catch (ThreadAbortException) + { + // happens on stop. don't log anything. + } + catch (ThreadInterruptedException) + { + // happens if receive thread interrupts send thread. + } + catch (Exception exception) + { + // something went wrong. the thread was interrupted or the + // connection closed or we closed our own connection or ... + // -> either way we should stop gracefully + Logger.Log("SendLoop Exception: connectionId=" + connectionId + " reason: " + exception); + } + finally + { + // clean up no matter what + // we might get SocketExceptions when sending if the 'host has + // failed to respond' - in which case we should close the connection + // which causes the ReceiveLoop to end and fire the Disconnected + // message. otherwise the connection would stay alive forever even + // though we can't send anymore. + stream.Close(); + client.Close(); + } + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Common.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Common.cs.meta new file mode 100644 index 0000000..5d8ab5b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Common.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c4d56322cf0e248a89103c002a505dab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/EventType.cs b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/EventType.cs new file mode 100644 index 0000000..f07baf2 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/EventType.cs @@ -0,0 +1,9 @@ +namespace Telepathy +{ + public enum EventType + { + Connected, + Data, + Disconnected + } +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/EventType.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/EventType.cs.meta new file mode 100644 index 0000000..ac88c1b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/EventType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 49f1a330755814803be5f27f493e1910 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/LICENSE b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/LICENSE new file mode 100644 index 0000000..680deef --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018, vis2k + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/LICENSE.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/LICENSE.meta new file mode 100644 index 0000000..4d7664e --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/LICENSE.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0ba11103b95fd4721bffbb08440d5b8e +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Logger.cs b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Logger.cs new file mode 100644 index 0000000..e97704d --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Logger.cs @@ -0,0 +1,15 @@ +// A simple logger class that uses Console.WriteLine by default. +// Can also do Logger.LogMethod = Debug.Log for Unity etc. +// (this way we don't have to depend on UnityEngine.DLL and don't need a +// different version for every UnityEngine version here) +using System; + +namespace Telepathy +{ + public static class Logger + { + public static Action Log = Console.WriteLine; + public static Action LogWarning = Console.WriteLine; + public static Action LogError = Console.Error.WriteLine; + } +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Logger.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Logger.cs.meta new file mode 100644 index 0000000..304866f --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Logger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aa8d703f0b73f4d6398b76812719b68b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Message.cs b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Message.cs new file mode 100644 index 0000000..529a594 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Message.cs @@ -0,0 +1,18 @@ +// incoming message queue of +// (not a HashSet because one connection can have multiple new messages) +// -> a struct to minimize GC +namespace Telepathy +{ + public struct Message + { + public readonly int connectionId; + public readonly EventType eventType; + public readonly byte[] data; + public Message(int connectionId, EventType eventType, byte[] data) + { + this.connectionId = connectionId; + this.eventType = eventType; + this.data = data; + } + } +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Message.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Message.cs.meta new file mode 100644 index 0000000..5937bb9 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Message.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aedf812e9637b4f92a35db1aedca8c92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/NetworkStreamExtensions.cs b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/NetworkStreamExtensions.cs new file mode 100644 index 0000000..9b5bd4e --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/NetworkStreamExtensions.cs @@ -0,0 +1,55 @@ +using System.IO; +using System.Net.Sockets; + +public static class NetworkStreamExtensions +{ + // .Read returns '0' if remote closed the connection but throws an + // IOException if we voluntarily closed our own connection. + // + // let's add a ReadSafely method that returns '0' in both cases so we don't + // have to worry about exceptions, since a disconnect is a disconnect... + public static int ReadSafely(this NetworkStream stream, byte[] buffer, int offset, int size) + { + try + { + return stream.Read(buffer, offset, size); + } + catch (IOException) + { + return 0; + } + } + + // helper function to read EXACTLY 'n' bytes + // -> default .Read reads up to 'n' bytes. this function reads exactly 'n' + // bytes + // -> this is blocking until 'n' bytes were received + // -> immediately returns false in case of disconnects + public static bool ReadExactly(this NetworkStream stream, byte[] buffer, int amount) + { + // there might not be enough bytes in the TCP buffer for .Read to read + // the whole amount at once, so we need to keep trying until we have all + // the bytes (blocking) + // + // note: this just is a faster version of reading one after another: + // for (int i = 0; i < amount; ++i) + // if (stream.Read(buffer, i, 1) == 0) + // return false; + // return true; + int bytesRead = 0; + while (bytesRead < amount) + { + // read up to 'remaining' bytes with the 'safe' read extension + int remaining = amount - bytesRead; + int result = stream.ReadSafely(buffer, bytesRead, remaining); + + // .Read returns 0 if disconnected + if (result == 0) + return false; + + // otherwise add to bytes read + bytesRead += result; + } + return true; + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/NetworkStreamExtensions.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/NetworkStreamExtensions.cs.meta new file mode 100644 index 0000000..e7e5744 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/NetworkStreamExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a8076c43fa8d4d45831adae232d4d3c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/SafeQueue.cs b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/SafeQueue.cs new file mode 100644 index 0000000..9ebdf8a --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/SafeQueue.cs @@ -0,0 +1,75 @@ +// Net 4.X has ConcurrentQueue, but ConcurrentQueue has no TryDequeueAll method, +// which makes SafeQueue twice as fast for the send thread. +// +// uMMORPG 450 CCU +// SafeQueue: 900-1440ms latency +// ConcurrentQueue: 2000ms latency +// +// It's also noticeable in the LoadTest project, which hardly handles 300 CCU +// with ConcurrentQueue! +using System.Collections.Generic; + +namespace Telepathy +{ + public class SafeQueue + { + readonly Queue queue = new Queue(); + + // for statistics. don't call Count and assume that it's the same after the + // call. + public int Count + { + get + { + lock(queue) + { + return queue.Count; + } + } + } + + public void Enqueue(T item) + { + lock(queue) + { + queue.Enqueue(item); + } + } + + // can't check .Count before doing Dequeue because it might change inbetween, + // so we need a TryDequeue + public bool TryDequeue(out T result) + { + lock(queue) + { + result = default; + if (queue.Count > 0) + { + result = queue.Dequeue(); + return true; + } + return false; + } + } + + // for when we want to dequeue and remove all of them at once without + // locking every single TryDequeue. + public bool TryDequeueAll(out T[] result) + { + lock(queue) + { + result = queue.ToArray(); + queue.Clear(); + return result.Length > 0; + } + } + + public void Clear() + { + lock(queue) + { + queue.Clear(); + } + } + } +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/SafeQueue.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/SafeQueue.cs.meta new file mode 100644 index 0000000..f3a9310 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/SafeQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8fc06e2fb29854a0c9e90c0188d36a08 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Server.cs b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Server.cs new file mode 100644 index 0000000..e8b4aa0 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Server.cs @@ -0,0 +1,286 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace Telepathy +{ + public class Server : Common + { + // listener + public TcpListener listener; + Thread listenerThread; + + // class with all the client's data. let's call it Token for consistency + // with the async socket methods. + class ClientToken + { + public TcpClient client; + + // send queue + // SafeQueue is twice as fast as ConcurrentQueue, see SafeQueue.cs! + public SafeQueue sendQueue = new SafeQueue(); + + // ManualResetEvent to wake up the send thread. better than Thread.Sleep + // -> call Set() if everything was sent + // -> call Reset() if there is something to send again + // -> call WaitOne() to block until Reset was called + public ManualResetEvent sendPending = new ManualResetEvent(false); + + public ClientToken(TcpClient client) + { + this.client = client; + } + } + + // clients with + readonly ConcurrentDictionary clients = new ConcurrentDictionary(); + + // connectionId counter + int counter; + + // public next id function in case someone needs to reserve an id + // (e.g. if hostMode should always have 0 connection and external + // connections should start at 1, etc.) + public int NextConnectionId() + { + int id = Interlocked.Increment(ref counter); + + // it's very unlikely that we reach the uint limit of 2 billion. + // even with 1 new connection per second, this would take 68 years. + // -> but if it happens, then we should throw an exception because + // the caller probably should stop accepting clients. + // -> it's hardly worth using 'bool Next(out id)' for that case + // because it's just so unlikely. + if (id == int.MaxValue) + { + throw new Exception("connection id limit reached: " + id); + } + + return id; + } + + // check if the server is running + public bool Active => listenerThread != null && listenerThread.IsAlive; + + // the listener thread's listen function + // note: no maxConnections parameter. high level API should handle that. + // (Transport can't send a 'too full' message anyway) + void Listen(int port) + { + // absolutely must wrap with try/catch, otherwise thread + // exceptions are silent + try + { + // start listener on all IPv4 and IPv6 address via .Create + listener = TcpListener.Create(port); + listener.Server.NoDelay = NoDelay; + listener.Server.SendTimeout = SendTimeout; + listener.Start(); + Logger.Log("Server: listening port=" + port); + + // keep accepting new clients + while (true) + { + // wait and accept new client + // note: 'using' sucks here because it will try to + // dispose after thread was started but we still need it + // in the thread + TcpClient client = listener.AcceptTcpClient(); + + // set socket options + client.NoDelay = NoDelay; + client.SendTimeout = SendTimeout; + + // generate the next connection id (thread safely) + int connectionId = NextConnectionId(); + + // add to dict immediately + ClientToken token = new ClientToken(client); + clients[connectionId] = token; + + // spawn a send thread for each client + Thread sendThread = new Thread(() => + { + // wrap in try-catch, otherwise Thread exceptions + // are silent + try + { + // run the send loop + SendLoop(connectionId, client, token.sendQueue, token.sendPending); + } + catch (ThreadAbortException) + { + // happens on stop. don't log anything. + // (we catch it in SendLoop too, but it still gets + // through to here when aborting. don't show an + // error.) + } + catch (Exception exception) + { + Logger.LogError("Server send thread exception: " + exception); + } + }); + sendThread.IsBackground = true; + sendThread.Start(); + + // spawn a receive thread for each client + Thread receiveThread = new Thread(() => + { + // wrap in try-catch, otherwise Thread exceptions + // are silent + try + { + // run the receive loop + ReceiveLoop(connectionId, client, receiveQueue, MaxMessageSize); + + // remove client from clients dict afterwards + clients.TryRemove(connectionId, out ClientToken _); + + // sendthread might be waiting on ManualResetEvent, + // so let's make sure to end it if the connection + // closed. + // otherwise the send thread would only end if it's + // actually sending data while the connection is + // closed. + sendThread.Interrupt(); + } + catch (Exception exception) + { + Logger.LogError("Server client thread exception: " + exception); + } + }); + receiveThread.IsBackground = true; + receiveThread.Start(); + } + } + catch (ThreadAbortException exception) + { + // UnityEditor causes AbortException if thread is still + // running when we press Play again next time. that's okay. + Logger.Log("Server thread aborted. That's okay. " + exception); + } + catch (SocketException exception) + { + // calling StopServer will interrupt this thread with a + // 'SocketException: interrupted'. that's okay. + Logger.Log("Server Thread stopped. That's okay. " + exception); + } + catch (Exception exception) + { + // something went wrong. probably important. + Logger.LogError("Server Exception: " + exception); + } + } + + // start listening for new connections in a background thread and spawn + // a new thread for each one. + public bool Start(int port) + { + // not if already started + if (Active) return false; + + // clear old messages in queue, just to be sure that the caller + // doesn't receive data from last time and gets out of sync. + // -> calling this in Stop isn't smart because the caller may + // still want to process all the latest messages afterwards + receiveQueue = new ConcurrentQueue(); + + // start the listener thread + // (on low priority. if main thread is too busy then there is not + // much value in accepting even more clients) + Logger.Log("Server: Start port=" + port); + listenerThread = new Thread(() => { Listen(port); }); + listenerThread.IsBackground = true; + listenerThread.Priority = ThreadPriority.BelowNormal; + listenerThread.Start(); + return true; + } + + public void Stop() + { + // only if started + if (!Active) return; + + Logger.Log("Server: stopping..."); + + // stop listening to connections so that no one can connect while we + // close the client connections + // (might be null if we call Stop so quickly after Start that the + // thread was interrupted before even creating the listener) + listener?.Stop(); + + // kill listener thread at all costs. only way to guarantee that + // .Active is immediately false after Stop. + // -> calling .Join would sometimes wait forever + listenerThread?.Interrupt(); + listenerThread = null; + + // close all client connections + foreach (KeyValuePair kvp in clients) + { + TcpClient client = kvp.Value.client; + // close the stream if not closed yet. it may have been closed + // by a disconnect already, so use try/catch + try { client.GetStream().Close(); } catch {} + client.Close(); + } + + // clear clients list + clients.Clear(); + } + + // send message to client using socket connection. + public bool Send(int connectionId, byte[] data) + { + // respect max message size to avoid allocation attacks. + if (data.Length <= MaxMessageSize) + { + // find the connection + ClientToken token; + if (clients.TryGetValue(connectionId, out token)) + { + // add to send queue and return immediately. + // calling Send here would be blocking (sometimes for long times + // if other side lags or wire was disconnected) + token.sendQueue.Enqueue(data); + token.sendPending.Set(); // interrupt SendThread WaitOne() + return true; + } + Logger.Log("Server.Send: invalid connectionId: " + connectionId); + return false; + } + Logger.LogError("Client.Send: message too big: " + data.Length + ". Limit: " + MaxMessageSize); + return false; + } + + // client's ip is sometimes needed by the server, e.g. for bans + public string GetClientAddress(int connectionId) + { + // find the connection + ClientToken token; + if (clients.TryGetValue(connectionId, out token)) + { + return ((IPEndPoint)token.client.Client.RemoteEndPoint).Address.ToString(); + } + return ""; + } + + // disconnect (kick) a client + public bool Disconnect(int connectionId) + { + // find the connection + ClientToken token; + if (clients.TryGetValue(connectionId, out token)) + { + // just close it. client thread will take care of the rest. + token.client.Close(); + Logger.Log("Server.Disconnect connectionId:" + connectionId); + return true; + } + return false; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Server.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Server.cs.meta new file mode 100644 index 0000000..9cee8b7 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Server.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb98a16841ccc4338a7e0b4e59136563 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Telepathy.dll b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Telepathy.dll new file mode 100644 index 0000000..dc984f0 Binary files /dev/null and b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Telepathy.dll differ diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Telepathy.dll.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Telepathy.dll.meta new file mode 100644 index 0000000..8ca1543 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Telepathy.dll.meta @@ -0,0 +1,30 @@ +fileFormatVersion: 2 +guid: cc38a12e9b5834143976137abe1c8f23 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Utils.cs b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Utils.cs new file mode 100644 index 0000000..c5b71cd --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Utils.cs @@ -0,0 +1,44 @@ +namespace Telepathy +{ + public static class Utils + { + // fast int to byte[] conversion and vice versa + // -> test with 100k conversions: + // BitConverter.GetBytes(ushort): 144ms + // bit shifting: 11ms + // -> 10x speed improvement makes this optimization actually worth it + // -> this way we don't need to allocate BinaryWriter/Reader either + // -> 4 bytes because some people may want to send messages larger than + // 64K bytes + // => big endian is standard for network transmissions, and necessary + // for compatibility with erlang + public static byte[] IntToBytesBigEndian(int value) + { + return new byte[] { + (byte)(value >> 24), + (byte)(value >> 16), + (byte)(value >> 8), + (byte)value + }; + } + + // IntToBytes version that doesn't allocate a new byte[4] each time. + // -> important for MMO scale networking performance. + public static void IntToBytesBigEndianNonAlloc(int value, byte[] bytes) + { + bytes[0] = (byte)(value >> 24); + bytes[1] = (byte)(value >> 16); + bytes[2] = (byte)(value >> 8); + bytes[3] = (byte)value; + } + + public static int BytesToIntBigEndian(byte[] bytes) + { + return + (bytes[0] << 24) | + (bytes[1] << 16) | + (bytes[2] << 8) | + bytes[3]; + } + } +} \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Utils.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Utils.cs.meta new file mode 100644 index 0000000..0a9253b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Telepathy/Utils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 951d08c05297f4b3e8feb5bfcab86531 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/TelepathyTransport.cs b/Assets/Packages/Mirror/Runtime/Transport/TelepathyTransport.cs new file mode 100644 index 0000000..f5ed0f6 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/TelepathyTransport.cs @@ -0,0 +1,180 @@ +// wraps Telepathy for use as HLAPI TransportLayer +using System; +using System.ComponentModel; +using System.Net.Sockets; +using UnityEngine; +using UnityEngine.Serialization; + +namespace Mirror +{ + [HelpURL("https://github.com/vis2k/Telepathy/blob/master/README.md")] + public class TelepathyTransport : Transport + { + public ushort port = 7777; + + [Tooltip("Nagle Algorithm can be disabled by enabling NoDelay")] + public bool NoDelay = true; + + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use MaxMessageSizeFromClient or MaxMessageSizeFromServer instead.")] + public int MaxMessageSize + { + get => serverMaxMessageSize; + set => serverMaxMessageSize = clientMaxMessageSize = value; + } + + [Tooltip("Protect against allocation attacks by keeping the max message size small. Otherwise an attacker might send multiple fake packets with 2GB headers, causing the server to run out of memory after allocating multiple large packets.")] + [FormerlySerializedAs("MaxMessageSize")] public int serverMaxMessageSize = 16 * 1024; + + [Tooltip("Protect against allocation attacks by keeping the max message size small. Otherwise an attacker host might send multiple fake packets with 2GB headers, causing the connected clients to run out of memory after allocating multiple large packets.")] + [FormerlySerializedAs("MaxMessageSize")] public int clientMaxMessageSize = 16 * 1024; + + protected Telepathy.Client client = new Telepathy.Client(); + protected Telepathy.Server server = new Telepathy.Server(); + + void Awake() + { + // tell Telepathy to use Unity's Debug.Log + Telepathy.Logger.Log = Debug.Log; + Telepathy.Logger.LogWarning = Debug.LogWarning; + Telepathy.Logger.LogError = Debug.LogError; + + // configure + client.NoDelay = NoDelay; + client.MaxMessageSize = clientMaxMessageSize; + server.NoDelay = NoDelay; + server.MaxMessageSize = serverMaxMessageSize; + + Debug.Log("TelepathyTransport initialized!"); + } + + // client + public override bool ClientConnected() => client.Connected; + public override void ClientConnect(string address) => client.Connect(address, port); + public override bool ClientSend(int channelId, byte[] data) => client.Send(data); + + bool ProcessClientMessage() + { + if (client.GetNextMessage(out Telepathy.Message message)) + { + switch (message.eventType) + { + case Telepathy.EventType.Connected: + OnClientConnected.Invoke(); + break; + case Telepathy.EventType.Data: + OnClientDataReceived.Invoke(new ArraySegment(message.data)); + break; + case Telepathy.EventType.Disconnected: + OnClientDisconnected.Invoke(); + break; + default: + // TODO: Telepathy does not report errors at all + // it just disconnects, should be fixed + OnClientDisconnected.Invoke(); + break; + } + return true; + } + return false; + } + public override void ClientDisconnect() => client.Disconnect(); + + // IMPORTANT: set script execution order to >1000 to call Transport's + // LateUpdate after all others. Fixes race condition where + // e.g. in uSurvival Transport would apply Cmds before + // ShoulderRotation.LateUpdate, resulting in projectile + // spawns at the point before shoulder rotation. + public void LateUpdate() + { + // note: we need to check enabled in case we set it to false + // when LateUpdate already started. + // (https://github.com/vis2k/Mirror/pull/379) + while (enabled && ProcessClientMessage()) {} + while (enabled && ProcessServerMessage()) {} + } + + // server + public override bool ServerActive() => server.Active; + public override void ServerStart() => server.Start(port); + public override bool ServerSend(int connectionId, int channelId, byte[] data) => server.Send(connectionId, data); + public bool ProcessServerMessage() + { + if (server.GetNextMessage(out Telepathy.Message message)) + { + switch (message.eventType) + { + case Telepathy.EventType.Connected: + OnServerConnected.Invoke(message.connectionId); + break; + case Telepathy.EventType.Data: + OnServerDataReceived.Invoke(message.connectionId, new ArraySegment(message.data)); + break; + case Telepathy.EventType.Disconnected: + OnServerDisconnected.Invoke(message.connectionId); + break; + default: + // TODO handle errors from Telepathy when telepathy can report errors + OnServerDisconnected.Invoke(message.connectionId); + break; + } + return true; + } + return false; + } + public override bool ServerDisconnect(int connectionId) => server.Disconnect(connectionId); + public override string ServerGetClientAddress(int connectionId) + { + try + { + return server.GetClientAddress(connectionId); + } + catch (SocketException) + { + // using server.listener.LocalEndpoint causes an Exception + // in UWP + Unity 2019: + // Exception thrown at 0x00007FF9755DA388 in UWF.exe: + // Microsoft C++ exception: Il2CppExceptionWrapper at memory + // location 0x000000E15A0FCDD0. SocketException: An address + // incompatible with the requested protocol was used at + // System.Net.Sockets.Socket.get_LocalEndPoint () + // so let's at least catch it and recover + return "unknown"; + } + } + public override void ServerStop() => server.Stop(); + + // common + public override void Shutdown() + { + Debug.Log("TelepathyTransport Shutdown()"); + client.Disconnect(); + server.Stop(); + } + + public override int GetMaxPacketSize(int channelId) + { + return serverMaxMessageSize; + } + + public override string ToString() + { + if (server.Active && server.listener != null) + { + // printing server.listener.LocalEndpoint causes an Exception + // in UWP + Unity 2019: + // Exception thrown at 0x00007FF9755DA388 in UWF.exe: + // Microsoft C++ exception: Il2CppExceptionWrapper at memory + // location 0x000000E15A0FCDD0. SocketException: An address + // incompatible with the requested protocol was used at + // System.Net.Sockets.Socket.get_LocalEndPoint () + // so let's use the regular port instead. + return "Telepathy Server port: " + port; + } + else if (client.Connecting || client.Connected) + { + return "Telepathy Client ip: " + client.client.Client.RemoteEndPoint; + } + return "Telepathy (inactive/disconnected)"; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/TelepathyTransport.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/TelepathyTransport.cs.meta new file mode 100644 index 0000000..a89b0d3 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/TelepathyTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c7424c1070fad4ba2a7a96b02fbeb4bb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 1000 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Transport.cs b/Assets/Packages/Mirror/Runtime/Transport/Transport.cs new file mode 100644 index 0000000..6a706e8 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Transport.cs @@ -0,0 +1,190 @@ +// abstract transport layer component +// note: not all transports need a port, so add it to yours if needed. +using System; +using System.ComponentModel; +using UnityEngine; +using UnityEngine.Events; + +namespace Mirror +{ + // UnityEvent definitions + [Serializable] public class UnityEventArraySegment : UnityEvent> {} + [Serializable] public class UnityEventException : UnityEvent {} + [Serializable] public class UnityEventInt : UnityEvent {} + [Serializable] public class UnityEventIntArraySegment : UnityEvent> {} + [Serializable] public class UnityEventIntException : UnityEvent {} + + public abstract class Transport : MonoBehaviour + { + /// + /// The current transport used by Mirror. + /// + public static Transport activeTransport; + + /// + /// Is this transport available in the current platform? + /// Some transports might only be available in mobile + /// Many will not work in webgl + /// + /// True if this transport works in the current platform + public virtual bool Available() + { + return Application.platform != RuntimePlatform.WebGLPlayer; + } + + #region Client + /// + /// Notify subscribers when when this client establish a successful connection to the server + /// + [HideInInspector] public UnityEvent OnClientConnected = new UnityEvent(); + + /// + /// Notify subscribers when this client receive data from the server + /// + [HideInInspector] public UnityEventArraySegment OnClientDataReceived = new UnityEventArraySegment(); + + /// + /// Notify subscribers when this clianet encounters an error communicating with the server + /// + [HideInInspector] public UnityEventException OnClientError = new UnityEventException(); + + /// + /// Notify subscribers when this client disconnects from the server + /// + [HideInInspector] public UnityEvent OnClientDisconnected = new UnityEvent(); + + /// + /// Determines if we are currently connected to the server + /// + /// True if a connection has been established to the server + public abstract bool ClientConnected(); + + /// + /// Establish a connecion to a server + /// + /// The IP address or FQDN of the server we are trying to connect to + public abstract void ClientConnect(string address); + + /// + /// Send data to the server + /// + /// The channel to use. 0 is the default channel, + /// but some transports might want to provide unreliable, encrypted, compressed, or any other feature + /// as new channels + /// The data to send to the server + /// true if the send was successful + public abstract bool ClientSend(int channelId, byte[] data); + + /// + /// Disconnect this client from the server + /// + public abstract void ClientDisconnect(); + + #endregion + + #region Server + + /// + /// Notify subscribers when a client connects to this server + /// + [HideInInspector] public UnityEventInt OnServerConnected = new UnityEventInt(); + + /// + /// Notify subscribers when this server receives data from the client + /// + [HideInInspector] public UnityEventIntArraySegment OnServerDataReceived = new UnityEventIntArraySegment(); + + /// + /// Notify subscribers when this server has some problem communicating with the client + /// + [HideInInspector] public UnityEventIntException OnServerError = new UnityEventIntException(); + + /// + /// Notify subscribers when a client disconnects from this server + /// + [HideInInspector] public UnityEventInt OnServerDisconnected = new UnityEventInt(); + + /// + /// Determines if the server is up and running + /// + /// true if the transport is ready for connections from clients + public abstract bool ServerActive(); + + /// + /// Start listening for clients + /// + public abstract void ServerStart(); + + /// + /// Send data to a client + /// + /// The id of the client to send the data to + /// The channel to be used. Transports can use channels to implement + /// other features such as unreliable, encryption, compression, etc... + /// + /// true if the data was sent + public abstract bool ServerSend(int connectionId, int channelId, byte[] data); + + /// + /// Disconnect a client from this server. Useful to kick people out. + /// + /// the id of the client to disconnect + /// true if the client was kicked + public abstract bool ServerDisconnect(int connectionId); + + /// + /// Deprecated: Use ServerGetClientAddress(int connectionId) instead + /// + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use ServerGetClientAddress(int connectionId) instead")] + public virtual bool GetConnectionInfo(int connectionId, out string address) + { + address = ServerGetClientAddress(connectionId); + return true; + } + + /// + /// Get the client address + /// + /// id of the client + /// address of the client + public abstract string ServerGetClientAddress(int connectionId); + + /// + /// Stop listening for clients and disconnect all existing clients + /// + public abstract void ServerStop(); + + + #endregion + + /// + /// Shut down the transport, both as client and server + /// + public abstract void Shutdown(); + + /// + /// The maximum packet size for a given channel. Unreliable transports + /// usually can only deliver small packets. Reliable fragmented channels + /// can usually deliver large ones. + /// + /// channel id + /// the size in bytes that can be sent via the provided channel + public abstract int GetMaxPacketSize(int channelId = Channels.DefaultReliable); + + // block Update() to force Transports to use LateUpdate to avoid race + // conditions. messages should be processed after all the game state + // was processed in Update. + // -> in other words: use LateUpdate! + // -> uMMORPG 480 CCU stress test: when bot machine stops, it causes + // 'Observer not ready for ...' log messages when using Update + // -> occupying a public Update() function will cause Warnings if a + // transport uses Update. + // + // IMPORTANT: set script execution order to >1000 to call Transport's + // LateUpdate after all others. Fixes race condition where + // e.g. in uSurvival Transport would apply Cmds before + // ShoulderRotation.LateUpdate, resulting in projectile + // spawns at the point before shoulder rotation. + public void Update() {} + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Transport.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Transport.cs.meta new file mode 100644 index 0000000..2d451cf --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Transport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cfffcac25d6d64ced9de620159e221b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket.meta new file mode 100644 index 0000000..5797569 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 75b15785adf2d4b7c8d779f5ba6a6326 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Client.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Client.cs new file mode 100644 index 0000000..535975b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Client.cs @@ -0,0 +1,191 @@ +#if !UNITY_WEBGL || UNITY_EDITOR + +using System; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Net.WebSockets; +using System.Threading; +using System.Threading.Tasks; +using Ninja.WebSockets; +using UnityEngine; + +namespace Mirror.Websocket +{ + + public class Client + { + public event Action Connected; + public event Action> ReceivedData; + public event Action Disconnected; + public event Action ReceivedError; + + const int MaxMessageSize = 1024 * 256; + WebSocket webSocket; + CancellationTokenSource cancellation; + + public bool NoDelay = true; + + public bool Connecting { get; set; } + public bool IsConnected { get; set; } + + Uri uri; + + public async void Connect(Uri uri) + { + // not if already started + if (webSocket != null) + { + // paul: exceptions are better than silence + ReceivedError?.Invoke(new Exception("Client already connected")); + return; + } + this.uri = uri; + // We are connecting from now until Connect succeeds or fails + Connecting = true; + + WebSocketClientOptions options = new WebSocketClientOptions() + { + NoDelay = true, + KeepAliveInterval = TimeSpan.Zero, + SecWebSocketProtocol = "binary" + }; + + cancellation = new CancellationTokenSource(); + + WebSocketClientFactory clientFactory = new WebSocketClientFactory(); + + try + { + using (webSocket = await clientFactory.ConnectAsync(uri, options, cancellation.Token)) + { + CancellationToken token = cancellation.Token; + IsConnected = true; + Connecting = false; + Connected?.Invoke(); + + await ReceiveLoop(webSocket, token); + } + } + catch (ObjectDisposedException) + { + // No error, the client got closed + } + catch (Exception ex) + { + ReceivedError?.Invoke(ex); + } + finally + { + Disconnect(); + Disconnected?.Invoke(); + } + } + + async Task ReceiveLoop(WebSocket webSocket, CancellationToken token) + { + byte[] buffer = new byte[MaxMessageSize]; + + while (true) + { + WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(buffer), token); + + + if (result == null) + break; + if (result.MessageType == WebSocketMessageType.Close) + break; + + // we got a text or binary message, need the full message + ArraySegment data = await ReadFrames(result, webSocket, buffer); + + if (data.Count == 0) + break; + + try + { + ReceivedData?.Invoke(data); + } + catch (Exception exception) + { + ReceivedError?.Invoke(exception); + } + } + } + + // a message might come splitted in multiple frames + // collect all frames + async Task> ReadFrames(WebSocketReceiveResult result, WebSocket webSocket, byte[] buffer) + { + int count = result.Count; + + while (!result.EndOfMessage) + { + if (count >= MaxMessageSize) + { + string closeMessage = string.Format("Maximum message size: {0} bytes.", MaxMessageSize); + await webSocket.CloseAsync(WebSocketCloseStatus.MessageTooBig, closeMessage, CancellationToken.None); + ReceivedError?.Invoke(new WebSocketException(WebSocketError.HeaderError)); + return new ArraySegment(); + } + + result = await webSocket.ReceiveAsync(new ArraySegment(buffer, count, MaxMessageSize - count), CancellationToken.None); + count += result.Count; + + } + return new ArraySegment(buffer, 0, count); + } + + public void Disconnect() + { + cancellation?.Cancel(); + + // only if started + if (webSocket != null) + { + // close client + webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,"", CancellationToken.None); + webSocket = null; + Connecting = false; + IsConnected = false; + } + } + + // send the data or throw exception + public async void Send(byte[] data) + { + if (webSocket == null) + { + ReceivedError?.Invoke(new SocketException((int)SocketError.NotConnected)); + return; + } + + try + { + await webSocket.SendAsync(new ArraySegment(data), WebSocketMessageType.Binary, true, cancellation.Token); + } + catch (Exception ex) + { + Disconnect(); + ReceivedError?.Invoke(ex); + } + } + + + public override string ToString() + { + if (IsConnected ) + { + return $"Websocket connected to {uri}"; + } + if (Connecting) + { + return $"Websocket connecting to {uri}"; + } + return ""; + } + } + +} + +#endif diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Client.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Client.cs.meta new file mode 100644 index 0000000..70e22d3 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Client.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f69ff0981a33445a89b5e37b245806f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/ClientJs.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/ClientJs.cs new file mode 100644 index 0000000..73d10cd --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/ClientJs.cs @@ -0,0 +1,118 @@ +#if UNITY_WEBGL && !UNITY_EDITOR + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Net.WebSockets; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using AOT; +using Ninja.WebSockets; +using UnityEngine; + +namespace Mirror.Websocket +{ + // this is the client implementation used by browsers + public class Client + { + static int idGenerator = 0; + static readonly Dictionary clients = new Dictionary(); + + public bool NoDelay = true; + + public event Action Connected; + public event Action> ReceivedData; + public event Action Disconnected; + public event Action ReceivedError; + + public bool Connecting { get; set; } + public bool IsConnected + { + get + { + return SocketState(m_NativeRef) != 0; + } + } + + int m_NativeRef = 0; + readonly int id; + + public Client() + { + id = Interlocked.Increment(ref idGenerator); + } + + public void Connect(Uri uri) + { + clients[id] = this; + + Connecting = true; + + m_NativeRef = SocketCreate(uri.ToString(), id, OnOpen, OnData, OnClose); + } + + public void Disconnect() + { + SocketClose(m_NativeRef); + } + + // send the data or throw exception + public void Send(byte[] data) + { + SocketSend(m_NativeRef, data, data.Length); + } + + + #region Javascript native functions + [DllImport("__Internal")] + static extern int SocketCreate( + string url, + int id, + Action onpen, + Action ondata, + Action onclose); + + [DllImport("__Internal")] + static extern int SocketState(int socketInstance); + + [DllImport("__Internal")] + static extern void SocketSend(int socketInstance, byte[] ptr, int length); + + [DllImport("__Internal")] + static extern void SocketClose(int socketInstance); + + #endregion + + #region Javascript callbacks + + [MonoPInvokeCallback(typeof(Action))] + public static void OnOpen(int id) + { + clients[id].Connecting = false; + clients[id].Connected?.Invoke(); + } + + [MonoPInvokeCallback(typeof(Action))] + public static void OnClose(int id) + { + clients[id].Connecting = false; + clients[id].Disconnected?.Invoke(); + clients.Remove(id); + } + + [MonoPInvokeCallback(typeof(Action))] + public static void OnData(int id, IntPtr ptr, int length) + { + byte[] data = new byte[length]; + Marshal.Copy(ptr, data, 0, length); + + clients[id].ReceivedData(new ArraySegment(data)); + } + #endregion + } +} + +#endif diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/ClientJs.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/ClientJs.cs.meta new file mode 100644 index 0000000..2fdca98 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/ClientJs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 278e08c90f2324e2e80a0fe8984b0590 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets.meta new file mode 100644 index 0000000..e156578 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 100fd42034e0d46db8980db4cc0cd178 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/BufferPool.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/BufferPool.cs new file mode 100644 index 0000000..74a0c87 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/BufferPool.cs @@ -0,0 +1,250 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Ninja.WebSockets +{ + /// + /// This buffer pool is instance thread safe + /// Use GetBuffer to get a MemoryStream (with a publically accessible buffer) + /// Calling Close on this MemoryStream will clear its internal buffer and return the buffer to the pool for reuse + /// MemoryStreams can grow larger than the DEFAULT_BUFFER_SIZE (or whatever you passed in) + /// and the underlying buffers will be returned to the pool at their larger sizes + /// + public class BufferPool : IBufferPool + { + const int DEFAULT_BUFFER_SIZE = 16384; + readonly ConcurrentStack _bufferPoolStack; + readonly int _bufferSize; + + public BufferPool() : this(DEFAULT_BUFFER_SIZE) + { + } + + public BufferPool(int bufferSize) + { + _bufferSize = bufferSize; + _bufferPoolStack = new ConcurrentStack(); + } + + /// + /// This memory stream is not instance thread safe (not to be confused with the BufferPool which is instance thread safe) + /// + protected class PublicBufferMemoryStream : MemoryStream + { + readonly BufferPool _bufferPoolInternal; + byte[] _buffer; + MemoryStream _ms; + + public PublicBufferMemoryStream(byte[] buffer, BufferPool bufferPool) : base(new byte[0]) + { + _bufferPoolInternal = bufferPool; + _buffer = buffer; + _ms = new MemoryStream(buffer, 0, buffer.Length, true, true); + } + + public override long Length => base.Length; + + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + return _ms.BeginRead(buffer, offset, count, callback, state); + } + + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + return _ms.BeginWrite(buffer, offset, count, callback, state); + } + + public override bool CanRead => _ms.CanRead; + public override bool CanSeek => _ms.CanSeek; + public override bool CanTimeout => _ms.CanTimeout; + public override bool CanWrite => _ms.CanWrite; + public override int Capacity + { + get { return _ms.Capacity; } + set { _ms.Capacity = value; } + } + + public override void Close() + { + // clear the buffer - we only need to clear up to the number of bytes we have already written + Array.Clear(_buffer, 0, (int)_ms.Position); + + _ms.Close(); + + // return the buffer to the pool + _bufferPoolInternal.ReturnBuffer(_buffer); + } + + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) + { + return _ms.CopyToAsync(destination, bufferSize, cancellationToken); + } + + public override int EndRead(IAsyncResult asyncResult) + { + return _ms.EndRead(asyncResult); + } + + public override void EndWrite(IAsyncResult asyncResult) + { + _ms.EndWrite(asyncResult); + } + + public override void Flush() + { + _ms.Flush(); + } + + public override Task FlushAsync(CancellationToken cancellationToken) + { + return _ms.FlushAsync(cancellationToken); + } + + public override byte[] GetBuffer() + { + return _buffer; + } + + public override long Position + { + get { return _ms.Position; } + set { _ms.Position = value; } + } + + public override int Read(byte[] buffer, int offset, int count) + { + return _ms.Read(buffer, offset, count); + } + + void EnlargeBufferIfRequired(int count) + { + // we cannot fit the data into the existing buffer, time for a new buffer + if (count > (_buffer.Length - _ms.Position)) + { + int position = (int)_ms.Position; + + // double the buffer size + int newSize = _buffer.Length * 2; + + // make sure the new size is big enough + int requiredSize = count + _buffer.Length - position; + if (requiredSize > newSize) + { + // compute the power of two larger than requiredSize. so 40000 => 65536 + newSize = (int)Math.Pow(2, Math.Ceiling(Math.Log(requiredSize) / Math.Log(2))); ; + } + + byte[] newBuffer = new byte[newSize]; + Buffer.BlockCopy(_buffer, 0, newBuffer, 0, position); + _ms = new MemoryStream(newBuffer, 0, newBuffer.Length, true, true) + { + Position = position + }; + + _buffer = newBuffer; + } + } + + public override void WriteByte(byte value) + { + EnlargeBufferIfRequired(1); + _ms.WriteByte(value); + } + + public override void Write(byte[] buffer, int offset, int count) + { + EnlargeBufferIfRequired(count); + _ms.Write(buffer, offset, count); + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + EnlargeBufferIfRequired(count); + return _ms.WriteAsync(buffer, offset, count); + } + + public override object InitializeLifetimeService() + { + return _ms.InitializeLifetimeService(); + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return _ms.ReadAsync(buffer, offset, count, cancellationToken); + } + + public override int ReadByte() + { + return _ms.ReadByte(); + } + + public override int ReadTimeout { + get { return _ms.ReadTimeout; } + set { _ms.ReadTimeout = value; } + } + + public override long Seek(long offset, SeekOrigin loc) + { + return _ms.Seek(offset, loc); + } + + /// + /// Note: This will not make the MemoryStream any smaller, only larger + /// + public override void SetLength(long value) + { + EnlargeBufferIfRequired((int)value); + } + + public override byte[] ToArray() + { + // you should never call this + return _ms.ToArray(); + } + + public override int WriteTimeout + { + get { return _ms.WriteTimeout; } + set { _ms.WriteTimeout = value; } + } + +#if !NET45 + public override bool TryGetBuffer(out ArraySegment buffer) + { + buffer = new ArraySegment(_buffer, 0, (int)_ms.Position); + return true; + } +#endif + + public override void WriteTo(Stream stream) + { + _ms.WriteTo(stream); + } + } + + /// + /// Gets a MemoryStream built from a buffer plucked from a thread safe pool + /// The pool grows automatically. + /// Closing the memory stream clears the buffer and returns it to the pool + /// + public MemoryStream GetBuffer() + { + if (!_bufferPoolStack.TryPop(out byte[] buffer)) + { + buffer = new byte[_bufferSize]; + } + + return new PublicBufferMemoryStream(buffer, this); + } + + protected void ReturnBuffer(byte[] buffer) + { + _bufferPoolStack.Push(buffer); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/BufferPool.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/BufferPool.cs.meta new file mode 100644 index 0000000..2bfda08 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/BufferPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e362254f82b2a4627bfd83394d093715 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions.meta new file mode 100644 index 0000000..210aa6b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ca217a8fd870444d0ae623d3905d603f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/EntityTooLargeException.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/EntityTooLargeException.cs new file mode 100644 index 0000000..5a1724f --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/EntityTooLargeException.cs @@ -0,0 +1,26 @@ +using System; + +namespace Ninja.WebSockets.Exceptions +{ + [Serializable] + public class EntityTooLargeException : Exception + { + public EntityTooLargeException() : base() + { + + } + + /// + /// Http header too large to fit in buffer + /// + public EntityTooLargeException(string message) : base(message) + { + + } + + public EntityTooLargeException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/EntityTooLargeException.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/EntityTooLargeException.cs.meta new file mode 100644 index 0000000..b54345b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/EntityTooLargeException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7ef87d4a0822c4d2da3e8daa392e61d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/InvalidHttpResponseCodeException.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/InvalidHttpResponseCodeException.cs new file mode 100644 index 0000000..73354dd --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/InvalidHttpResponseCodeException.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Ninja.WebSockets.Exceptions +{ + [Serializable] + public class InvalidHttpResponseCodeException : Exception + { + public string ResponseCode { get; private set; } + + public string ResponseHeader { get; private set; } + + public string ResponseDetails { get; private set; } + + public InvalidHttpResponseCodeException() : base() + { + } + + public InvalidHttpResponseCodeException(string message) : base(message) + { + } + + public InvalidHttpResponseCodeException(string responseCode, string responseDetails, string responseHeader) : base(responseCode) + { + ResponseCode = responseCode; + ResponseDetails = responseDetails; + ResponseHeader = responseHeader; + } + + public InvalidHttpResponseCodeException(string message, Exception inner) : base(message, inner) + { + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/InvalidHttpResponseCodeException.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/InvalidHttpResponseCodeException.cs.meta new file mode 100644 index 0000000..7e772d5 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/InvalidHttpResponseCodeException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c2d7303a1a324f0ebe15cb3faf9b0d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/README.txt b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/README.txt new file mode 100644 index 0000000..a1d28e4 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/README.txt @@ -0,0 +1 @@ +Make sure that exceptions follow the microsoft standards \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/README.txt.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/README.txt.meta new file mode 100644 index 0000000..2ac5059 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/README.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 3488f8d8c73d64a12bc24930c0210a41 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/SecWebSocketKeyMissingException.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/SecWebSocketKeyMissingException.cs new file mode 100644 index 0000000..8247625 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/SecWebSocketKeyMissingException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Ninja.WebSockets.Exceptions +{ + [Serializable] + public class SecWebSocketKeyMissingException : Exception + { + public SecWebSocketKeyMissingException() : base() + { + + } + + public SecWebSocketKeyMissingException(string message) : base(message) + { + + } + + public SecWebSocketKeyMissingException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/SecWebSocketKeyMissingException.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/SecWebSocketKeyMissingException.cs.meta new file mode 100644 index 0000000..ebb2ec0 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/SecWebSocketKeyMissingException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 66d99fe90f4cb4471bf01c6f391ffc29 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/ServerListenerSocketException.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/ServerListenerSocketException.cs new file mode 100644 index 0000000..69d5360 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/ServerListenerSocketException.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net.Sockets; + +namespace Ninja.WebSockets.Exceptions +{ + [Serializable] + public class ServerListenerSocketException : Exception + { + public ServerListenerSocketException() : base() + { + } + + public ServerListenerSocketException(string message) : base(message) + { + } + + public ServerListenerSocketException(string message, Exception inner) : base(message, inner) + { + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/ServerListenerSocketException.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/ServerListenerSocketException.cs.meta new file mode 100644 index 0000000..10b3384 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/ServerListenerSocketException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9b188b3dddee84decadd5913a535746b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketBufferOverflowException.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketBufferOverflowException.cs new file mode 100644 index 0000000..682143f --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketBufferOverflowException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Ninja.WebSockets.Exceptions +{ + [Serializable] + public class WebSocketBufferOverflowException : Exception + { + public WebSocketBufferOverflowException() : base() + { + } + + public WebSocketBufferOverflowException(string message) : base(message) + { + } + + public WebSocketBufferOverflowException(string message, Exception inner) : base(message, inner) + { + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketBufferOverflowException.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketBufferOverflowException.cs.meta new file mode 100644 index 0000000..419f9d0 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketBufferOverflowException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c3188abcb6c441759011da01fa342f4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketHandshakeFailedException.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketHandshakeFailedException.cs new file mode 100644 index 0000000..624dc77 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketHandshakeFailedException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Ninja.WebSockets.Exceptions +{ + [Serializable] + public class WebSocketHandshakeFailedException : Exception + { + public WebSocketHandshakeFailedException() : base() + { + } + + public WebSocketHandshakeFailedException(string message) : base(message) + { + } + + public WebSocketHandshakeFailedException(string message, Exception inner) : base(message, inner) + { + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketHandshakeFailedException.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketHandshakeFailedException.cs.meta new file mode 100644 index 0000000..8bd4271 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketHandshakeFailedException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7dd72ca0a28054d258c1d1ad8254a16e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketVersionNotSupportedException.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketVersionNotSupportedException.cs new file mode 100644 index 0000000..f23a85a --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketVersionNotSupportedException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Ninja.WebSockets.Exceptions +{ + [Serializable] + public class WebSocketVersionNotSupportedException : Exception + { + public WebSocketVersionNotSupportedException() : base() + { + } + + public WebSocketVersionNotSupportedException(string message) : base(message) + { + } + + public WebSocketVersionNotSupportedException(string message, Exception inner) : base(message, inner) + { + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketVersionNotSupportedException.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketVersionNotSupportedException.cs.meta new file mode 100644 index 0000000..6f14394 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Exceptions/WebSocketVersionNotSupportedException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dc12d4b9cfe854aeeaab3c9f2f3d165e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/HttpHelper.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/HttpHelper.cs new file mode 100644 index 0000000..88fc9a6 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/HttpHelper.cs @@ -0,0 +1,202 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Ninja.WebSockets.Exceptions; +using System.Linq; + +namespace Ninja.WebSockets +{ + public class HttpHelper + { + const string HTTP_GET_HEADER_REGEX = @"^GET(.*)HTTP\/1\.1"; + + /// + /// Calculates a random WebSocket key that can be used to initiate a WebSocket handshake + /// + /// A random websocket key + public static string CalculateWebSocketKey() + { + // this is not used for cryptography so doing something simple like he code below is op + Random rand = new Random((int)DateTime.Now.Ticks); + byte[] keyAsBytes = new byte[16]; + rand.NextBytes(keyAsBytes); + return Convert.ToBase64String(keyAsBytes); + } + + /// + /// Computes a WebSocket accept string from a given key + /// + /// The web socket key to base the accept string on + /// A web socket accept string + public static string ComputeSocketAcceptString(string secWebSocketKey) + { + // this is a guid as per the web socket spec + const string webSocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + string concatenated = secWebSocketKey + webSocketGuid; + byte[] concatenatedAsBytes = Encoding.UTF8.GetBytes(concatenated); + + // note an instance of SHA1 is not threadsafe so we have to create a new one every time here + byte[] sha1Hash = SHA1.Create().ComputeHash(concatenatedAsBytes); + string secWebSocketAccept = Convert.ToBase64String(sha1Hash); + return secWebSocketAccept; + } + + /// + /// Reads an http header as per the HTTP spec + /// + /// The stream to read UTF8 text from + /// The cancellation token + /// The HTTP header + public static async Task ReadHttpHeaderAsync(Stream stream, CancellationToken token) + { + int length = 1024*16; // 16KB buffer more than enough for http header + byte[] buffer = new byte[length]; + int offset = 0; + int bytesRead = 0; + + do + { + if (offset >= length) + { + throw new EntityTooLargeException("Http header message too large to fit in buffer (16KB)"); + } + + bytesRead = await stream.ReadAsync(buffer, offset, length - offset, token); + offset += bytesRead; + string header = Encoding.UTF8.GetString(buffer, 0, offset); + + // as per http specification, all headers should end this this + if (header.Contains("\r\n\r\n")) + { + return header; + } + + } while (bytesRead > 0); + + return string.Empty; + } + + /// + /// Decodes the header to detect is this is a web socket upgrade response + /// + /// The HTTP header + /// True if this is an http WebSocket upgrade response + public static bool IsWebSocketUpgradeRequest(String header) + { + Regex getRegex = new Regex(HTTP_GET_HEADER_REGEX, RegexOptions.IgnoreCase); + Match getRegexMatch = getRegex.Match(header); + + if (getRegexMatch.Success) + { + // check if this is a web socket upgrade request + Regex webSocketUpgradeRegex = new Regex("Upgrade: websocket", RegexOptions.IgnoreCase); + Match webSocketUpgradeRegexMatch = webSocketUpgradeRegex.Match(header); + return webSocketUpgradeRegexMatch.Success; + } + + return false; + } + + /// + /// Gets the path from the HTTP header + /// + /// The HTTP header to read + /// The path + public static string GetPathFromHeader(string httpHeader) + { + Regex getRegex = new Regex(HTTP_GET_HEADER_REGEX, RegexOptions.IgnoreCase); + Match getRegexMatch = getRegex.Match(httpHeader); + + if (getRegexMatch.Success) + { + // extract the path attribute from the first line of the header + return getRegexMatch.Groups[1].Value.Trim(); + } + + return null; + } + + public static IList GetSubProtocols(string httpHeader) + { + Regex regex = new Regex(@"Sec-WebSocket-Protocol:(?.+)", RegexOptions.IgnoreCase); + Match match = regex.Match(httpHeader); + + if (match.Success) + { + const int MAX_LEN = 2048; + if (match.Length > MAX_LEN) + { + throw new EntityTooLargeException($"Sec-WebSocket-Protocol exceeded the maximum of length of {MAX_LEN}"); + } + + // extract a csv list of sub protocols (in order of highest preference first) + string csv = match.Groups["protocols"].Value.Trim(); + return csv.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + .Select(x => x.Trim()) + .ToList(); + } + + return new List(); + } + + /// + /// Reads the HTTP response code from the http response string + /// + /// The response string + /// the response code + public static string ReadHttpResponseCode(string response) + { + Regex getRegex = new Regex(@"HTTP\/1\.1 (.*)", RegexOptions.IgnoreCase); + Match getRegexMatch = getRegex.Match(response); + + if (getRegexMatch.Success) + { + // extract the path attribute from the first line of the header + return getRegexMatch.Groups[1].Value.Trim(); + } + + return null; + } + + /// + /// Writes an HTTP response string to the stream + /// + /// The response (without the new line characters) + /// The stream to write to + /// The cancellation token + public static async Task WriteHttpHeaderAsync(string response, Stream stream, CancellationToken token) + { + response = response.Trim() + "\r\n\r\n"; + Byte[] bytes = Encoding.UTF8.GetBytes(response); + await stream.WriteAsync(bytes, 0, bytes.Length, token); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/HttpHelper.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/HttpHelper.cs.meta new file mode 100644 index 0000000..808420c --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/HttpHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c90b5378af58402987e8a2938d763f2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IBufferPool.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IBufferPool.cs new file mode 100644 index 0000000..395a281 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IBufferPool.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace Ninja.WebSockets +{ + public interface IBufferPool + { + /// + /// Gets a MemoryStream built from a buffer plucked from a thread safe pool + /// The pool grows automatically. + /// Closing the memory stream clears the buffer and returns it to the pool + /// + MemoryStream GetBuffer(); + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IBufferPool.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IBufferPool.cs.meta new file mode 100644 index 0000000..cb3da58 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IBufferPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 894bb86ff9cbe4179a6764904f9dd742 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IPingPongManager.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IPingPongManager.cs new file mode 100644 index 0000000..e87dbb6 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IPingPongManager.cs @@ -0,0 +1,24 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Ninja.WebSockets +{ + /// + /// Ping Pong Manager used to facilitate ping pong WebSocket messages + /// + interface IPingPongManager + { + /// + /// Raised when a Pong frame is received + /// + event EventHandler Pong; + + /// + /// Sends a ping frame + /// + /// The payload (must be 125 bytes of less) + /// The cancellation token + Task SendPing(ArraySegment payload, CancellationToken cancellation); + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IPingPongManager.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IPingPongManager.cs.meta new file mode 100644 index 0000000..9ac6ac5 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IPingPongManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1432676d0074e4a7ca123228797fe0ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketClientFactory.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketClientFactory.cs new file mode 100644 index 0000000..7eb1071 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketClientFactory.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using System.Net.WebSockets; +using System.Threading; +using System.Threading.Tasks; + +namespace Ninja.WebSockets +{ + /// + /// Web socket client factory used to open web socket client connections + /// + public interface IWebSocketClientFactory + { + /// + /// Connect with default options + /// + /// The WebSocket uri to connect to (e.g. ws://example.com or wss://example.com for SSL) + /// The optional cancellation token + /// A connected web socket instance + Task ConnectAsync(Uri uri, CancellationToken token = default(CancellationToken)); + + /// + /// Connect with options specified + /// + /// The WebSocket uri to connect to (e.g. ws://example.com or wss://example.com for SSL) + /// The WebSocket client options + /// The optional cancellation token + /// A connected web socket instance + Task ConnectAsync(Uri uri, WebSocketClientOptions options, CancellationToken token = default(CancellationToken)); + + /// + /// Connect with a stream that has already been opened and HTTP websocket upgrade request sent + /// This function will check the handshake response from the server and proceed if successful + /// Use this function if you have specific requirements to open a conenction like using special http headers and cookies + /// You will have to build your own HTTP websocket upgrade request + /// You may not even choose to use TCP/IP and this function will allow you to do that + /// + /// The full duplex response stream from the server + /// The secWebSocketKey you used in the handshake request + /// The WebSocket client options + /// The optional cancellation token + /// + Task ConnectAsync(Stream responseStream, string secWebSocketKey, WebSocketClientOptions options, CancellationToken token = default(CancellationToken)); + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketClientFactory.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketClientFactory.cs.meta new file mode 100644 index 0000000..7039071 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketClientFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 290e337adc73544809ef6db4d09ec5bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketServerFactory.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketServerFactory.cs new file mode 100644 index 0000000..6915463 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketServerFactory.cs @@ -0,0 +1,40 @@ +using System.IO; +using System.Net.WebSockets; +using System.Threading; +using System.Threading.Tasks; + +namespace Ninja.WebSockets +{ + /// + /// Web socket server factory used to open web socket server connections + /// + public interface IWebSocketServerFactory + { + /// + /// Reads a http header information from a stream and decodes the parts relating to the WebSocket protocot upgrade + /// + /// The network stream + /// The optional cancellation token + /// Http data read from the stream + Task ReadHttpHeaderFromStreamAsync(Stream stream, CancellationToken token = default(CancellationToken)); + + /// + /// Accept web socket with default options + /// Call ReadHttpHeaderFromStreamAsync first to get WebSocketHttpContext + /// + /// The http context used to initiate this web socket request + /// The optional cancellation token + /// A connected web socket + Task AcceptWebSocketAsync(WebSocketHttpContext context, CancellationToken token = default(CancellationToken)); + + /// + /// Accept web socket with options specified + /// Call ReadHttpHeaderFromStreamAsync first to get WebSocketHttpContext + /// + /// The http context used to initiate this web socket request + /// The web socket options + /// The optional cancellation token + /// A connected web socket + Task AcceptWebSocketAsync(WebSocketHttpContext context, WebSocketServerOptions options, CancellationToken token = default(CancellationToken)); + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketServerFactory.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketServerFactory.cs.meta new file mode 100644 index 0000000..391cb7f --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/IWebSocketServerFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 33e062311740342db82c2f6e53fbce73 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal.meta new file mode 100644 index 0000000..b6bf8b2 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 58fcf4fbb7c9b47eeaf267adb27810d3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/BinaryReaderWriter.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/BinaryReaderWriter.cs new file mode 100644 index 0000000..e31c222 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/BinaryReaderWriter.cs @@ -0,0 +1,149 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System; +using System.IO; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; + +namespace Ninja.WebSockets.Internal +{ + internal class BinaryReaderWriter + { + public static async Task ReadExactly(int length, Stream stream, ArraySegment buffer, CancellationToken cancellationToken) + { + if (buffer.Count < length) + { + // This will happen if the calling function supplied a buffer that was too small to fit the payload of the websocket frame. + // Note that this can happen on the close handshake where the message size can be larger than the regular payload + throw new InternalBufferOverflowException($"Unable to read {length} bytes into buffer (offset: {buffer.Offset} size: {buffer.Count}). Use a larger read buffer"); + } + + int offset = 0; + while (offset < length) + { + int bytesRead = 0; + + NetworkStream networkStream = stream as NetworkStream; + if (networkStream != null && networkStream.DataAvailable) + { + // paul: if data is available read it immediatelly. + // in my tests this performed a lot better, because ReadAsync always waited until + // the next frame. + bytesRead = stream.Read(buffer.Array, buffer.Offset + offset, length - offset); + } + else + { + bytesRead = await stream.ReadAsync(buffer.Array, buffer.Offset + offset, length - offset, cancellationToken); + } + + if (bytesRead == 0) + { + throw new EndOfStreamException(string.Format("Unexpected end of stream encountered whilst attempting to read {0:#,##0} bytes", length)); + } + + offset += bytesRead; + } + } + + public static async Task ReadUShortExactly(Stream stream, bool isLittleEndian, ArraySegment buffer, CancellationToken cancellationToken) + { + await ReadExactly(2, stream, buffer, cancellationToken); + + if (!isLittleEndian) + { + Array.Reverse(buffer.Array, buffer.Offset, 2); // big endian + } + + return BitConverter.ToUInt16(buffer.Array, buffer.Offset); + } + + public static async Task ReadULongExactly(Stream stream, bool isLittleEndian, ArraySegment buffer, CancellationToken cancellationToken) + { + await ReadExactly(8, stream, buffer, cancellationToken); + + if (!isLittleEndian) + { + Array.Reverse(buffer.Array, buffer.Offset, 8); // big endian + } + + return BitConverter.ToUInt64(buffer.Array, buffer.Offset); + } + + public static async Task ReadLongExactly(Stream stream, bool isLittleEndian, ArraySegment buffer, CancellationToken cancellationToken) + { + await ReadExactly(8, stream, buffer, cancellationToken); + + if (!isLittleEndian) + { + Array.Reverse(buffer.Array, buffer.Offset, 8); // big endian + } + + return BitConverter.ToInt64(buffer.Array, buffer.Offset); + } + + public static void WriteInt(int value, Stream stream, bool isLittleEndian) + { + byte[] buffer = BitConverter.GetBytes(value); + if (BitConverter.IsLittleEndian && !isLittleEndian) + { + Array.Reverse(buffer); + } + + stream.Write(buffer, 0, buffer.Length); + } + + public static void WriteULong(ulong value, Stream stream, bool isLittleEndian) + { + byte[] buffer = BitConverter.GetBytes(value); + if (BitConverter.IsLittleEndian && ! isLittleEndian) + { + Array.Reverse(buffer); + } + + stream.Write(buffer, 0, buffer.Length); + } + + public static void WriteLong(long value, Stream stream, bool isLittleEndian) + { + byte[] buffer = BitConverter.GetBytes(value); + if (BitConverter.IsLittleEndian && !isLittleEndian) + { + Array.Reverse(buffer); + } + + stream.Write(buffer, 0, buffer.Length); + } + + public static void WriteUShort(ushort value, Stream stream, bool isLittleEndian) + { + byte[] buffer = BitConverter.GetBytes(value); + if (BitConverter.IsLittleEndian && !isLittleEndian) + { + Array.Reverse(buffer); + } + + stream.Write(buffer, 0, buffer.Length); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/BinaryReaderWriter.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/BinaryReaderWriter.cs.meta new file mode 100644 index 0000000..8671b81 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/BinaryReaderWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2379de83fde9446689e7fd94d8cefca1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/Events.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/Events.cs new file mode 100644 index 0000000..310092e --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/Events.cs @@ -0,0 +1,393 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System; +using System.Diagnostics.Tracing; +using System.Net.Security; +using System.Net.WebSockets; + +namespace Ninja.WebSockets.Internal +{ + /// + /// Use the Guid to locate this EventSource in PerfView using the Additional Providers box (without wildcard characters) + /// + [EventSource(Name = "Ninja-WebSockets", Guid = "7DE1A071-4F85-4DBD-8FB1-EE8D3845E087")] + internal sealed class Events : EventSource + { + public static Events Log = new Events(); + + [Event(1, Level = EventLevel.Informational)] + public void ClientConnectingToIpAddress(Guid guid, string ipAddress, int port) + { + if (this.IsEnabled()) + { + WriteEvent(1, guid, ipAddress, port); + } + } + + [Event(2, Level = EventLevel.Informational)] + public void ClientConnectingToHost(Guid guid, string host, int port) + { + if (this.IsEnabled()) + { + WriteEvent(2, guid, host, port); + } + } + + [Event(3, Level = EventLevel.Informational)] + public void AttemtingToSecureSslConnection(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(3, guid); + } + } + + [Event(4, Level = EventLevel.Informational)] + public void ConnectionSecured(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(4, guid); + } + } + + [Event(5, Level = EventLevel.Informational)] + public void ConnectionNotSecure(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(5, guid); + } + } + + [Event(6, Level = EventLevel.Error)] + public void SslCertificateError(SslPolicyErrors sslPolicyErrors) + { + if (this.IsEnabled()) + { + WriteEvent(6, sslPolicyErrors); + } + } + + [Event(7, Level = EventLevel.Informational)] + public void HandshakeSent(Guid guid, string httpHeader) + { + if (this.IsEnabled()) + { + WriteEvent(7, guid, httpHeader ?? string.Empty); + } + } + + [Event(8, Level = EventLevel.Informational)] + public void ReadingHttpResponse(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(8, guid); + } + } + + [Event(9, Level = EventLevel.Error)] + public void ReadHttpResponseError(Guid guid, string exception) + { + if (this.IsEnabled()) + { + WriteEvent(9, guid, exception ?? string.Empty); + } + } + + [Event(10, Level = EventLevel.Warning)] + public void InvalidHttpResponseCode(Guid guid, string response) + { + if (this.IsEnabled()) + { + WriteEvent(10, guid, response ?? string.Empty); + } + } + + [Event(11, Level = EventLevel.Error)] + public void HandshakeFailure(Guid guid, string message) + { + if (this.IsEnabled()) + { + WriteEvent(11, guid, message ?? string.Empty); + } + } + + [Event(12, Level = EventLevel.Informational)] + public void ClientHandshakeSuccess(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(12, guid); + } + } + + [Event(13, Level = EventLevel.Informational)] + public void ServerHandshakeSuccess(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(13, guid); + } + } + + [Event(14, Level = EventLevel.Informational)] + public void AcceptWebSocketStarted(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(14, guid); + } + } + + [Event(15, Level = EventLevel.Informational)] + public void SendingHandshakeResponse(Guid guid, string response) + { + if (this.IsEnabled()) + { + WriteEvent(15, guid, response ?? string.Empty); + } + } + + [Event(16, Level = EventLevel.Error)] + public void WebSocketVersionNotSupported(Guid guid, string exception) + { + if (this.IsEnabled()) + { + WriteEvent(16, guid, exception ?? string.Empty); + } + } + + [Event(17, Level = EventLevel.Error)] + public void BadRequest(Guid guid, string exception) + { + if (this.IsEnabled()) + { + WriteEvent(17, guid, exception ?? string.Empty); + } + } + + [Event(18, Level = EventLevel.Informational)] + public void UsePerMessageDeflate(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(18, guid); + } + } + + [Event(19, Level = EventLevel.Informational)] + public void NoMessageCompression(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(19, guid); + } + } + + [Event(20, Level = EventLevel.Informational)] + public void KeepAliveIntervalZero(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(20, guid); + } + } + + [Event(21, Level = EventLevel.Informational)] + public void PingPongManagerStarted(Guid guid, int keepAliveIntervalSeconds) + { + if (this.IsEnabled()) + { + WriteEvent(21, guid, keepAliveIntervalSeconds); + } + } + + [Event(22, Level = EventLevel.Informational)] + public void PingPongManagerEnded(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(22, guid); + } + } + + [Event(23, Level = EventLevel.Warning)] + public void KeepAliveIntervalExpired(Guid guid, int keepAliveIntervalSeconds) + { + if (this.IsEnabled()) + { + WriteEvent(23, guid, keepAliveIntervalSeconds); + } + } + + [Event(24, Level = EventLevel.Warning)] + public void CloseOutputAutoTimeout(Guid guid, WebSocketCloseStatus closeStatus, string statusDescription, string exception) + { + if (this.IsEnabled()) + { + WriteEvent(24, guid, closeStatus, statusDescription ?? string.Empty, exception ?? string.Empty); + } + } + + [Event(25, Level = EventLevel.Error)] + public void CloseOutputAutoTimeoutCancelled(Guid guid, int timeoutSeconds, WebSocketCloseStatus closeStatus, string statusDescription, string exception) + { + if (this.IsEnabled()) + { + WriteEvent(25, guid, timeoutSeconds, closeStatus, statusDescription ?? string.Empty, exception ?? string.Empty); + } + } + + [Event(26, Level = EventLevel.Error)] + public void CloseOutputAutoTimeoutError(Guid guid, string closeException, WebSocketCloseStatus closeStatus, string statusDescription, string exception) + { + if (this.IsEnabled()) + { + WriteEvent(26, guid, closeException ?? string.Empty, closeStatus, statusDescription ?? string.Empty, exception ?? string.Empty); + } + } + + [Event(27, Level = EventLevel.Warning)] + public void TryGetBufferNotSupported(Guid guid, string streamType) + { + if (this.IsEnabled()) + { + WriteEvent(27, guid, streamType ?? string.Empty); + } + } + + [Event(28, Level = EventLevel.Verbose)] + public void SendingFrame(Guid guid, WebSocketOpCode webSocketOpCode, bool isFinBitSet, int numBytes, bool isPayloadCompressed) + { + if (this.IsEnabled(EventLevel.Verbose, EventKeywords.None)) + { + WriteEvent(28, guid, webSocketOpCode, isFinBitSet, numBytes, isPayloadCompressed); + } + } + + [Event(29, Level = EventLevel.Verbose)] + public void ReceivedFrame(Guid guid, WebSocketOpCode webSocketOpCode, bool isFinBitSet, int numBytes) + { + if (this.IsEnabled(EventLevel.Verbose, EventKeywords.None)) + { + WriteEvent(29, guid, webSocketOpCode, isFinBitSet, numBytes); + } + } + + [Event(30, Level = EventLevel.Informational)] + public void CloseOutputNoHandshake(Guid guid, WebSocketCloseStatus? closeStatus, string statusDescription) + { + if (this.IsEnabled()) + { + string closeStatusDesc = $"{closeStatus}"; + WriteEvent(30, guid, closeStatusDesc, statusDescription ?? string.Empty); + } + } + + [Event(31, Level = EventLevel.Informational)] + public void CloseHandshakeStarted(Guid guid, WebSocketCloseStatus? closeStatus, string statusDescription) + { + if (this.IsEnabled()) + { + string closeStatusDesc = $"{closeStatus}"; + WriteEvent(31, guid, closeStatusDesc, statusDescription ?? string.Empty); + } + } + + [Event(32, Level = EventLevel.Informational)] + public void CloseHandshakeRespond(Guid guid, WebSocketCloseStatus? closeStatus, string statusDescription) + { + if (this.IsEnabled()) + { + string closeStatusDesc = $"{closeStatus}"; + WriteEvent(32, guid, closeStatusDesc, statusDescription ?? string.Empty); + } + } + + [Event(33, Level = EventLevel.Informational)] + public void CloseHandshakeComplete(Guid guid) + { + if (this.IsEnabled()) + { + WriteEvent(33, guid); + } + } + + [Event(34, Level = EventLevel.Warning)] + public void CloseFrameReceivedInUnexpectedState(Guid guid, WebSocketState webSocketState, WebSocketCloseStatus? closeStatus, string statusDescription) + { + if (this.IsEnabled()) + { + string closeStatusDesc = $"{closeStatus}"; + WriteEvent(34, guid, webSocketState, closeStatusDesc, statusDescription ?? string.Empty); + } + } + + [Event(35, Level = EventLevel.Informational)] + public void WebSocketDispose(Guid guid, WebSocketState webSocketState) + { + if (this.IsEnabled()) + { + WriteEvent(35, guid, webSocketState); + } + } + + [Event(36, Level = EventLevel.Warning)] + public void WebSocketDisposeCloseTimeout(Guid guid, WebSocketState webSocketState) + { + if (this.IsEnabled()) + { + WriteEvent(36, guid, webSocketState); + } + } + + [Event(37, Level = EventLevel.Error)] + public void WebSocketDisposeError(Guid guid, WebSocketState webSocketState, string exception) + { + if (this.IsEnabled()) + { + WriteEvent(37, guid, webSocketState, exception ?? string.Empty); + } + } + + [Event(38, Level = EventLevel.Warning)] + public void InvalidStateBeforeClose(Guid guid, WebSocketState webSocketState) + { + if (this.IsEnabled()) + { + WriteEvent(38, guid, webSocketState); + } + } + + [Event(39, Level = EventLevel.Warning)] + public void InvalidStateBeforeCloseOutput(Guid guid, WebSocketState webSocketState) + { + if (this.IsEnabled()) + { + WriteEvent(39, guid, webSocketState); + } + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/Events.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/Events.cs.meta new file mode 100644 index 0000000..3e533be --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/Events.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7713ae9d113e145389c0a175d58090be +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrame.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrame.cs new file mode 100644 index 0000000..eb37317 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrame.cs @@ -0,0 +1,31 @@ +using System.Net.WebSockets; + +namespace Ninja.WebSockets.Internal +{ + internal class WebSocketFrame + { + public bool IsFinBitSet { get; private set; } + + public WebSocketOpCode OpCode { get; private set; } + + public int Count { get; private set; } + + public WebSocketCloseStatus? CloseStatus { get; private set; } + + public string CloseStatusDescription { get; private set; } + + public WebSocketFrame(bool isFinBitSet, WebSocketOpCode webSocketOpCode, int count) + { + IsFinBitSet = isFinBitSet; + OpCode = webSocketOpCode; + Count = count; + } + + public WebSocketFrame(bool isFinBitSet, WebSocketOpCode webSocketOpCode, int count, WebSocketCloseStatus closeStatus, string closeStatusDescription) : this(isFinBitSet, webSocketOpCode, count) + { + CloseStatus = closeStatus; + CloseStatusDescription = closeStatusDescription; + } + + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrame.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrame.cs.meta new file mode 100644 index 0000000..f27e26d --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrame.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a4e8a4f1bcb0c49d7a82e5f430c85e2d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameCommon.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameCommon.cs new file mode 100644 index 0000000..48022bb --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameCommon.cs @@ -0,0 +1,62 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System; + +namespace Ninja.WebSockets.Internal +{ + internal static class WebSocketFrameCommon + { + public const int MaskKeyLength = 4; + + /// + /// Mutate payload with the mask key + /// This is a reversible process + /// If you apply this to masked data it will be unmasked and visa versa + /// + /// The 4 byte mask key + /// The payload to mutate + public static void ToggleMask(ArraySegment maskKey, ArraySegment payload) + { + if (maskKey.Count != MaskKeyLength) + { + throw new Exception($"MaskKey key must be {MaskKeyLength} bytes"); + } + + byte[] buffer = payload.Array; + byte[] maskKeyArray = maskKey.Array; + int payloadOffset = payload.Offset; + int payloadCount = payload.Count; + int maskKeyOffset = maskKey.Offset; + + // apply the mask key (this is a reversible process so no need to copy the payload) + // NOTE: this is a hot function + // TODO: make this faster + for (int i = payloadOffset; i < payloadCount; i++) + { + int payloadIndex = i - payloadOffset; // index should start at zero + int maskKeyIndex = maskKeyOffset + (payloadIndex % MaskKeyLength); + buffer[i] = (Byte)(buffer[i] ^ maskKeyArray[maskKeyIndex]); + } + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameCommon.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameCommon.cs.meta new file mode 100644 index 0000000..0011ea2 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameCommon.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: adbf6c11b66794c0494acf9c713a6759 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameReader.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameReader.cs new file mode 100644 index 0000000..e8ff65f --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameReader.cs @@ -0,0 +1,168 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System; +using System.IO; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Ninja.WebSockets.Internal +{ + /// + /// Reads a WebSocket frame + /// see http://tools.ietf.org/html/rfc6455 for specification + /// + internal static class WebSocketFrameReader + { + /// + /// Read a WebSocket frame from the stream + /// + /// The stream to read from + /// The buffer to read into + /// the cancellation token + /// A websocket frame + public static async Task ReadAsync(Stream fromStream, ArraySegment intoBuffer, CancellationToken cancellationToken) + { + // allocate a small buffer to read small chunks of data from the stream + ArraySegment smallBuffer = new ArraySegment(new byte[8]); + + await BinaryReaderWriter.ReadExactly(2, fromStream, smallBuffer, cancellationToken); + byte byte1 = smallBuffer.Array[0]; + byte byte2 = smallBuffer.Array[1]; + + // process first byte + byte finBitFlag = 0x80; + byte opCodeFlag = 0x0F; + bool isFinBitSet = (byte1 & finBitFlag) == finBitFlag; + WebSocketOpCode opCode = (WebSocketOpCode) (byte1 & opCodeFlag); + + // read and process second byte + byte maskFlag = 0x80; + bool isMaskBitSet = (byte2 & maskFlag) == maskFlag; + uint len = await ReadLength(byte2, smallBuffer, fromStream, cancellationToken); + int count = (int)len; + + try + { + // use the masking key to decode the data if needed + if (isMaskBitSet) + { + ArraySegment maskKey = new ArraySegment(smallBuffer.Array, 0, WebSocketFrameCommon.MaskKeyLength); + await BinaryReaderWriter.ReadExactly(maskKey.Count, fromStream, maskKey, cancellationToken); + await BinaryReaderWriter.ReadExactly(count, fromStream, intoBuffer, cancellationToken); + ArraySegment payloadToMask = new ArraySegment(intoBuffer.Array, intoBuffer.Offset, count); + WebSocketFrameCommon.ToggleMask(maskKey, payloadToMask); + } + else + { + await BinaryReaderWriter.ReadExactly(count, fromStream, intoBuffer, cancellationToken); + } + } + catch (InternalBufferOverflowException e) + { + throw new InternalBufferOverflowException($"Supplied buffer too small to read {0} bytes from {Enum.GetName(typeof(WebSocketOpCode), opCode)} frame", e); + } + + if (opCode == WebSocketOpCode.ConnectionClose) + { + return DecodeCloseFrame(isFinBitSet, opCode, count, intoBuffer); + } + else + { + // note that by this point the payload will be populated + return new WebSocketFrame(isFinBitSet, opCode, count); + } + } + + /// + /// Extracts close status and close description information from the web socket frame + /// + static WebSocketFrame DecodeCloseFrame(bool isFinBitSet, WebSocketOpCode opCode, int count, ArraySegment buffer) + { + WebSocketCloseStatus closeStatus; + string closeStatusDescription; + + if (count >= 2) + { + Array.Reverse(buffer.Array, buffer.Offset, 2); // network byte order + int closeStatusCode = (int)BitConverter.ToUInt16(buffer.Array, buffer.Offset); + if (Enum.IsDefined(typeof(WebSocketCloseStatus), closeStatusCode)) + { + closeStatus = (WebSocketCloseStatus)closeStatusCode; + } + else + { + closeStatus = WebSocketCloseStatus.Empty; + } + + int offset = buffer.Offset + 2; + int descCount = count - 2; + + if (descCount > 0) + { + closeStatusDescription = Encoding.UTF8.GetString(buffer.Array, offset, descCount); + } + else + { + closeStatusDescription = null; + } + } + else + { + closeStatus = WebSocketCloseStatus.Empty; + closeStatusDescription = null; + } + + return new WebSocketFrame(isFinBitSet, opCode, count, closeStatus, closeStatusDescription); + } + + /// + /// Reads the length of the payload according to the contents of byte2 + /// + static async Task ReadLength(byte byte2, ArraySegment smallBuffer, Stream fromStream, CancellationToken cancellationToken) + { + byte payloadLenFlag = 0x7F; + uint len = (uint) (byte2 & payloadLenFlag); + + // read a short length or a long length depending on the value of len + if (len == 126) + { + len = await BinaryReaderWriter.ReadUShortExactly(fromStream, false, smallBuffer, cancellationToken); + } + else if (len == 127) + { + len = (uint) await BinaryReaderWriter.ReadULongExactly(fromStream, false, smallBuffer, cancellationToken); + const uint maxLen = 2147483648; // 2GB - not part of the spec but just a precaution. Send large volumes of data in smaller frames. + + // protect ourselves against bad data + if (len > maxLen || len < 0) + { + throw new ArgumentOutOfRangeException($"Payload length out of range. Min 0 max 2GB. Actual {len:#,##0} bytes."); + } + } + + return len; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameReader.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameReader.cs.meta new file mode 100644 index 0000000..370baf4 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 092a4b88aabbc4d3b91f6a82c40b47e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameWriter.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameWriter.cs new file mode 100644 index 0000000..7ecf274 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameWriter.cs @@ -0,0 +1,100 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System.IO; +using System; +using System.Net.WebSockets; +using System.Text; + +namespace Ninja.WebSockets.Internal +{ + // see http://tools.ietf.org/html/rfc6455 for specification + // see fragmentation section for sending multi part messages + // EXAMPLE: For a text message sent as three fragments, + // the first fragment would have an opcode of TextFrame and isLastFrame false, + // the second fragment would have an opcode of ContinuationFrame and isLastFrame false, + // the third fragment would have an opcode of ContinuationFrame and isLastFrame true. + internal static class WebSocketFrameWriter + { + /// + /// This is used for data masking so that web proxies don't cache the data + /// Therefore, there are no cryptographic concerns + /// + static readonly Random _random; + + static WebSocketFrameWriter() + { + _random = new Random((int)DateTime.Now.Ticks); + } + + /// + /// No async await stuff here because we are dealing with a memory stream + /// + /// The web socket opcode + /// Array segment to get payload data from + /// Stream to write to + /// True is this is the last frame in this message (usually true) + public static void Write(WebSocketOpCode opCode, ArraySegment fromPayload, MemoryStream toStream, bool isLastFrame, bool isClient) + { + MemoryStream memoryStream = toStream; + byte finBitSetAsByte = isLastFrame ? (byte)0x80 : (byte)0x00; + byte byte1 = (byte)(finBitSetAsByte | (byte)opCode); + memoryStream.WriteByte(byte1); + + // NB, set the mask flag if we are constructing a client frame + byte maskBitSetAsByte = isClient ? (byte)0x80 : (byte)0x00; + + // depending on the size of the length we want to write it as a byte, ushort or ulong + if (fromPayload.Count < 126) + { + byte byte2 = (byte)(maskBitSetAsByte | (byte)fromPayload.Count); + memoryStream.WriteByte(byte2); + } + else if (fromPayload.Count <= ushort.MaxValue) + { + byte byte2 = (byte)(maskBitSetAsByte | 126); + memoryStream.WriteByte(byte2); + BinaryReaderWriter.WriteUShort((ushort)fromPayload.Count, memoryStream, false); + } + else + { + byte byte2 = (byte)(maskBitSetAsByte | 127); + memoryStream.WriteByte(byte2); + BinaryReaderWriter.WriteULong((ulong)fromPayload.Count, memoryStream, false); + } + + // if we are creating a client frame then we MUST mack the payload as per the spec + if (isClient) + { + byte[] maskKey = new byte[WebSocketFrameCommon.MaskKeyLength]; + _random.NextBytes(maskKey); + memoryStream.Write(maskKey, 0, maskKey.Length); + + // mask the payload + ArraySegment maskKeyArraySegment = new ArraySegment(maskKey, 0, maskKey.Length); + WebSocketFrameCommon.ToggleMask(maskKeyArraySegment, fromPayload); + } + + memoryStream.Write(fromPayload.Array, fromPayload.Offset, fromPayload.Count); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameWriter.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameWriter.cs.meta new file mode 100644 index 0000000..acd29fa --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketFrameWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: df337f1f7ba5245f7acadbe2e44b86bd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketImplementation.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketImplementation.cs new file mode 100644 index 0000000..1e6f708 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketImplementation.cs @@ -0,0 +1,628 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Net.Security; +using System.Net.Sockets; +using System.Net.WebSockets; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +#if RELEASESIGNED +[assembly: InternalsVisibleTo("Ninja.WebSockets.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b1707056f4761b7846ed503642fcde97fc350c939f78026211304a56ba51e094c9cefde77fadce5b83c0a621c17f032c37c520b6d9ab2da8291a21472175d9caad55bf67bab4bffb46a96f864ea441cf695edc854296e02a44062245a4e09ccd9a77ef6146ecf941ce1d9da078add54bc2d4008decdac2fa2b388e17794ee6a6")] +#else +[assembly: InternalsVisibleTo("Ninja.WebSockets.UnitTests")] +#endif + +namespace Ninja.WebSockets.Internal +{ + /// + /// Main implementation of the WebSocket abstract class + /// + internal class WebSocketImplementation : WebSocket + { + readonly Guid _guid; + readonly Func _recycledStreamFactory; + readonly Stream _stream; + readonly bool _includeExceptionInCloseResponse; + readonly bool _isClient; + readonly string _subProtocol; + CancellationTokenSource _internalReadCts; + WebSocketState _state; + bool _isContinuationFrame; + WebSocketMessageType _continuationFrameMessageType = WebSocketMessageType.Binary; + readonly bool _usePerMessageDeflate = false; + bool _tryGetBufferFailureLogged = false; + const int MAX_PING_PONG_PAYLOAD_LEN = 125; + WebSocketCloseStatus? _closeStatus; + string _closeStatusDescription; + + public event EventHandler Pong; + + Queue> _messageQueue = new Queue>(); + SemaphoreSlim _sendSemaphore = new SemaphoreSlim(1, 1); + + internal WebSocketImplementation(Guid guid, Func recycledStreamFactory, Stream stream, TimeSpan keepAliveInterval, string secWebSocketExtensions, bool includeExceptionInCloseResponse, bool isClient, string subProtocol) + { + _guid = guid; + _recycledStreamFactory = recycledStreamFactory; + _stream = stream; + _isClient = isClient; + _subProtocol = subProtocol; + _internalReadCts = new CancellationTokenSource(); + _state = WebSocketState.Open; + + if (secWebSocketExtensions?.IndexOf("permessage-deflate") >= 0) + { + _usePerMessageDeflate = true; + Events.Log.UsePerMessageDeflate(guid); + } + else + { + Events.Log.NoMessageCompression(guid); + } + + KeepAliveInterval = keepAliveInterval; + _includeExceptionInCloseResponse = includeExceptionInCloseResponse; + if (keepAliveInterval.Ticks < 0) + { + throw new InvalidOperationException("KeepAliveInterval must be Zero or positive"); + } + + if (keepAliveInterval == TimeSpan.Zero) + { + Events.Log.KeepAliveIntervalZero(guid); + } + else + { + // the ping pong manager starts a task + // but we don't have to keep a reference to it +#pragma warning disable 0219 + PingPongManager pingPongManager = new PingPongManager(guid, this, keepAliveInterval, _internalReadCts.Token); +#pragma warning restore 0219 + } + } + + public override WebSocketCloseStatus? CloseStatus => _closeStatus; + + public override string CloseStatusDescription => _closeStatusDescription; + + public override WebSocketState State { get { return _state; } } + + public override string SubProtocol => _subProtocol; + + public TimeSpan KeepAliveInterval { get; private set; } + + /// + /// Receive web socket result + /// + /// The buffer to copy data into + /// The cancellation token + /// The web socket result details + public override async Task ReceiveAsync(ArraySegment buffer, CancellationToken cancellationToken) + { + try + { + // we may receive control frames so reading needs to happen in an infinite loop + while (true) + { + // allow this operation to be cancelled from iniside OR outside this instance + using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_internalReadCts.Token, cancellationToken)) + { + WebSocketFrame frame = null; + try + { + frame = await WebSocketFrameReader.ReadAsync(_stream, buffer, linkedCts.Token); + Events.Log.ReceivedFrame(_guid, frame.OpCode, frame.IsFinBitSet, frame.Count); + } + catch (SocketException) + { + // do nothing, the socket has been disconnected + } + catch (InternalBufferOverflowException ex) + { + await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.MessageTooBig, "Frame too large to fit in buffer. Use message fragmentation", ex); + throw; + } + catch (ArgumentOutOfRangeException ex) + { + await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.ProtocolError, "Payload length out of range", ex); + throw; + } + catch (EndOfStreamException ex) + { + await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.InvalidPayloadData, "Unexpected end of stream encountered", ex); + throw; + } + catch (OperationCanceledException ex) + { + await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.EndpointUnavailable, "Operation cancelled", ex); + throw; + } + catch (Exception ex) + { + await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.InternalServerError, "Error reading WebSocket frame", ex); + throw; + } + + switch (frame.OpCode) + { + case WebSocketOpCode.ConnectionClose: + return await RespondToCloseFrame(frame, buffer, linkedCts.Token); + case WebSocketOpCode.Ping: + ArraySegment pingPayload = new ArraySegment(buffer.Array, buffer.Offset, frame.Count); + await SendPongAsync(pingPayload, linkedCts.Token); + break; + case WebSocketOpCode.Pong: + ArraySegment pongBuffer = new ArraySegment(buffer.Array, frame.Count, buffer.Offset); + Pong?.Invoke(this, new PongEventArgs(pongBuffer)); + break; + case WebSocketOpCode.TextFrame: + if (!frame.IsFinBitSet) + { + // continuation frames will follow, record the message type Text + _continuationFrameMessageType = WebSocketMessageType.Text; + } + return new WebSocketReceiveResult(frame.Count, WebSocketMessageType.Text, frame.IsFinBitSet); + case WebSocketOpCode.BinaryFrame: + if (!frame.IsFinBitSet) + { + // continuation frames will follow, record the message type Binary + _continuationFrameMessageType = WebSocketMessageType.Binary; + } + return new WebSocketReceiveResult(frame.Count, WebSocketMessageType.Binary, frame.IsFinBitSet); + case WebSocketOpCode.ContinuationFrame: + return new WebSocketReceiveResult(frame.Count, _continuationFrameMessageType, frame.IsFinBitSet); + default: + Exception ex = new NotSupportedException($"Unknown WebSocket opcode {frame.OpCode}"); + await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.ProtocolError, ex.Message, ex); + throw ex; + } + } + } + } + catch (Exception catchAll) + { + // Most exceptions will be caught closer to their source to send an appropriate close message (and set the WebSocketState) + // However, if an unhandled exception is encountered and a close message not sent then send one here + if (_state == WebSocketState.Open) + { + await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.InternalServerError, "Unexpected error reading from WebSocket", catchAll); + } + + throw; + } + } + + /// + /// Send data to the web socket + /// + /// the buffer containing data to send + /// The message type. Can be Text or Binary + /// True if this message is a standalone message (this is the norm) + /// If it is a multi-part message then false (and true for the last message) + /// the cancellation token + public override async Task SendAsync(ArraySegment buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) + { + using (MemoryStream stream = _recycledStreamFactory()) + { + WebSocketOpCode opCode = GetOppCode(messageType); + + if (_usePerMessageDeflate) + { + // NOTE: Compression is currently work in progress and should NOT be used in this library. + // The code below is very inefficient for small messages. Ideally we would like to have some sort of moving window + // of data to get the best compression. And we don't want to create new buffers which is bad for GC. + using (MemoryStream temp = new MemoryStream()) + { + DeflateStream deflateStream = new DeflateStream(temp, CompressionMode.Compress); + deflateStream.Write(buffer.Array, buffer.Offset, buffer.Count); + deflateStream.Flush(); + ArraySegment compressedBuffer = new ArraySegment(temp.ToArray()); + WebSocketFrameWriter.Write(opCode, compressedBuffer, stream, endOfMessage, _isClient); + Events.Log.SendingFrame(_guid, opCode, endOfMessage, compressedBuffer.Count, true); + } + } + else + { + WebSocketFrameWriter.Write(opCode, buffer, stream, endOfMessage, _isClient); + Events.Log.SendingFrame(_guid, opCode, endOfMessage, buffer.Count, false); + } + + await WriteStreamToNetwork(stream, cancellationToken); + _isContinuationFrame = !endOfMessage; // TODO: is this correct?? + } + } + + /// + /// Call this automatically from server side each keepAliveInterval period + /// NOTE: ping payload must be 125 bytes or less + /// + public async Task SendPingAsync(ArraySegment payload, CancellationToken cancellationToken) + { + if (payload.Count > MAX_PING_PONG_PAYLOAD_LEN) + { + throw new InvalidOperationException($"Cannot send Ping: Max ping message size {MAX_PING_PONG_PAYLOAD_LEN} exceeded: {payload.Count}"); + } + + if (_state == WebSocketState.Open) + { + using (MemoryStream stream = _recycledStreamFactory()) + { + WebSocketFrameWriter.Write(WebSocketOpCode.Ping, payload, stream, true, _isClient); + Events.Log.SendingFrame(_guid, WebSocketOpCode.Ping, true, payload.Count, false); + await WriteStreamToNetwork(stream, cancellationToken); + } + } + } + + /// + /// Aborts the WebSocket without sending a Close frame + /// + public override void Abort() + { + _state = WebSocketState.Aborted; + _internalReadCts.Cancel(); + } + + /// + /// Polite close (use the close handshake) + /// + public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) + { + if (_state == WebSocketState.Open) + { + using (MemoryStream stream = _recycledStreamFactory()) + { + ArraySegment buffer = BuildClosePayload(closeStatus, statusDescription); + WebSocketFrameWriter.Write(WebSocketOpCode.ConnectionClose, buffer, stream, true, _isClient); + Events.Log.CloseHandshakeStarted(_guid, closeStatus, statusDescription); + Events.Log.SendingFrame(_guid, WebSocketOpCode.ConnectionClose, true, buffer.Count, true); + await WriteStreamToNetwork(stream, cancellationToken); + _state = WebSocketState.CloseSent; + } + } + else + { + Events.Log.InvalidStateBeforeClose(_guid, _state); + } + } + + /// + /// Fire and forget close + /// + public override async Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) + { + if (_state == WebSocketState.Open) + { + _state = WebSocketState.Closed; // set this before we write to the network because the write may fail + + using (MemoryStream stream = _recycledStreamFactory()) + { + ArraySegment buffer = BuildClosePayload(closeStatus, statusDescription); + WebSocketFrameWriter.Write(WebSocketOpCode.ConnectionClose, buffer, stream, true, _isClient); + Events.Log.CloseOutputNoHandshake(_guid, closeStatus, statusDescription); + Events.Log.SendingFrame(_guid, WebSocketOpCode.ConnectionClose, true, buffer.Count, true); + await WriteStreamToNetwork(stream, cancellationToken); + } + } + else + { + Events.Log.InvalidStateBeforeCloseOutput(_guid, _state); + } + + // cancel pending reads + _internalReadCts.Cancel(); + } + + /// + /// Dispose will send a close frame if the connection is still open + /// + public override void Dispose() + { + Events.Log.WebSocketDispose(_guid, _state); + + try + { + if (_state == WebSocketState.Open) + { + CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + try + { + CloseOutputAsync(WebSocketCloseStatus.EndpointUnavailable, "Service is Disposed", cts.Token).Wait(); + } + catch (OperationCanceledException) + { + // log don't throw + Events.Log.WebSocketDisposeCloseTimeout(_guid, _state); + } + } + + // cancel pending reads - usually does nothing + _internalReadCts.Cancel(); + _stream.Close(); + } + catch (Exception ex) + { + // log dont throw + Events.Log.WebSocketDisposeError(_guid, _state, ex.ToString()); + } + } + + /// + /// Called when a Pong frame is received + /// + /// + protected virtual void OnPong(PongEventArgs e) + { + Pong?.Invoke(this, e); + } + + /// + /// As per the spec, write the close status followed by the close reason + /// + /// The close status + /// Optional extra close details + /// The payload to sent in the close frame + ArraySegment BuildClosePayload(WebSocketCloseStatus closeStatus, string statusDescription) + { + byte[] statusBuffer = BitConverter.GetBytes((ushort)closeStatus); + Array.Reverse(statusBuffer); // network byte order (big endian) + + if (statusDescription == null) + { + return new ArraySegment(statusBuffer); + } + else + { + byte[] descBuffer = Encoding.UTF8.GetBytes(statusDescription); + byte[] payload = new byte[statusBuffer.Length + descBuffer.Length]; + Buffer.BlockCopy(statusBuffer, 0, payload, 0, statusBuffer.Length); + Buffer.BlockCopy(descBuffer, 0, payload, statusBuffer.Length, descBuffer.Length); + return new ArraySegment(payload); + } + } + + /// NOTE: pong payload must be 125 bytes or less + /// Pong should contain the same payload as the ping + async Task SendPongAsync(ArraySegment payload, CancellationToken cancellationToken) + { + // as per websocket spec + if (payload.Count > MAX_PING_PONG_PAYLOAD_LEN) + { + Exception ex = new InvalidOperationException($"Max ping message size {MAX_PING_PONG_PAYLOAD_LEN} exceeded: {payload.Count}"); + await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.ProtocolError, ex.Message, ex); + throw ex; + } + + try + { + if (_state == WebSocketState.Open) + { + using (MemoryStream stream = _recycledStreamFactory()) + { + WebSocketFrameWriter.Write(WebSocketOpCode.Pong, payload, stream, true, _isClient); + Events.Log.SendingFrame(_guid, WebSocketOpCode.Pong, true, payload.Count, false); + await WriteStreamToNetwork(stream, cancellationToken); + } + } + } + catch (Exception ex) + { + await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.EndpointUnavailable, "Unable to send Pong response", ex); + throw; + } + } + + /// + /// Called when a Close frame is received + /// Send a response close frame if applicable + /// + async Task RespondToCloseFrame(WebSocketFrame frame, ArraySegment buffer, CancellationToken token) + { + _closeStatus = frame.CloseStatus; + _closeStatusDescription = frame.CloseStatusDescription; + + if (_state == WebSocketState.CloseSent) + { + // this is a response to close handshake initiated by this instance + _state = WebSocketState.Closed; + Events.Log.CloseHandshakeComplete(_guid); + } + else if (_state == WebSocketState.Open) + { + // do not echo the close payload back to the client, there is no requirement for it in the spec. + // However, the same CloseStatus as recieved should be sent back. + ArraySegment closePayload = new ArraySegment(new byte[0], 0, 0); + _state = WebSocketState.CloseReceived; + Events.Log.CloseHandshakeRespond(_guid, frame.CloseStatus, frame.CloseStatusDescription); + + using (MemoryStream stream = _recycledStreamFactory()) + { + WebSocketFrameWriter.Write(WebSocketOpCode.ConnectionClose, closePayload, stream, true, _isClient); + Events.Log.SendingFrame(_guid, WebSocketOpCode.ConnectionClose, true, closePayload.Count, false); + await WriteStreamToNetwork(stream, token); + } + } + else + { + Events.Log.CloseFrameReceivedInUnexpectedState(_guid, _state, frame.CloseStatus, frame.CloseStatusDescription); + } + + return new WebSocketReceiveResult(frame.Count, WebSocketMessageType.Close, frame.IsFinBitSet, frame.CloseStatus, frame.CloseStatusDescription); + } + + /// + /// Note that the way in which the stream buffer is accessed can lead to significant performance problems + /// You want to avoid a call to stream.ToArray to avoid extra memory allocation + /// MemoryStream can be configured to have its internal buffer accessible. + /// + ArraySegment GetBuffer(MemoryStream stream) + { +#if NET45 + // NET45 does not have a TryGetBuffer function on Stream + if (_tryGetBufferFailureLogged) + { + return new ArraySegment(stream.ToArray(), 0, (int)stream.Position); + } + + // note that a MemoryStream will throw an UnuthorizedAccessException if the internal buffer is not public. Set publiclyVisible = true + try + { + return new ArraySegment(stream.GetBuffer(), 0, (int)stream.Position); + } + catch (UnauthorizedAccessException) + { + Events.Log.TryGetBufferNotSupported(_guid, stream?.GetType()?.ToString()); + _tryGetBufferFailureLogged = true; + return new ArraySegment(stream.ToArray(), 0, (int)stream.Position); + } +#else + // Avoid calling ToArray on the MemoryStream because it allocates a new byte array on tha heap + // We avaoid this by attempting to access the internal memory stream buffer + // This works with supported streams like the recyclable memory stream and writable memory streams + if (!stream.TryGetBuffer(out ArraySegment buffer)) + { + if (!_tryGetBufferFailureLogged) + { + Events.Log.TryGetBufferNotSupported(_guid, stream?.GetType()?.ToString()); + _tryGetBufferFailureLogged = true; + } + + // internal buffer not suppoted, fall back to ToArray() + byte[] array = stream.ToArray(); + buffer = new ArraySegment(array, 0, array.Length); + } + + return new ArraySegment(buffer.Array, buffer.Offset, (int)stream.Position); +#endif + } + + /// + /// Puts data on the wire + /// + /// The stream to read data from + async Task WriteStreamToNetwork(MemoryStream stream, CancellationToken cancellationToken) + { + ArraySegment buffer = GetBuffer(stream); + if(_stream is SslStream) + { + _messageQueue.Enqueue(buffer); + await _sendSemaphore.WaitAsync(); + try + { + while (_messageQueue.Count > 0) + { + var _buf = _messageQueue.Dequeue(); + try + { + if (_stream != null && _stream.CanWrite) + { + await _stream.WriteAsync(_buf.Array, _buf.Offset, _buf.Count, cancellationToken).ConfigureAwait(false); + } + } + catch (IOException) + { + // do nothing, the socket is not connected + } + catch (SocketException) + { + // do nothing, the socket is not connected + } + } + } + finally + { + _sendSemaphore.Release(); + } + } + else + { + await _stream.WriteAsync(buffer.Array, buffer.Offset, buffer.Count, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Turns a spec websocket frame opcode into a WebSocketMessageType + /// + WebSocketOpCode GetOppCode(WebSocketMessageType messageType) + { + if (_isContinuationFrame) + { + return WebSocketOpCode.ContinuationFrame; + } + else + { + switch (messageType) + { + case WebSocketMessageType.Binary: + return WebSocketOpCode.BinaryFrame; + case WebSocketMessageType.Text: + return WebSocketOpCode.TextFrame; + case WebSocketMessageType.Close: + throw new NotSupportedException("Cannot use Send function to send a close frame. Use Close function."); + default: + throw new NotSupportedException($"MessageType {messageType} not supported"); + } + } + } + + /// + /// Automatic WebSocket close in response to some invalid data from the remote websocket host + /// + /// The close status to use + /// A description of why we are closing + /// The exception (for logging) + async Task CloseOutputAutoTimeoutAsync(WebSocketCloseStatus closeStatus, string statusDescription, Exception ex) + { + TimeSpan timeSpan = TimeSpan.FromSeconds(5); + Events.Log.CloseOutputAutoTimeout(_guid, closeStatus, statusDescription, ex.ToString()); + + try + { + // we may not want to send sensitive information to the client / server + if (_includeExceptionInCloseResponse) + { + statusDescription = statusDescription + "\r\n\r\n" + ex.ToString(); + } + + CancellationTokenSource autoCancel = new CancellationTokenSource(timeSpan); + await CloseOutputAsync(closeStatus, statusDescription, autoCancel.Token); + } + catch (OperationCanceledException) + { + // do not throw an exception because that will mask the original exception + Events.Log.CloseOutputAutoTimeoutCancelled(_guid, (int)timeSpan.TotalSeconds, closeStatus, statusDescription, ex.ToString()); + } + catch (Exception closeException) + { + // do not throw an exception because that will mask the original exception + Events.Log.CloseOutputAutoTimeoutError(_guid, closeException.ToString(), closeStatus, statusDescription, ex.ToString()); + } + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketImplementation.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketImplementation.cs.meta new file mode 100644 index 0000000..a573a62 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketImplementation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 087dfa54efe9345b390e0758d42e52cf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketOpCode.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketOpCode.cs new file mode 100644 index 0000000..6ef2ac0 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketOpCode.cs @@ -0,0 +1,12 @@ +namespace Ninja.WebSockets.Internal +{ + internal enum WebSocketOpCode + { + ContinuationFrame = 0, + TextFrame = 1, + BinaryFrame = 2, + ConnectionClose = 8, + Ping = 9, + Pong = 10 + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketOpCode.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketOpCode.cs.meta new file mode 100644 index 0000000..f568d56 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Internal/WebSocketOpCode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f2106e8022034b9180513e27b488b4c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/LICENCE.md b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/LICENCE.md new file mode 100644 index 0000000..6fd6c11 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/LICENCE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright 2018 David Haig + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/LICENCE.md.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/LICENCE.md.meta new file mode 100644 index 0000000..9a7423e --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/LICENCE.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 681505da4aa4b48b8b6251521a495d64 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PingPongManager.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PingPongManager.cs new file mode 100644 index 0000000..762e625 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PingPongManager.cs @@ -0,0 +1,139 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System; +using System.Diagnostics; +using System.Net.WebSockets; +using System.Threading; +using System.Threading.Tasks; +using Ninja.WebSockets.Internal; + +namespace Ninja.WebSockets +{ + /// + /// Ping Pong Manager used to facilitate ping pong WebSocket messages + /// + public class PingPongManager : IPingPongManager + { + readonly WebSocketImplementation _webSocket; + readonly Guid _guid; + readonly TimeSpan _keepAliveInterval; + readonly Task _pingTask; + readonly CancellationToken _cancellationToken; + Stopwatch _stopwatch; + long _pingSentTicks; + + /// + /// Raised when a Pong frame is received + /// + public event EventHandler Pong; + + /// + /// Initialises a new instance of the PingPongManager to facilitate ping pong WebSocket messages. + /// If you are manually creating an instance of this class then it is advisable to set keepAliveInterval to + /// TimeSpan.Zero when you create the WebSocket instance (using a factory) otherwise you may be automatically + /// be sending duplicate Ping messages (see keepAliveInterval below) + /// + /// The web socket used to listen to ping messages and send pong messages + /// The time between automatically sending ping messages. + /// Set this to TimeSpan.Zero if you with to manually control sending ping messages. + /// + /// The token used to cancel a pending ping send AND the automatic sending of ping messages + /// if keepAliveInterval is positive + public PingPongManager(Guid guid, WebSocket webSocket, TimeSpan keepAliveInterval, CancellationToken cancellationToken) + { + WebSocketImplementation webSocketImpl = webSocket as WebSocketImplementation; + _webSocket = webSocketImpl; + if (_webSocket == null) + throw new InvalidCastException("Cannot cast WebSocket to an instance of WebSocketImplementation. Please use the web socket factories to create a web socket"); + _guid = guid; + _keepAliveInterval = keepAliveInterval; + _cancellationToken = cancellationToken; + webSocketImpl.Pong += WebSocketImpl_Pong; + _stopwatch = Stopwatch.StartNew(); + + if (keepAliveInterval != TimeSpan.Zero) + { + Task.Run(PingForever, cancellationToken); + } + } + + /// + /// Sends a ping frame + /// + /// The payload (must be 125 bytes of less) + /// The cancellation token + public async Task SendPing(ArraySegment payload, CancellationToken cancellation) + { + await _webSocket.SendPingAsync(payload, cancellation); + } + + protected virtual void OnPong(PongEventArgs e) + { + Pong?.Invoke(this, e); + } + + async Task PingForever() + { + Events.Log.PingPongManagerStarted(_guid, (int)_keepAliveInterval.TotalSeconds); + + try + { + while (!_cancellationToken.IsCancellationRequested) + { + await Task.Delay(_keepAliveInterval, _cancellationToken); + + if (_webSocket.State != WebSocketState.Open) + { + break; + } + + if (_pingSentTicks != 0) + { + Events.Log.KeepAliveIntervalExpired(_guid, (int)_keepAliveInterval.TotalSeconds); + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, $"No Pong message received in response to a Ping after KeepAliveInterval {_keepAliveInterval}", _cancellationToken); + break; + } + + if (!_cancellationToken.IsCancellationRequested) + { + _pingSentTicks = _stopwatch.Elapsed.Ticks; + ArraySegment buffer = new ArraySegment(BitConverter.GetBytes(_pingSentTicks)); + await SendPing(buffer, _cancellationToken); + } + } + } + catch (OperationCanceledException) + { + // normal, do nothing + } + + Events.Log.PingPongManagerEnded(_guid); + } + + void WebSocketImpl_Pong(object sender, PongEventArgs e) + { + _pingSentTicks = 0; + OnPong(e); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PingPongManager.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PingPongManager.cs.meta new file mode 100644 index 0000000..80bb880 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PingPongManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e69d99db8e5024dda9afb8bb5d494260 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PongEventArgs.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PongEventArgs.cs new file mode 100644 index 0000000..027d06b --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PongEventArgs.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Ninja.WebSockets +{ + /// + /// Pong EventArgs + /// + public class PongEventArgs : EventArgs + { + /// + /// The data extracted from a Pong WebSocket frame + /// + public ArraySegment Payload { get; private set; } + + /// + /// Initialises a new instance of the PongEventArgs class + /// + /// The pong payload must be 125 bytes or less (can be zero bytes) + public PongEventArgs(ArraySegment payload) + { + Payload = payload; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PongEventArgs.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PongEventArgs.cs.meta new file mode 100644 index 0000000..6b75b16 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/PongEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57068e417e3ea4201a8de864e9a223a5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties.meta new file mode 100644 index 0000000..afecd37 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c1e6c099dd56f4b30b02f4258c38ff05 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties/PublishProfiles.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties/PublishProfiles.meta new file mode 100644 index 0000000..5fc2e66 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties/PublishProfiles.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 52998228355394f00bf8c88cfad8e362 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties/PublishProfiles/FolderProfile.pubxml b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties/PublishProfiles/FolderProfile.pubxml new file mode 100644 index 0000000..f873eee --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties/PublishProfiles/FolderProfile.pubxml @@ -0,0 +1,13 @@ + + + + + FileSystem + ReleaseSigned + netstandard2.0 + bin\ReleaseSigned\PublishOutput + Any CPU + + \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties/PublishProfiles/FolderProfile.pubxml.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties/PublishProfiles/FolderProfile.pubxml.meta new file mode 100644 index 0000000..a829e20 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/Properties/PublishProfiles/FolderProfile.pubxml.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5e1a5037feecd49deb7892a8b0b755c6 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientFactory.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientFactory.cs new file mode 100644 index 0000000..a6f0546 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientFactory.cs @@ -0,0 +1,288 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Net.WebSockets; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Ninja.WebSockets.Exceptions; +using Ninja.WebSockets.Internal; + +namespace Ninja.WebSockets +{ + /// + /// Web socket client factory used to open web socket client connections + /// + public class WebSocketClientFactory : IWebSocketClientFactory + { + readonly Func _bufferFactory; + readonly IBufferPool _bufferPool; + + /// + /// Initialises a new instance of the WebSocketClientFactory class without caring about internal buffers + /// + public WebSocketClientFactory() + { + _bufferPool = new BufferPool(); + _bufferFactory = _bufferPool.GetBuffer; + } + + /// + /// Initialises a new instance of the WebSocketClientFactory class with control over internal buffer creation + /// + /// Used to get a memory stream. Feel free to implement your own buffer pool. MemoryStreams will be disposed when no longer needed and can be returned to the pool. + public WebSocketClientFactory(Func bufferFactory) + { + _bufferFactory = bufferFactory; + } + + /// + /// Connect with default options + /// + /// The WebSocket uri to connect to (e.g. ws://example.com or wss://example.com for SSL) + /// The optional cancellation token + /// A connected web socket instance + public async Task ConnectAsync(Uri uri, CancellationToken token = default(CancellationToken)) + { + return await ConnectAsync(uri, new WebSocketClientOptions(), token); + } + + /// + /// Connect with options specified + /// + /// The WebSocket uri to connect to (e.g. ws://example.com or wss://example.com for SSL) + /// The WebSocket client options + /// The optional cancellation token + /// A connected web socket instance + public async Task ConnectAsync(Uri uri, WebSocketClientOptions options, CancellationToken token = default(CancellationToken)) + { + Guid guid = Guid.NewGuid(); + string host = uri.Host; + int port = uri.Port; + TcpClient tcpClient = new TcpClient(AddressFamily.InterNetworkV6); + tcpClient.NoDelay = options.NoDelay; + tcpClient.Client.DualMode = true; + string uriScheme = uri.Scheme.ToLower(); + bool useSsl = uriScheme == "wss" || uriScheme == "https"; + if (IPAddress.TryParse(host, out IPAddress ipAddress)) + { + Events.Log.ClientConnectingToIpAddress(guid, ipAddress.ToString(), port); + await tcpClient.ConnectAsync(ipAddress, port); + } + else + { + Events.Log.ClientConnectingToHost(guid, host, port); + await tcpClient.ConnectAsync(host, port); + } + + token.ThrowIfCancellationRequested(); + Stream stream = GetStream(guid, tcpClient, useSsl, host); + return await PerformHandshake(guid, uri, stream, options, token); + } + + /// + /// Connect with a stream that has already been opened and HTTP websocket upgrade request sent + /// This function will check the handshake response from the server and proceed if successful + /// Use this function if you have specific requirements to open a conenction like using special http headers and cookies + /// You will have to build your own HTTP websocket upgrade request + /// You may not even choose to use TCP/IP and this function will allow you to do that + /// + /// The full duplex response stream from the server + /// The secWebSocketKey you used in the handshake request + /// The WebSocket client options + /// The optional cancellation token + /// + public async Task ConnectAsync(Stream responseStream, string secWebSocketKey, WebSocketClientOptions options, CancellationToken token = default(CancellationToken)) + { + Guid guid = Guid.NewGuid(); + return await ConnectAsync(guid, responseStream, secWebSocketKey, options.KeepAliveInterval, options.SecWebSocketExtensions, options.IncludeExceptionInCloseResponse, token); + } + + async Task ConnectAsync(Guid guid, Stream responseStream, string secWebSocketKey, TimeSpan keepAliveInterval, string secWebSocketExtensions, bool includeExceptionInCloseResponse, CancellationToken token) + { + Events.Log.ReadingHttpResponse(guid); + string response = string.Empty; + + try + { + response = await HttpHelper.ReadHttpHeaderAsync(responseStream, token); + } + catch (Exception ex) + { + Events.Log.ReadHttpResponseError(guid, ex.ToString()); + throw new WebSocketHandshakeFailedException("Handshake unexpected failure", ex); + } + + ThrowIfInvalidResponseCode(response); + ThrowIfInvalidAcceptString(guid, response, secWebSocketKey); + string subProtocol = GetSubProtocolFromHeader(response); + return new WebSocketImplementation(guid, _bufferFactory, responseStream, keepAliveInterval, secWebSocketExtensions, includeExceptionInCloseResponse, true, subProtocol); + } + + string GetSubProtocolFromHeader(string response) + { + // make sure we escape the accept string which could contain special regex characters + string regexPattern = "Sec-WebSocket-Protocol: (.*)"; + Regex regex = new Regex(regexPattern, RegexOptions.IgnoreCase); + Match match = regex.Match(response); + if (match.Success) + { + return match.Groups[1].Value.Trim(); + } + + return null; + } + + void ThrowIfInvalidAcceptString(Guid guid, string response, string secWebSocketKey) + { + // make sure we escape the accept string which could contain special regex characters + string regexPattern = "Sec-WebSocket-Accept: (.*)"; + Regex regex = new Regex(regexPattern, RegexOptions.IgnoreCase); + string actualAcceptString = regex.Match(response).Groups[1].Value.Trim(); + + // check the accept string + string expectedAcceptString = HttpHelper.ComputeSocketAcceptString(secWebSocketKey); + if (expectedAcceptString != actualAcceptString) + { + string warning = string.Format($"Handshake failed because the accept string from the server '{expectedAcceptString}' was not the expected string '{actualAcceptString}'"); + Events.Log.HandshakeFailure(guid, warning); + throw new WebSocketHandshakeFailedException(warning); + } + else + { + Events.Log.ClientHandshakeSuccess(guid); + } + } + + void ThrowIfInvalidResponseCode(string responseHeader) + { + string responseCode = HttpHelper.ReadHttpResponseCode(responseHeader); + if (!string.Equals(responseCode, "101 Switching Protocols", StringComparison.InvariantCultureIgnoreCase)) + { + string[] lines = responseHeader.Split(new string[] { "\r\n" }, StringSplitOptions.None); + + for (int i = 0; i < lines.Length; i++) + { + // if there is more to the message than just the header + if (string.IsNullOrWhiteSpace(lines[i])) + { + StringBuilder builder = new StringBuilder(); + for (int j = i + 1; j < lines.Length - 1; j++) + { + builder.AppendLine(lines[j]); + } + + string responseDetails = builder.ToString(); + throw new InvalidHttpResponseCodeException(responseCode, responseDetails, responseHeader); + } + } + } + } + + Stream GetStream(Guid guid, TcpClient tcpClient, bool isSecure, string host) + { + Stream stream = tcpClient.GetStream(); + + if (isSecure) + { + SslStream sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); + Events.Log.AttemtingToSecureSslConnection(guid); + + // This will throw an AuthenticationException if the certificate is not valid + sslStream.AuthenticateAsClient(host); + Events.Log.ConnectionSecured(guid); + return sslStream; + } + else + { + Events.Log.ConnectionNotSecure(guid); + return stream; + } + } + + /// + /// Invoked by the RemoteCertificateValidationDelegate + /// If you want to ignore certificate errors (for debugging) then return true + /// + static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + if (sslPolicyErrors == SslPolicyErrors.None) + { + return true; + } + + Events.Log.SslCertificateError(sslPolicyErrors); + + // Do not allow this client to communicate with unauthenticated servers. + return false; + } + + static string GetAdditionalHeaders(Dictionary additionalHeaders) + { + if (additionalHeaders == null || additionalHeaders.Count == 0) + { + return string.Empty; + } + else + { + StringBuilder builder = new StringBuilder(); + foreach (KeyValuePair pair in additionalHeaders) + { + builder.Append($"{pair.Key}: {pair.Value}\r\n"); + } + + return builder.ToString(); + } + } + + async Task PerformHandshake(Guid guid, Uri uri, Stream stream, WebSocketClientOptions options, CancellationToken token) + { + Random rand = new Random(); + byte[] keyAsBytes = new byte[16]; + rand.NextBytes(keyAsBytes); + string secWebSocketKey = Convert.ToBase64String(keyAsBytes); + string additionalHeaders = GetAdditionalHeaders(options.AdditionalHttpHeaders); + string handshakeHttpRequest = $"GET {uri.PathAndQuery} HTTP/1.1\r\n" + + $"Host: {uri.Host}:{uri.Port}\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + $"Sec-WebSocket-Key: {secWebSocketKey}\r\n" + + $"Origin: http://{uri.Host}:{uri.Port}\r\n" + + $"Sec-WebSocket-Protocol: {options.SecWebSocketProtocol}\r\n" + + additionalHeaders + + "Sec-WebSocket-Version: 13\r\n\r\n"; + + byte[] httpRequest = Encoding.UTF8.GetBytes(handshakeHttpRequest); + stream.Write(httpRequest, 0, httpRequest.Length); + Events.Log.HandshakeSent(guid, handshakeHttpRequest); + return await ConnectAsync(stream, secWebSocketKey, options, token); + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientFactory.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientFactory.cs.meta new file mode 100644 index 0000000..a93bf3e --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38af07c5cfa1940f2bd0b981bccea293 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientOptions.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientOptions.cs new file mode 100644 index 0000000..b6318a8 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientOptions.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Ninja.WebSockets +{ + /// + /// Client WebSocket init options + /// + public class WebSocketClientOptions + { + /// + /// How often to send ping requests to the Server + /// This is done to prevent proxy servers from closing your connection + /// The default is TimeSpan.Zero meaning that it is disabled. + /// WebSocket servers usually send ping messages so it is not normally necessary for the client to send them (hence the TimeSpan.Zero default) + /// You can manually control ping pong messages using the PingPongManager class. + /// If you do that it is advisible to set this KeepAliveInterval to zero for the WebSocketClientFactory + /// + public TimeSpan KeepAliveInterval { get; set; } + + /// + /// Set to true to send a message immediately with the least amount of latency (typical usage for chat) + /// This will disable Nagle's algorithm which can cause high tcp latency for small packets sent infrequently + /// However, if you are streaming large packets or sending large numbers of small packets frequently it is advisable to set NoDelay to false + /// This way data will be bundled into larger packets for better throughput + /// + public bool NoDelay { get; set; } + + /// + /// Add any additional http headers to this dictionary + /// + public Dictionary AdditionalHttpHeaders { get; set; } + + /// + /// Include the full exception (with stack trace) in the close response + /// when an exception is encountered and the WebSocket connection is closed + /// The default is false + /// + public bool IncludeExceptionInCloseResponse { get; set; } + + /// + /// WebSocket Extensions as an HTTP header value + /// + public string SecWebSocketExtensions { get; set; } + + /// + /// A comma separated list of sub protocols in preference order (first one being the most preferred) + /// The server will return the first supported sub protocol (or none if none are supported) + /// Can be null + /// + public string SecWebSocketProtocol { get; set; } + + /// + /// Initialises a new instance of the WebSocketClientOptions class + /// + public WebSocketClientOptions() + { + KeepAliveInterval = TimeSpan.Zero; + NoDelay = true; + AdditionalHttpHeaders = new Dictionary(); + IncludeExceptionInCloseResponse = false; + SecWebSocketProtocol = null; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientOptions.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientOptions.cs.meta new file mode 100644 index 0000000..45c8305 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketClientOptions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f2911aa44c1154bf88781555542a9de3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketHttpContext.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketHttpContext.cs new file mode 100644 index 0000000..f1c85dc --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketHttpContext.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using System.IO; + +namespace Ninja.WebSockets +{ + /// + /// The WebSocket HTTP Context used to initiate a WebSocket handshake + /// + public class WebSocketHttpContext + { + /// + /// True if this is a valid WebSocket request + /// + public bool IsWebSocketRequest { get; private set; } + + public IList WebSocketRequestedProtocols { get; private set; } + + /// + /// The raw http header extracted from the stream + /// + public string HttpHeader { get; private set; } + + /// + /// The Path extracted from the http header + /// + public string Path { get; private set; } + + /// + /// The stream AFTER the header has already been read + /// + public Stream Stream { get; private set; } + + /// + /// Initialises a new instance of the WebSocketHttpContext class + /// + /// True if this is a valid WebSocket request + /// The raw http header extracted from the stream + /// The Path extracted from the http header + /// The stream AFTER the header has already been read + public WebSocketHttpContext(bool isWebSocketRequest, IList webSocketRequestedProtocols, string httpHeader, string path, Stream stream) + { + IsWebSocketRequest = isWebSocketRequest; + WebSocketRequestedProtocols = webSocketRequestedProtocols; + HttpHeader = httpHeader; + Path = path; + Stream = stream; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketHttpContext.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketHttpContext.cs.meta new file mode 100644 index 0000000..7e38e8a --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketHttpContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: efbbd1ab9e45e4dd3b88faaca1048c7f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerFactory.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerFactory.cs new file mode 100644 index 0000000..a638ce0 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerFactory.cs @@ -0,0 +1,169 @@ +// --------------------------------------------------------------------- +// Copyright 2018 David Haig +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// --------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.WebSockets; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Ninja.WebSockets.Exceptions; +using Ninja.WebSockets.Internal; + +namespace Ninja.WebSockets +{ + /// + /// Web socket server factory used to open web socket server connections + /// + public class WebSocketServerFactory : IWebSocketServerFactory + { + readonly Func _bufferFactory; + readonly IBufferPool _bufferPool; + + /// + /// Initialises a new instance of the WebSocketServerFactory class without caring about internal buffers + /// + public WebSocketServerFactory() + { + _bufferPool = new BufferPool(); + _bufferFactory = _bufferPool.GetBuffer; + } + + /// + /// Initialises a new instance of the WebSocketClientFactory class with control over internal buffer creation + /// + /// Used to get a memory stream. Feel free to implement your own buffer pool. MemoryStreams will be disposed when no longer needed and can be returned to the pool. + /// + public WebSocketServerFactory(Func bufferFactory) + { + _bufferFactory = bufferFactory; + } + + /// + /// Reads a http header information from a stream and decodes the parts relating to the WebSocket protocot upgrade + /// + /// The network stream + /// The optional cancellation token + /// Http data read from the stream + public async Task ReadHttpHeaderFromStreamAsync(Stream stream, CancellationToken token = default(CancellationToken)) + { + string header = await HttpHelper.ReadHttpHeaderAsync(stream, token); + string path = HttpHelper.GetPathFromHeader(header); + bool isWebSocketRequest = HttpHelper.IsWebSocketUpgradeRequest(header); + IList subProtocols = HttpHelper.GetSubProtocols(header); + return new WebSocketHttpContext(isWebSocketRequest, subProtocols, header, path, stream); + } + + /// + /// Accept web socket with default options + /// Call ReadHttpHeaderFromStreamAsync first to get WebSocketHttpContext + /// + /// The http context used to initiate this web socket request + /// The optional cancellation token + /// A connected web socket + public async Task AcceptWebSocketAsync(WebSocketHttpContext context, CancellationToken token = default(CancellationToken)) + { + return await AcceptWebSocketAsync(context, new WebSocketServerOptions(), token); + } + + /// + /// Accept web socket with options specified + /// Call ReadHttpHeaderFromStreamAsync first to get WebSocketHttpContext + /// + /// The http context used to initiate this web socket request + /// The web socket options + /// The optional cancellation token + /// A connected web socket + public async Task AcceptWebSocketAsync(WebSocketHttpContext context, WebSocketServerOptions options, CancellationToken token = default(CancellationToken)) + { + Guid guid = Guid.NewGuid(); + Events.Log.AcceptWebSocketStarted(guid); + await PerformHandshakeAsync(guid, context.HttpHeader, options.SubProtocol, context.Stream, token); + Events.Log.ServerHandshakeSuccess(guid); + string secWebSocketExtensions = null; + return new WebSocketImplementation(guid, _bufferFactory, context.Stream, options.KeepAliveInterval, secWebSocketExtensions, options.IncludeExceptionInCloseResponse, false, options.SubProtocol); + } + + static void CheckWebSocketVersion(string httpHeader) + { + Regex webSocketVersionRegex = new Regex("Sec-WebSocket-Version: (.*)", RegexOptions.IgnoreCase); + + // check the version. Support version 13 and above + const int WebSocketVersion = 13; + Match match = webSocketVersionRegex.Match(httpHeader); + if (match.Success) + { + int secWebSocketVersion = Convert.ToInt32(match.Groups[1].Value.Trim()); + if (secWebSocketVersion < WebSocketVersion) + { + throw new WebSocketVersionNotSupportedException(string.Format("WebSocket Version {0} not suported. Must be {1} or above", secWebSocketVersion, WebSocketVersion)); + } + } + else + { + throw new WebSocketVersionNotSupportedException("Cannot find \"Sec-WebSocket-Version\" in http header"); + } + } + + static async Task PerformHandshakeAsync(Guid guid, String httpHeader, string subProtocol, Stream stream, CancellationToken token) + { + try + { + Regex webSocketKeyRegex = new Regex("Sec-WebSocket-Key: (.*)", RegexOptions.IgnoreCase); + CheckWebSocketVersion(httpHeader); + + Match match = webSocketKeyRegex.Match(httpHeader); + if (match.Success) + { + string secWebSocketKey = match.Groups[1].Value.Trim(); + string setWebSocketAccept = HttpHelper.ComputeSocketAcceptString(secWebSocketKey); + string response = ("HTTP/1.1 101 Switching Protocols\r\n" + + "Connection: Upgrade\r\n" + + "Upgrade: websocket\r\n" + + (subProtocol != null ? $"Sec-WebSocket-Protocol: {subProtocol}\r\n" : "") + + $"Sec-WebSocket-Accept: {setWebSocketAccept}"); + + Events.Log.SendingHandshakeResponse(guid, response); + await HttpHelper.WriteHttpHeaderAsync(response, stream, token); + } + else + { + throw new SecWebSocketKeyMissingException("Unable to read \"Sec-WebSocket-Key\" from http header"); + } + } + catch (WebSocketVersionNotSupportedException ex) + { + Events.Log.WebSocketVersionNotSupported(guid, ex.ToString()); + string response = "HTTP/1.1 426 Upgrade Required\r\nSec-WebSocket-Version: 13" + ex.Message; + await HttpHelper.WriteHttpHeaderAsync(response, stream, token); + throw; + } + catch (Exception ex) + { + Events.Log.BadRequest(guid, ex.ToString()); + await HttpHelper.WriteHttpHeaderAsync("HTTP/1.1 400 Bad Request", stream, token); + throw; + } + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerFactory.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerFactory.cs.meta new file mode 100644 index 0000000..920e27a --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c5fcfcd10538542edb4842d81798f4dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerOptions.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerOptions.cs new file mode 100644 index 0000000..c347bd5 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerOptions.cs @@ -0,0 +1,45 @@ +using System; + +namespace Ninja.WebSockets +{ + /// + /// Server WebSocket init options + /// + public class WebSocketServerOptions + { + /// + /// How often to send ping requests to the Client + /// The default is 60 seconds + /// This is done to prevent proxy servers from closing your connection + /// A timespan of zero will disable the automatic ping pong mechanism + /// You can manually control ping pong messages using the PingPongManager class. + /// If you do that it is advisible to set this KeepAliveInterval to zero in the WebSocketServerFactory + /// + public TimeSpan KeepAliveInterval { get; set; } + + /// + /// Include the full exception (with stack trace) in the close response + /// when an exception is encountered and the WebSocket connection is closed + /// The default is false + /// + public bool IncludeExceptionInCloseResponse { get; set; } + + /// + /// Specifies the sub protocol to send back to the client in the opening handshake + /// Can be null (the most common use case) + /// The client can specify multiple preferred protocols in the opening handshake header + /// The server should use the first supported one or set this to null if none of the requested sub protocols are supported + /// + public string SubProtocol { get; set; } + + /// + /// Initialises a new instance of the WebSocketServerOptions class + /// + public WebSocketServerOptions() + { + KeepAliveInterval = TimeSpan.FromSeconds(60); + IncludeExceptionInCloseResponse = false; + SubProtocol = null; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerOptions.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerOptions.cs.meta new file mode 100644 index 0000000..adfcf1d --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Ninja.WebSockets/WebSocketServerOptions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f8d9d315d665461a94bc139e46cbfce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Plugins.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Plugins.meta new file mode 100644 index 0000000..6d6de23 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b64fa4674492a4cf1857ecee9f73fcb1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Plugins/WebSocket.jslib b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Plugins/WebSocket.jslib new file mode 100644 index 0000000..ff1e622 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Plugins/WebSocket.jslib @@ -0,0 +1,108 @@ +var LibraryWebSockets = { + $webSocketInstances: [], + + SocketCreate: function(url, id, onopen, ondata, onclose) + { + var str = Pointer_stringify(url); + + var socket = new WebSocket(str, "binary"); + + socket.binaryType = 'arraybuffer'; + + socket.onopen = function(e) { + Runtime.dynCall('vi', onopen, [id]); + } + + socket.onerror = function(e) { + console.log("websocket error " + JSON.stringify(e)); + } + + socket.onmessage = function (e) { + // Todo: handle other data types? + if (e.data instanceof Blob) + { + var reader = new FileReader(); + reader.addEventListener("loadend", function() { + var array = new Uint8Array(reader.result); + }); + reader.readAsArrayBuffer(e.data); + } + else if (e.data instanceof ArrayBuffer) + { + var array = new Uint8Array(e.data); + var ptr = _malloc(array.length); + var dataHeap = new Uint8Array(HEAPU8.buffer, ptr, array.length); + dataHeap.set(array); + Runtime.dynCall('viii', ondata, [id, ptr, array.length]); + _free(ptr); + } + else if(typeof e.data === "string") { + var reader = new FileReader(); + reader.addEventListener("loadend", function() { + var array = new Uint8Array(reader.result); + }); + var blob = new Blob([e.data]); + reader.readAsArrayBuffer(blob); + } + }; + + socket.onclose = function (e) { + Runtime.dynCall('vi', onclose, [id]); + + if (e.code != 1000) + { + if (e.reason != null && e.reason.length > 0) + socket.error = e.reason; + else + { + switch (e.code) + { + case 1001: + socket.error = "Endpoint going away."; + break; + case 1002: + socket.error = "Protocol error."; + break; + case 1003: + socket.error = "Unsupported message."; + break; + case 1005: + socket.error = "No status."; + break; + case 1006: + socket.error = "Abnormal disconnection."; + break; + case 1009: + socket.error = "Data frame too large."; + break; + default: + socket.error = "Error "+e.code; + } + } + } + } + var instance = webSocketInstances.push(socket) - 1; + return instance; + }, + + SocketState: function (socketInstance) + { + var socket = webSocketInstances[socketInstance]; + return socket.readyState; + }, + + SocketSend: function (socketInstance, ptr, length) + { + var socket = webSocketInstances[socketInstance]; + socket.send (HEAPU8.buffer.slice(ptr, ptr+length)); + }, + + SocketClose: function (socketInstance) + { + var socket = webSocketInstances[socketInstance]; + socket.close(); + } +}; + +autoAddDeps(LibraryWebSockets, '$webSocketInstances'); +mergeInto(LibraryManager.library, LibraryWebSockets); \ No newline at end of file diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Plugins/WebSocket.jslib.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Plugins/WebSocket.jslib.meta new file mode 100644 index 0000000..67daa5e --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Plugins/WebSocket.jslib.meta @@ -0,0 +1,34 @@ +fileFormatVersion: 2 +guid: 3fba16b22ae274c729f6e8f91c425355 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Facebook: WebGL + second: + enabled: 1 + settings: {} + - first: + WebGL: WebGL + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Server.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Server.cs new file mode 100644 index 0000000..9afd8c3 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Server.cs @@ -0,0 +1,344 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Security; +using System.Net.Sockets; +using System.Net.WebSockets; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using Ninja.WebSockets; +using UnityEngine; + +namespace Mirror.Websocket +{ + public class Server + { + public event Action Connected; + public event Action> ReceivedData; + public event Action Disconnected; + public event Action ReceivedError; + + const int MaxMessageSize = 256 * 1024; + + // listener + TcpListener listener; + readonly IWebSocketServerFactory webSocketServerFactory = new WebSocketServerFactory(); + + CancellationTokenSource cancellation; + + // clients with + Dictionary clients = new Dictionary(); + + public bool NoDelay = true; + + // connectionId counter + // (right now we only use it from one listener thread, but we might have + // multiple threads later in case of WebSockets etc.) + // -> static so that another server instance doesn't start at 0 again. + static int counter = 0; + + // public next id function in case someone needs to reserve an id + // (e.g. if hostMode should always have 0 connection and external + // connections should start at 1, etc.) + public static int NextConnectionId() + { + int id = Interlocked.Increment(ref counter); + + // it's very unlikely that we reach the uint limit of 2 billion. + // even with 1 new connection per second, this would take 68 years. + // -> but if it happens, then we should throw an exception because + // the caller probably should stop accepting clients. + // -> it's hardly worth using 'bool Next(out id)' for that case + // because it's just so unlikely. + if (id == int.MaxValue) + { + throw new Exception("connection id limit reached: " + id); + } + + return id; + } + + // check if the server is running + public bool Active + { + get { return listener != null; } + } + + public WebSocket GetClient(int connectionId) + { + // paul: null is evil, throw exception if not found + return clients[connectionId]; + } + + public bool _secure = false; + + public SslConfiguration _sslConfig; + + public class SslConfiguration + { + public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate; + public bool ClientCertificateRequired; + public System.Security.Authentication.SslProtocols EnabledSslProtocols; + public bool CheckCertificateRevocation; + } + + public async void Listen(int port) + { + try + { + cancellation = new CancellationTokenSource(); + + listener = TcpListener.Create(port); + listener.Server.NoDelay = this.NoDelay; + listener.Start(); + Debug.Log($"Websocket server started listening on port {port}"); + while (true) + { + TcpClient tcpClient = await listener.AcceptTcpClientAsync(); + ProcessTcpClient(tcpClient, cancellation.Token); + } + } + catch (ObjectDisposedException) + { + // do nothing. This will be thrown if the Listener has been stopped + } + catch (Exception ex) + { + ReceivedError?.Invoke(0, ex); + } + } + + async void ProcessTcpClient(TcpClient tcpClient, CancellationToken token) + { + + try + { + // this worker thread stays alive until either of the following happens: + // Client sends a close conection request OR + // An unhandled exception is thrown OR + // The server is disposed + + // get a secure or insecure stream + Stream stream = tcpClient.GetStream(); + if (_secure) + { + SslStream sslStream = new SslStream(stream, false, CertVerificationCallback); + sslStream.AuthenticateAsServer(_sslConfig.Certificate, _sslConfig.ClientCertificateRequired, _sslConfig.EnabledSslProtocols, _sslConfig.CheckCertificateRevocation); + stream = sslStream; + } + WebSocketHttpContext context = await webSocketServerFactory.ReadHttpHeaderFromStreamAsync(stream, token); + if (context.IsWebSocketRequest) + { + WebSocketServerOptions options = new WebSocketServerOptions() { KeepAliveInterval = TimeSpan.FromSeconds(30), SubProtocol = "binary" }; + + WebSocket webSocket = await webSocketServerFactory.AcceptWebSocketAsync(context, options); + + await ReceiveLoopAsync(webSocket, token); + } + else + { + Debug.Log("Http header contains no web socket upgrade request. Ignoring"); + } + + } + catch(IOException) + { + // do nothing. This will be thrown if the transport is closed + } + catch (ObjectDisposedException) + { + // do nothing. This will be thrown if the Listener has been stopped + } + catch (Exception ex) + { + ReceivedError?.Invoke(0, ex); + } + finally + { + try + { + tcpClient.Client.Close(); + tcpClient.Close(); + } + catch (Exception ex) + { + ReceivedError?.Invoke(0, ex); + } + } + } + + bool CertVerificationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + // Much research has been done on this. When this is initiated from a HTTPS/WSS stream, + // the certificate is null and the SslPolicyErrors is RemoteCertificateNotAvailable. + // Meaning we CAN'T verify this and this is all we can do. + return true; + } + + async Task ReceiveLoopAsync(WebSocket webSocket, CancellationToken token) + { + int connectionId = NextConnectionId(); + clients.Add(connectionId, webSocket); + + byte[] buffer = new byte[MaxMessageSize]; + + try + { + // someone connected, raise event + Connected?.Invoke(connectionId); + + + while (true) + { + WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(buffer), token); + + if (result.MessageType == WebSocketMessageType.Close) + { + Debug.Log($"Client initiated close. Status: {result.CloseStatus} Description: {result.CloseStatusDescription}"); + break; + } + + ArraySegment data = await ReadFrames(connectionId, result, webSocket, buffer, token); + + if (data.Count == 0) + break; + + try + { + // we received some data, raise event + ReceivedData?.Invoke(connectionId, data); + } + catch (Exception exception) + { + ReceivedError?.Invoke(connectionId, exception); + } + } + + } + catch (Exception exception) + { + ReceivedError?.Invoke(connectionId, exception); + } + finally + { + clients.Remove(connectionId); + Disconnected?.Invoke(connectionId); + } + } + + // a message might come splitted in multiple frames + // collect all frames + async Task> ReadFrames(int connectionId, WebSocketReceiveResult result, WebSocket webSocket, byte[] buffer, CancellationToken token) + { + int count = result.Count; + + while (!result.EndOfMessage) + { + if (count >= MaxMessageSize) + { + string closeMessage = string.Format("Maximum message size: {0} bytes.", MaxMessageSize); + await webSocket.CloseAsync(WebSocketCloseStatus.MessageTooBig, closeMessage, CancellationToken.None); + ReceivedError?.Invoke(connectionId, new WebSocketException(WebSocketError.HeaderError)); + return new ArraySegment(); + } + + result = await webSocket.ReceiveAsync(new ArraySegment(buffer, count, MaxMessageSize - count), CancellationToken.None); + count += result.Count; + + } + return new ArraySegment(buffer, 0, count); + } + + public void Stop() + { + // only if started + if (!Active) return; + + Debug.Log("Server: stopping..."); + cancellation.Cancel(); + + // stop listening to connections so that no one can connect while we + // close the client connections + listener.Stop(); + + // clear clients list + clients.Clear(); + listener = null; + } + + // send message to client using socket connection or throws exception + public async void Send(int connectionId, byte[] data) + { + // find the connection + if (clients.TryGetValue(connectionId, out WebSocket client)) + { + try + { + await client.SendAsync(new ArraySegment(data), WebSocketMessageType.Binary, true, cancellation.Token); + } + catch (ObjectDisposedException) { + // connection has been closed, swallow exception + Disconnect(connectionId); + } + catch (Exception exception) + { + if (clients.ContainsKey(connectionId)) + { + // paul: If someone unplugs their internet + // we can potentially get hundreds of errors here all at once + // because all the WriteAsync wake up at once and throw exceptions + + // by hiding inside this if, I ensure that we only report the first error + // all other errors are swallowed. + // this prevents a log storm that freezes the server for several seconds + ReceivedError?.Invoke(connectionId, exception); + } + + Disconnect(connectionId); + } + } + else + { + ReceivedError?.Invoke(connectionId, new SocketException((int)SocketError.NotConnected)); + } + } + + // get connection info in case it's needed (IP etc.) + // (we should never pass the TcpClient to the outside) + public string GetClientAddress(int connectionId) + { + // find the connection + if (clients.TryGetValue(connectionId, out WebSocket client)) + { + return ""; + } + return null; + } + + // disconnect (kick) a client + public bool Disconnect(int connectionId) + { + // find the connection + if (clients.TryGetValue(connectionId, out WebSocket client)) + { + clients.Remove(connectionId); + // just close it. client thread will take care of the rest. + client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + Debug.Log("Server.Disconnect connectionId:" + connectionId); + return true; + } + return false; + } + + public override string ToString() + { + if (Active) + { + return $"Websocket server {listener.LocalEndpoint}"; + } + return ""; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/Server.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Server.cs.meta new file mode 100644 index 0000000..44d8af0 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/Server.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4bf9040513294fa4939bb9f2f0cda4e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/WebsocketTransport.cs b/Assets/Packages/Mirror/Runtime/Transport/Websocket/WebsocketTransport.cs new file mode 100644 index 0000000..6dd1a92 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/WebsocketTransport.cs @@ -0,0 +1,132 @@ +using System; +using UnityEngine; + +namespace Mirror.Websocket +{ + public class WebsocketTransport : Transport + { + + protected Client client = new Client(); + protected Server server = new Server(); + + public int port = 7778; + + public bool Secure; + public string CertificatePath; + public string CertificatePassword; + + [Tooltip("Nagle Algorithm can be disabled by enabling NoDelay")] + public bool NoDelay = true; + + public WebsocketTransport() + { + // dispatch the events from the server + server.Connected += (connectionId) => OnServerConnected.Invoke(connectionId); + server.Disconnected += (connectionId) => OnServerDisconnected.Invoke(connectionId); + server.ReceivedData += (connectionId, data) => OnServerDataReceived.Invoke(connectionId, data); + server.ReceivedError += (connectionId, error) => OnServerError.Invoke(connectionId, error); + + // dispatch events from the client + client.Connected += () => OnClientConnected.Invoke(); + client.Disconnected += () => OnClientDisconnected.Invoke(); + client.ReceivedData += (data) => OnClientDataReceived.Invoke(data); + client.ReceivedError += (error) => OnClientError.Invoke(error); + + // configure + client.NoDelay = NoDelay; + server.NoDelay = NoDelay; + + Debug.Log("Websocket transport initialized!"); + } + + public override bool Available() + { + // WebSockets should be available on all platforms, including WebGL (automatically) using our included JSLIB code + return true; + } + + // client + public override bool ClientConnected() => client.IsConnected; + + public override void ClientConnect(string host) + { + if (Secure) + { + client.Connect(new Uri($"wss://{host}:{port}")); + } + else + { + client.Connect(new Uri($"ws://{host}:{port}")); + } + } + + public override bool ClientSend(int channelId, byte[] data) { client.Send(data); return true; } + + public override void ClientDisconnect() => client.Disconnect(); + + // server + public override bool ServerActive() => server.Active; + + public override void ServerStart() + { + server._secure = Secure; + if (Secure) + { + server._secure = Secure; + server._sslConfig = new Server.SslConfiguration + { + Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2( + System.IO.Path.Combine(Application.dataPath, CertificatePath), + CertificatePassword), + ClientCertificateRequired = false, + CheckCertificateRevocation = false, + EnabledSslProtocols = System.Security.Authentication.SslProtocols.Default + }; + } + server.Listen(port); + } + + public override bool ServerSend(int connectionId, int channelId, byte[] data) + { + server.Send(connectionId, data); + return true; + } + + public override bool ServerDisconnect(int connectionId) + { + return server.Disconnect(connectionId); + } + + public override string ServerGetClientAddress(int connectionId) + { + return server.GetClientAddress(connectionId); + } + public override void ServerStop() => server.Stop(); + + // common + public override void Shutdown() + { + client.Disconnect(); + server.Stop(); + } + + public override int GetMaxPacketSize(int channelId) + { + // Telepathy's limit is Array.Length, which is int + return int.MaxValue; + } + + public override string ToString() + { + if (client.Connecting || client.IsConnected) + { + return client.ToString(); + } + if (server.Active) + { + return server.ToString(); + } + return ""; + } + } +} diff --git a/Assets/Packages/Mirror/Runtime/Transport/Websocket/WebsocketTransport.cs.meta b/Assets/Packages/Mirror/Runtime/Transport/Websocket/WebsocketTransport.cs.meta new file mode 100644 index 0000000..aab9380 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/Transport/Websocket/WebsocketTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f039183eda8945448b822a77e2a9d0e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Packages/Mirror/Runtime/UNetwork.cs b/Assets/Packages/Mirror/Runtime/UNetwork.cs new file mode 100644 index 0000000..a515c41 --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/UNetwork.cs @@ -0,0 +1,107 @@ +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using UnityEngine; + +namespace Mirror +{ + // Handles network messages on client and server + public delegate void NetworkMessageDelegate(NetworkMessage netMsg); + + // Handles requests to spawn objects on the client + public delegate GameObject SpawnDelegate(Vector3 position, Guid assetId); + + // Handles requests to unspawn objects on the client + public delegate void UnSpawnDelegate(GameObject spawned); + + // invoke type for Cmd/Rpc/SyncEvents + public enum MirrorInvokeType + { + Command, + ClientRpc, + SyncEvent + } + + // built-in system network messages + // original HLAPI uses short, so let's keep short to not break packet header etc. + // => use .ToString() to get the field name from the field value + // => we specify the short values so it's easier to look up opcodes when debugging packets + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use Send with no message id instead")] + public enum MsgType : short + { + // internal system messages - cannot be replaced by user code + ObjectDestroy = 1, + Rpc = 2, + Owner = 4, + Command = 5, + SyncEvent = 7, + UpdateVars = 8, + SpawnPrefab = 3, + SpawnSceneObject = 10, + SpawnStarted = 11, + SpawnFinished = 12, + ObjectHide = 13, + LocalClientAuthority = 15, + + // public system messages - can be replaced by user code + Connect = 32, + Disconnect = 33, + Error = 34, + Ready = 35, + NotReady = 36, + AddPlayer = 37, + RemovePlayer = 38, + Scene = 39, + + // time synchronization + Ping = 43, + Pong = 44, + + Highest = 47 + } + + public enum Version + { + Current = 1 + } + + public static class Channels + { + public const int DefaultReliable = 0; + public const int DefaultUnreliable = 1; + } + + // -- helpers for float conversion without allocations -- + [StructLayout(LayoutKind.Explicit)] + internal struct UIntFloat + { + [FieldOffset(0)] + public float floatValue; + + [FieldOffset(0)] + public uint intValue; + } + + [StructLayout(LayoutKind.Explicit)] + internal struct UIntDouble + { + [FieldOffset(0)] + public double doubleValue; + + [FieldOffset(0)] + public ulong longValue; + } + + [StructLayout(LayoutKind.Explicit)] + internal struct UIntDecimal + { + [FieldOffset(0)] + public ulong longValue1; + + [FieldOffset(8)] + public ulong longValue2; + + [FieldOffset(0)] + public decimal decimalValue; + } +} diff --git a/Assets/Packages/Mirror/Runtime/UNetwork.cs.meta b/Assets/Packages/Mirror/Runtime/UNetwork.cs.meta new file mode 100644 index 0000000..0ee79ed --- /dev/null +++ b/Assets/Packages/Mirror/Runtime/UNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b530ce39098b54374a29ad308c8e4554 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scenes/Main.unity b/Assets/Scenes/Player.unity similarity index 100% rename from Assets/Scenes/Main.unity rename to Assets/Scenes/Player.unity diff --git a/Assets/Scenes/Main.unity.meta b/Assets/Scenes/Player.unity.meta similarity index 100% rename from Assets/Scenes/Main.unity.meta rename to Assets/Scenes/Player.unity.meta diff --git a/ProjectSettings/EditorBuildSettings.asset b/ProjectSettings/EditorBuildSettings.asset index 53457f5..a218b90 100644 --- a/ProjectSettings/EditorBuildSettings.asset +++ b/ProjectSettings/EditorBuildSettings.asset @@ -6,6 +6,6 @@ EditorBuildSettings: serializedVersion: 2 m_Scenes: - enabled: 1 - path: Assets/Scenes/Main.unity + path: Assets/Scenes/Player.unity guid: 2cda990e2423bbf4892e6590ba056729 m_configObjects: {} diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index eda4747..28e0230 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -642,7 +642,8 @@ PlayerSettings: webGLLinkerTarget: 1 webGLThreadsSupport: 0 webGLWasmStreaming: 0 - scriptingDefineSymbols: {} + scriptingDefineSymbols: + 7: MIRROR;MIRROR_1726_OR_NEWER;MIRROR_3_0_OR_NEWER;MIRROR_3_12_OR_NEWER platformArchitecture: {} scriptingBackend: {} il2cppCompilerConfiguration: {}