C++RAW #include "UnityPrefix.h" #include "Configuration/UnityConfigure.h" #include "Runtime/Math/Quaternion.h" #include "Runtime/Utilities/Utility.h" #include "Runtime/Network/NetworkManager.h" #include "Runtime/Network/NetworkUtility.h" #include "Runtime/Network/BitStreamPacker.h" #include "Runtime/Network/MasterServerInterface.h" #include "Runtime/Mono/MonoBehaviour.h" #include "Runtime/Scripting/Scripting.h" CSRAW #if ENABLE_NETWORK using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using UnityEngineInternal; namespace UnityEngine { // Option for who will receive an [[RPC]], used by NetworkView.RPC. CONDITIONAL ENABLE_NETWORK ENUM RPCMode // Sends to the server only Server = 0, // Sends to everyone except the sender Others = 1, // Sends to everyone except the sender and adds to the buffer OthersBuffered = 5, // Sends to everyone All = 2, // Sends to everyone and adds to the buffer AllBuffered = 6 END // The various test results the connection tester may return with. CONDITIONAL ENABLE_NETWORK ENUM ConnectionTesterStatus // Some unknown error occurred. Error = -2, // Test result undetermined, still in progress. Undetermined = -1, OBSOLETE warning No longer returned, use newer connection tester enums instead. PrivateIPNoNATPunchthrough = 0, OBSOLETE warning No longer returned, use newer connection tester enums instead. PrivateIPHasNATPunchThrough = 1, // Public IP address detected and game listen port is accessible to the internet. PublicIPIsConnectable = 2, // Public IP address detected but the port is not connectable from the internet. PublicIPPortBlocked = 3, // Public IP address detected but server is not initialized and no port is listening. PublicIPNoServerStarted = 4, // Port-restricted NAT type, can do NAT punchthrough to everyone except symmetric. LimitedNATPunchthroughPortRestricted = 5, // Symmetric NAT type, cannot do NAT punchthrough to other symmetric types nor port restricted type. LimitedNATPunchthroughSymmetric = 6, // Full cone type, NAT punchthrough fully supported. NATpunchthroughFullCone = 7, // Address-restricted cone type, NAT punchthrough fully supported. NATpunchthroughAddressRestrictedCone = 8 END // Possible status messages returned by Network.Connect and in [[MonoBehaviour.OnFailedToConnect|OnFailedToConnect]] CONDITIONAL ENABLE_NETWORK ENUM NetworkConnectionError // No error occurred. NoError = 0, // We presented an RSA public key which does not match what the system we connected to is using. RSAPublicKeyMismatch = 21, // The server is using a password and has refused our connection because we did not set the correct password. InvalidPassword = 23, // Connection attempt failed, possibly because of internal connectivity problems. ConnectionFailed = 15, // The server is at full capacity, failed to connect. TooManyConnectedPlayers = 18, // We are banned from the system we attempted to connect to (likely temporarily). ConnectionBanned = 22, // We are already connected to this particular server (can happen after fast disconnect/reconnect). AlreadyConnectedToServer = 16, // Cannot connect to two servers at once. Close the connection before connecting again. AlreadyConnectedToAnotherServer = -1, // Internal error while attempting to initialize network interface. Socket possibly already in use. CreateSocketOrThreadFailure = -2, // Incorrect parameters given to Connect function. IncorrectParameters = -3, // No host target given in Connect. EmptyConnectTarget = -4, // Client could not connect internally to same network NAT enabled server. InternalDirectConnectFailed = -5, // The NAT target we are trying to connect to is not connected to the facilitator server. NATTargetNotConnected = 69, // Connection lost while attempting to connect to NAT target. NATTargetConnectionLost = 71, // NAT punchthrough attempt has failed. The cause could be a too restrictive NAT implementation on either endpoints. NATPunchthroughFailed = 73 END // The reason a disconnect event occured, like in [[MonoBehaviour.OnDisconnectedFromServer|OnDisconnectedFromServer]]. CONDITIONAL ENABLE_NETWORK ENUM NetworkDisconnection // The connection to the system has been lost, no reliable packets could be delivered. LostConnection = 20, // The connection to the system has been closed. Disconnected = 19 END // Describes status messages from the master server as returned in [[MonoBehaviour.OnMasterServerEvent|OnMasterServerEvent]]. CONDITIONAL ENABLE_NETWORK ENUM MasterServerEvent // Registration failed because an empty game name was given. RegistrationFailedGameName = 0, // Registration failed because an empty game type was given. RegistrationFailedGameType = 1, // Registration failed because no server is running. RegistrationFailedNoServer = 2, // Registration to master server succeeded, received confirmation. RegistrationSucceeded = 3, // Received a host list from the master server. HostListReceived = 4 END // Different types of synchronization for the [[NetworkView]] component. CONDITIONAL ENABLE_NETWORK ENUM NetworkStateSynchronization // No state data will be synchronized Off = 0, // All packets are sent reliable and ordered. ReliableDeltaCompressed = 1, // Brute force unreliable state sending Unreliable = 2 END // Describes the status of the network interface peer type as returned by Network.peerType. CONDITIONAL ENABLE_NETWORK ENUM NetworkPeerType // No client connection running. Server not initialized. Disconnected = 0, // Running as server. Server = 1, // Running as client. Client = 2, // Attempting to connect to a server. Connecting = 3 END // Describes different levels of log information the network layer supports. CONDITIONAL ENABLE_NETWORK ENUM NetworkLogLevel // Only report errors, otherwise silent. Off = 0, // Report informational messages like connectivity events. Informational = 1, // Full debug level logging down to each individual message being reported. Full = 3 END // The NetworkPlayer is a data structure with which you can locate another player over the network. CONDITIONAL ENABLE_NETWORK STRUCT NetworkPlayer CSRAW internal int index; CUSTOM private static string Internal_GetIPAddress(int index) { return scripting_string_new(GetNetworkManager().GetIPAddress(index)); } CUSTOM private static int Internal_GetPort(int index) { return GetNetworkManager().GetPort(index); } CUSTOM private static string Internal_GetExternalIP() { return scripting_string_new(GetNetworkManager().GetExternalIP()); } CUSTOM private static int Internal_GetExternalPort() { return GetNetworkManager().GetExternalPort(); } CUSTOM private static string Internal_GetLocalIP() { return scripting_string_new(GetLocalIP()); } CUSTOM private static int Internal_GetLocalPort() { return GetNetworkManager().GetPort(); } CUSTOM private static int Internal_GetPlayerIndex () { return GetNetworkManager().GetPlayerID(); } CUSTOM private static string Internal_GetGUID(int index) { return scripting_string_new(GetNetworkManager().GetGUID(index)); } CUSTOM private static string Internal_GetLocalGUID () { return scripting_string_new(GetNetworkManager().GetGUID()); } // *undocumented* CSRAW public NetworkPlayer (string ip, int port) { Debug.LogError("Not yet implemented"); index = 0; } // Returns true if two NetworkPlayers are the same player. CSRAW public static bool operator == (NetworkPlayer lhs, NetworkPlayer rhs) { return lhs.index == rhs.index; } // Returns true if two NetworkPlayers are not the same player. CSRAW public static bool operator != (NetworkPlayer lhs, NetworkPlayer rhs) { return lhs.index != rhs.index; } // *undocumented* Used to allow NetworkPlayer to be used as keys in hash tables. Also triggers warning for == and != operators if not present CSRAW public override int GetHashCode() { return index.GetHashCode(); } // *undocumented* Required for being able to use NetworkPlayer as keys in hash tables CSRAW public override bool Equals(object other) { if(!(other is NetworkPlayer)) return false; NetworkPlayer rhs=(NetworkPlayer)other; return rhs.index == index; } // The IP address of this player. CSRAW public string ipAddress { get { if (index == Internal_GetPlayerIndex()) return Internal_GetLocalIP(); else return Internal_GetIPAddress(index); } } // The port of this player. CSRAW public int port { get { if (index == Internal_GetPlayerIndex()) return Internal_GetLocalPort(); else return Internal_GetPort(index); } } // The GUID for this player, used when connecting with NAT punchthrough. CSRAW public string guid { get { if (index == Internal_GetPlayerIndex()) return Internal_GetLocalGUID(); else return Internal_GetGUID(index); } } // Returns the index number for this network player. CSRAW override public string ToString() { return index.ToString(); } // Returns the external IP address of the network interface. CSRAW public string externalIP { get { return Internal_GetExternalIP(); } } // Returns the external port of the network interface. CSRAW public int externalPort { get { return Internal_GetExternalPort(); } } CSRAW static internal NetworkPlayer unassigned { get { NetworkPlayer val; val.index = -1; return val; } } END // The NetworkViewID is a unique identifier for a network view instance in a multiplayer game. CONDITIONAL ENABLE_NETWORK STRUCT NetworkViewID CSRAW int a; CSRAW int b; CSRAW int c; // Represents an invalid network view ID. CUSTOM_PROP static NetworkViewID unassigned { return NetworkViewID::GetUnassignedViewID(); } CUSTOM static internal bool Internal_IsMine(NetworkViewID value) { return GetNetworkManager().WasViewIdAllocatedByMe(value); } CUSTOM static internal void Internal_GetOwner(NetworkViewID value, out NetworkPlayer player) { *player = GetNetworkManager().GetNetworkViewIDOwner(value); } CUSTOM static internal string Internal_GetString(NetworkViewID value) { return scripting_string_new(value.ToString()); } CUSTOM static internal bool Internal_Compare(NetworkViewID lhs, NetworkViewID rhs) { return rhs == lhs; } // Returns true if two NetworkViewIDs are identical CSRAW public static bool operator == (NetworkViewID lhs, NetworkViewID rhs) { return Internal_Compare(lhs, rhs); } // Returns true if two NetworkViewIDs are not identical CSRAW public static bool operator != (NetworkViewID lhs, NetworkViewID rhs) { return !Internal_Compare(lhs, rhs); } // *undocumented* Used to allow NetworkViewIDs to be used as keys in hash tables. Also triggers warning for == and != operators if not present CSRAW public override int GetHashCode() { return a ^ b ^ c; } // *undocumented* Required for being able to use NetworkViewIDs as keys in hash tables CSRAW public override bool Equals(object other) { if(!(other is NetworkViewID)) return false; NetworkViewID rhs=(NetworkViewID)other; return Internal_Compare(this, rhs); } // True if instantiated by me CSRAW public bool isMine { get { return Internal_IsMine(this); } } // The [[NetworkPlayer]] who owns the [[NetworkView]]. Could be the server. CSRAW public NetworkPlayer owner { get { NetworkPlayer p; Internal_GetOwner(this, out p); return p;} } // Returns a formatted string with details on this NetworkViewID. CSRAW override public string ToString() { return Internal_GetString(this); } END // Ping any given IP address (given in dot notation). CONDITIONAL ENABLE_NETWORK CLASS Ping // We are matching the Ping class here so we can directly access it. CSRAW private IntPtr pingWrapper; // this is needed only for batched android build due to bug in txt parser // screwing up iphone_input.txt to have cpp line emited in wrong place C++RAW #undef GET C++RAW #define GET ExtractMonoObjectData (self) // Perform a ping to the supplied target IP address. CUSTOM Ping(string address) { GET = new Ping(address); GetNetworkManager().PingWrapper(GET); } //*undocumented* THREAD_SAFE CUSTOM void DestroyPing() { if (GET) { GET->Release(); GET = 0; } } CSRAW ~Ping() { DestroyPing(); } // Has the ping function completed? CUSTOM_PROP public bool isDone { if (GET) return (short)GET->GetIsDone(); else return false; } // This property contains the ping time result after isDone returns true. CUSTOM_PROP public int time { return GET->GetTime(); } // The IP target of the ping. CUSTOM_PROP public string ip { return scripting_string_new(GET->GetIP()); } C++RAW #undef GET END // The network view is the binding material of multiplayer games. CONDITIONAL ENABLE_NETWORK CLASS NetworkView : Behaviour CUSTOM private static void Internal_RPC (NetworkView view, string name, RPCMode mode, object[] args) { view->RPCCall(name, mode, args); } CUSTOM private static void Internal_RPC_Target (NetworkView view, string name, NetworkPlayer target, object[] args) { view->RPCCallSpecificTarget(name, target, args); } // Call a [[RPC]] function on all connected peers. CSRAW public void RPC (string name, RPCMode mode, params object[] args) { Internal_RPC(this, name, mode, args); } // Call a RPC function on a specific player CSRAW public void RPC (string name, NetworkPlayer target, params object[] args) { Internal_RPC_Target(this, name, target, args); } // The component the network view is observing. AUTO_PTR_PROP Component observed GetObserved SetObserved // The type of [[NetworkStateSynchronization]] set for this network view. CUSTOM_PROP NetworkStateSynchronization stateSynchronization { return self->GetStateSynchronization(); } { self->SetStateSynchronization(value); } CUSTOM private void Internal_GetViewID (out NetworkViewID viewID) { *viewID = self->GetViewID(); } CUSTOM private void Internal_SetViewID (NetworkViewID viewID) { self->SetViewID(viewID); } // The ViewID of this network view. CSRAW public NetworkViewID viewID { get { NetworkViewID val; Internal_GetViewID(out val); return val; } set { Internal_SetViewID(value); } } // The network group number of this network view. AUTO_PROP int group GetGroup SetGroup // Is the network view controlled by this object? CSRAW public bool isMine { get { return viewID.isMine; } } // The [[NetworkPlayer]] who owns this network view. CSRAW public NetworkPlayer owner { get { return viewID.owner; } } // Set the scope of the network view in relation to a specific network player. CUSTOM bool SetScope(NetworkPlayer player, bool relevancy) { return self->SetPlayerScope(player, relevancy); } // Find a network view based on a [[NetworkViewID]]. CUSTOM static NetworkView Find (NetworkViewID viewID) { return Scripting::ScriptingWrapperFor(GetNetworkManager().ViewIDToNetworkView (viewID)); } END // The network class is at the heart of the network implementation and provides the core functions. CONDITIONAL ENABLE_NETWORK CLASS Network // Initialize the server. CUSTOM static NetworkConnectionError InitializeServer (int connections, int listenPort, bool useNat) { return GetNetworkManager().InitializeServer(connections, listenPort, useNat); } CUSTOM private static NetworkConnectionError Internal_InitializeServerDeprecated (int connections, int listenPort) { return GetNetworkManager().InitializeServer(connections, listenPort, false); } OBSOLETE warning Use the IntializeServer(connections, listenPort, useNat) function instead CSRAW public static NetworkConnectionError InitializeServer (int connections, int listenPort) { return Internal_InitializeServerDeprecated(connections, listenPort); } // Set the password for the server (for incoming connections). CUSTOM_PROP static string incomingPassword { return scripting_string_new(GetNetworkManager().GetIncomingPassword());} { GetNetworkManager().SetIncomingPassword(value);} // Set the log level for network messages (default is Off). CUSTOM_PROP static NetworkLogLevel logLevel { return GetNetworkManager().GetDebugLevel(); } { GetNetworkManager().SetDebugLevel(value); } // Initializes security layer. CUSTOM static void InitializeSecurity() { GetNetworkManager().InitializeSecurity(); } CUSTOM private static NetworkConnectionError Internal_ConnectToSingleIP (string IP, int remotePort, int localPort, string password = "") { return GetNetworkManager().Connect(IP, remotePort, localPort, password); } CUSTOM private static NetworkConnectionError Internal_ConnectToGuid (string guid, string password) { RakNetGUID remoteGuid; remoteGuid.FromString(guid.AsUTF8().c_str()); return GetNetworkManager().Connect(remoteGuid, 0, password); } CUSTOM private static NetworkConnectionError Internal_ConnectToIPs (string[] IP, int remotePort, int localPort, string password = "") { std::vector ipvector; for (int i=0; i < mono_array_length_safe(IP); i++) { ipvector.push_back(scripting_cpp_string_for(GetMonoArrayElement (IP, i))); } return GetNetworkManager().Connect(ipvector, remotePort, localPort, password); } // Connect to the specified host (ip or domain name) and server port. CSRAW public static NetworkConnectionError Connect (string IP, int remotePort, string password = "") { return Internal_ConnectToSingleIP(IP, remotePort, 0, password); } // This function is exactly like Network.Connect but can accept an array of IP addresses. CSRAW public static NetworkConnectionError Connect (string[] IPs, int remotePort, string password = ""){ return Internal_ConnectToIPs(IPs, remotePort, 0, password); } // Connect to a server GUID. NAT punchthrough can only be performed this way. CSRAW public static NetworkConnectionError Connect (string GUID, string password = "") { return Internal_ConnectToGuid(GUID, password); } // Connect to the host represented by a [[HostData]] structure returned by the Master Server. CSRAW public static NetworkConnectionError Connect (HostData hostData, string password = "") { if(hostData == null) throw new NullReferenceException(); if (hostData.guid.Length > 0 && hostData.useNat) return Connect(hostData.guid, password); else return Connect(hostData.ip, hostData.port, password); } // Close all open connections and shuts down the network interface. CUSTOM static void Disconnect(int timeout = 200) { GetNetworkManager().Disconnect(timeout); } // Close the connection to another system. CUSTOM static void CloseConnection (NetworkPlayer target, bool sendDisconnectionNotification) { GetNetworkManager().CloseConnection(target, sendDisconnectionNotification); } // All connected players. CUSTOM_PROP static NetworkPlayer[] connections { MonoArray* array = mono_array_new (mono_domain_get (), MONO_COMMON.networkPlayer, GetNetworkManager().GetConnectionCount()); GetNetworkManager().GetConnections(&GetMonoArrayElement (array,0)); return array; } CUSTOM private static int Internal_GetPlayer () { return GetNetworkManager().GetPlayerID(); } // Get the local [[NetworkPlayer]] instance CSRAW public static NetworkPlayer player { get { NetworkPlayer np; np.index = Internal_GetPlayer(); return np; } } CUSTOM private static void Internal_AllocateViewID(out NetworkViewID viewID) { *viewID = GetNetworkManager().AllocateViewID(); } // Query for the next available network view ID number and allocate it (reserve). CSRAW public static NetworkViewID AllocateViewID() { NetworkViewID val; Internal_AllocateViewID (out val); return val; } // Network instantiate a prefab. CSRAW [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] CUSTOM public static Object Instantiate (Object prefab, Vector3 position, Quaternion rotation, int group) { return Scripting::ScriptingWrapperFor(GetNetworkManager().Instantiate (*prefab, position, rotation, group)); } // Destroy the object associated with this view ID across the network. CUSTOM static void Destroy (NetworkViewID viewID) { GetNetworkManager().DestroyDelayed(viewID); } // Destroy the object across the network. CSRAW public static void Destroy (GameObject gameObject) { if (gameObject != null) { NetworkView view = gameObject.networkView; if (view != null) Destroy(view.viewID); else Debug.LogError("Couldn't destroy game object because no network view is attached to it.", gameObject); } } // Destroy all the objects based on view IDs belonging to this player. CUSTOM static void DestroyPlayerObjects(NetworkPlayer playerID) { GetNetworkManager().DestroyPlayerObjects(playerID); } CUSTOM private static void Internal_RemoveRPCs(NetworkPlayer playerID, NetworkViewID viewID, uint channelMask) { GetNetworkManager().RemoveRPCs(playerID, viewID, channelMask); } // Remove all [[RPC]] functions which belong to this player ID. CSRAW public static void RemoveRPCs(NetworkPlayer playerID) { Internal_RemoveRPCs(playerID, NetworkViewID.unassigned, 0xFFFFFFFF); } // Remove all [[RPC]] functions which belong to this player ID and were sent based on the given group. CSRAW public static void RemoveRPCs(NetworkPlayer playerID, int group) { Internal_RemoveRPCs(playerID, NetworkViewID.unassigned, (uint)(1 << group)); } // Remove the [[RPC]] function calls accociated with this view ID number. CSRAW public static void RemoveRPCs(NetworkViewID viewID) { Internal_RemoveRPCs(NetworkPlayer.unassigned, viewID, 0xFFFFFFFF); } // Remove all [[RPC]] functions which belong to given group number. CSRAW public static void RemoveRPCsInGroup (int group) { Internal_RemoveRPCs(NetworkPlayer.unassigned, NetworkViewID.unassigned, (uint)(1 << group)); } // Returns true if your peer type is client. CUSTOM_PROP static bool isClient { return GetNetworkManager().IsClient(); } // Returns true if your peer type is server. CUSTOM_PROP static bool isServer { return GetNetworkManager().IsServer(); } // The status of the peer type, i.e. if it is disconnected, connecting, server or client. CUSTOM_PROP static NetworkPeerType peerType { return GetNetworkManager().GetPeerType(); } // Set the level prefix which will then be prefixed to all network ViewID numbers. CUSTOM static void SetLevelPrefix (int prefix) { return GetNetworkManager().SetLevelPrefix(prefix); } // The last ping time to the given /player/ in milliseconds. CUSTOM static int GetLastPing (NetworkPlayer player) { return GetNetworkManager().GetLastPing(player); } // The last average ping time to the given /player/ in milliseconds. CUSTOM static int GetAveragePing (NetworkPlayer player) { return GetNetworkManager().GetAveragePing(player); } // The default send rate of network updates for all Network Views. CUSTOM_PROP static float sendRate { return GetNetworkManager().GetSendRate(); } { GetNetworkManager().SetSendRate(value); } // Enable or disable the processing of network messages. CUSTOM_PROP static bool isMessageQueueRunning { return GetNetworkManager().GetMessageQueueRunning(); } { GetNetworkManager().SetMessageQueueRunning(value); } // Enable or disables the reception of messages in a specific group number from a specific player. CUSTOM static void SetReceivingEnabled (NetworkPlayer player, int group, bool enabled) { GetNetworkManager().SetReceivingGroupEnabled(player, group, enabled); } CUSTOM private static void Internal_SetSendingGlobal(int group, bool enabled) { GetNetworkManager().SetSendingGroupEnabled(group, enabled); } CUSTOM private static void Internal_SetSendingSpecific (NetworkPlayer player, int group, bool enabled) { GetNetworkManager().SetSendingGroupEnabled(player, group, enabled); } // Enables or disables transmission of messages and [[RPC]] calls on a specific network group number. CSRAW public static void SetSendingEnabled (int group, bool enabled) { Internal_SetSendingGlobal(group, enabled); } // Enable or disable transmission of messages and [[RPC]] calls based on target network player as well as the network group. CSRAW public static void SetSendingEnabled (NetworkPlayer player, int group, bool enabled) { Internal_SetSendingSpecific(player, group, enabled); } CUSTOM private static void Internal_GetTime(out double t) { *t = GetNetworkManager().GetTime();} // Get the current network time (seconds). CSRAW public static double time { get { double t; Internal_GetTime(out t); return t; } } // Called on the server whenever a new player has successfully connected. CSNONE void OnPlayerConnected (NetworkPlayer player); // Called on the server whenever a Network.InitializeServer was invoked and has completed. CSNONE void OnServerInitialized (); // Called on the client when you have successfully connected to a server CSNONE void OnConnectedToServer (); // Called on the server whenever a player is disconnected from the server CSNONE void OnPlayerDisconnected (NetworkPlayer player); // Called on client during disconnection from server, but also on the server when the connection has disconnected. CSNONE void OnDisconnectedFromServer (NetworkDisconnection mode); // Called on the client when a connection attempt fails for some reason. CSNONE void OnFailedToConnect (NetworkConnectionError error); // Called on objects which have been network instantiated with Network.Instantiate CSNONE void OnNetworkInstantiate (NetworkMessageInfo info); // Used to customize synchronization of variables in a script watched by a network view. CSNONE void OnSerializeNetworkView (BitStream stream, NetworkMessageInfo info); // Get or set the minimum number of ViewID numbers in the ViewID pool given to clients by the server. CUSTOM_PROP static int minimumAllocatableViewIDs { return GetNetworkManager().GetMinimumAllocatableViewIDs(); } { GetNetworkManager().SetMinimumAllocatableViewIDs(value); } OBSOLETE warning No longer needed. This is now explicitly set in the InitializeServer function call. It is implicitly set when calling Connect depending on if an IP/port combination is used (useNat=false) or a GUID is used(useNat=true). CUSTOM_PROP static bool useNat { return GetNetworkManager().GetUseNat(); } { GetNetworkManager().SetUseNat(value); } // The IP address of the NAT punchthrough facilitator. CUSTOM_PROP static string natFacilitatorIP { return scripting_string_new(GetNetworkManager().GetFacilitatorAddress().ToString());} { GetNetworkManager().GetFacilitatorAddress(false).SetBinaryAddress(value.AsUTF8().c_str());} // The port of the NAT punchthrough facilitator. CUSTOM_PROP static int natFacilitatorPort { return GetNetworkManager().GetFacilitatorAddress().port;} { #ifdef _XBOX // mircea@XBOX: for some reason, the xbox compiler chokes on the "simple" assign SystemAddress& sa = GetNetworkManager().GetFacilitatorAddress(false); sa.port = value; #else GetNetworkManager().GetFacilitatorAddress(false).port = value; #endif } // Test this machines network connection. CUSTOM static ConnectionTesterStatus TestConnection(bool forceTest = false) { return GetNetworkManager().TestConnection(false, forceTest); } // Test the connecction specifically for NAT punchthrough connectivity. CUSTOM static ConnectionTesterStatus TestConnectionNAT(bool forceTest = false) { return GetNetworkManager().TestConnection(true, forceTest); } // The IP address of the connection tester used in Network.TestConnection. CUSTOM_PROP static string connectionTesterIP { return scripting_string_new(GetNetworkManager().GetConnTesterAddress().ToString(false));} { SystemAddress address = GetNetworkManager().GetConnTesterAddress(); address.SetBinaryAddress(value.AsUTF8().c_str()); GetNetworkManager().SetConnTesterAddress(address);} // The port of the connection tester used in Network.TestConnection. CUSTOM_PROP static int connectionTesterPort { return GetNetworkManager().GetConnTesterAddress().port;} { SystemAddress address = GetNetworkManager().GetConnTesterAddress(); address.port = value; GetNetworkManager().SetConnTesterAddress(address);} // Check if this machine has a public IP address. CUSTOM static bool HavePublicAddress() { return CheckForPublicAddress(); } // Set the maximum amount of connections/players allowed. CUSTOM_PROP static int maxConnections {return GetNetworkManager().GetMaxConnections(); } { GetNetworkManager().SetMaxConnections(value); } // The IP address of the proxy server. CUSTOM_PROP static string proxyIP { return scripting_string_new(GetNetworkManager().GetProxyIP());} { GetNetworkManager().SetProxyIP(value);} // The port of the proxy server. CUSTOM_PROP static int proxyPort { return GetNetworkManager().GetProxyPort();} { GetNetworkManager().SetProxyPort(value);} // Indicate if proxy support is needed, in which case traffic is relayed through the proxy server. CUSTOM_PROP static bool useProxy { return GetNetworkManager().GetUseProxy(); } { GetNetworkManager().SetUseProxy(value); } // Set the proxy server password. CUSTOM_PROP static string proxyPassword { return scripting_string_new(GetNetworkManager().GetProxyPassword()); } { GetNetworkManager().SetProxyPassword(value); } END // The BitStream class represents seralized variables, packed into a stream. CONDITIONAL ENABLE_NETWORK CLASS BitStream CSRAW internal IntPtr m_Ptr; C++RAW #define GET ExtractMonoObjectData (self) C++RAW #define CHECK_PTR if (ExtractMonoObjectData (self) == NULL) Scripting::RaiseNullException(""); CUSTOM private void Serializeb (ref int value) { CHECK_PTR bool temp = value; GET->Serialize(temp); value = temp; } CUSTOM private void Serializec (ref char value) { // pre-Unity 2.5 serialized .NET chars as single bytes. Let's keep it backwards compatible for now. // on big endian the lower order bits of the 2 byte .NET Char value contains the actual bits we need to send #if UNITY_BIG_ENDIAN char* hack = reinterpret_cast(&value)+1; #else char* hack = reinterpret_cast(&value); #endif CHECK_PTR GET->Serialize(*hack); } CUSTOM private void Serializes (ref short value) { CHECK_PTR GET->Serialize(value); } CUSTOM private void Serializei (ref int value) { CHECK_PTR GET->Serialize(reinterpret_cast(value)); } CUSTOM private void Serializef (ref float value, float maximumDelta) { CHECK_PTR GET->Serialize(value, maximumDelta); } CUSTOM private void Serializeq (ref Quaternion value, float maximumDelta) { CHECK_PTR GET->Serialize(value, maximumDelta); } CUSTOM private void Serializev (ref Vector3 value, float maximumDelta) { CHECK_PTR GET->Serialize(value, maximumDelta); } CUSTOM private void Serializen (ref NetworkViewID viewID) { CHECK_PTR GET->Serialize(viewID); } ///*listonly* CSRAW public void Serialize(ref bool value) { int cross = value ? 1 : 0; Serializeb( ref cross ); value = cross == 0 ? false : true; } ///*listonly* CSRAW public void Serialize(ref char value) { Serializec( ref value ); } ///*listonly* CSRAW public void Serialize(ref short value) { Serializes( ref value); } ///*listonly* CSRAW public void Serialize(ref int value) { Serializei( ref value); } ///*listonly* CSRAW public void Serialize(ref float value, float maxDelta = 0.00001F) { Serializef( ref value, maxDelta); } ///*listonly* CSRAW public void Serialize(ref Quaternion value, float maxDelta = 0.00001F) { Serializeq( ref value, maxDelta); } ///*listonly* CSRAW public void Serialize(ref Vector3 value, float maxDelta = 0.00001F) { Serializev( ref value, maxDelta); } ///*listonly* CSRAW public void Serialize(ref NetworkPlayer value) { int index = value.index; Serializei( ref index ); value.index = index;} // Serializes different types of variables. CSRAW public void Serialize(ref NetworkViewID viewID) { Serializen(ref viewID); } // Is the BitStream currently being read? (RO) CUSTOM_PROP bool isReading { CHECK_PTR return GET->IsReading(); } // Is the BitStream currently being written? (RO) CUSTOM_PROP bool isWriting { CHECK_PTR return GET->IsWriting(); } CUSTOM private void Serialize (ref string value) { CHECK_PTR std::string cppValue; if (GET->IsWriting()) cppValue = value; GET->Serialize(cppValue); if (GET->IsReading()) value.str = scripting_string_new(cppValue); } C++RAW #undef GET C++RAW #undef CHECK END // Attribute for setting up RPC functions. CONDITIONAL ENABLE_NETWORK CSRAW [AttributeUsage(AttributeTargets.Method, AllowMultiple=true)] CLASS RPC : Attribute END // This is the data structure for holding individual host information. CONDITIONAL ENABLE_NETWORK CSRAW [StructLayout (LayoutKind.Sequential)] CLASS HostData CSRAW private int m_Nat; CSRAW private string m_GameType; CSRAW private string m_GameName; CSRAW private int m_ConnectedPlayers; CSRAW private int m_PlayerLimit; CSRAW private string[] m_IP; CSRAW private int m_Port; CSRAW private int m_PasswordProtected; CSRAW private string m_Comment; CSRAW private string m_GUID; // Does this server require NAT punchthrough? CSRAW public bool useNat { get { return m_Nat != 0; } set { m_Nat = value ? 1 : 0; } } // The type of the game (like "MyUniqueGameType") CSRAW public string gameType { get { return m_GameType; } set { m_GameType = value; } } // The name of the game (like John Doe's Game) CSRAW public string gameName { get { return m_GameName; } set { m_GameName = value; } } // Currently connected players CSRAW public int connectedPlayers { get { return m_ConnectedPlayers; } set { m_ConnectedPlayers = value; } } // Maximum players limit CSRAW public int playerLimit { get { return m_PlayerLimit; } set { m_PlayerLimit = value; } } // Server IP address CSRAW public string[] ip { get { return m_IP; } set { m_IP = value; } } // Server port CSRAW public int port { get { return m_Port; } set { m_Port = value; } } // Does the server require a password? CSRAW public bool passwordProtected { get { return m_PasswordProtected != 0; } set { m_PasswordProtected = value ? 1 : 0; } } // A miscellaneous comment (can hold data) CSRAW public string comment { get { return m_Comment; } set { m_Comment = value; } } // The GUID of the host, needed when connecting with NAT punchthrough. CSRAW public string guid { get { return m_GUID; } set { m_GUID = value; } } END C++RAW struct HostDataCpp { int useNat; MonoString* gameType; MonoString* gameName; int connectedPlayers; int playerLimit; MonoArray* IP; int port; int passwordProtected; MonoString* comment; MonoString* guid; }; // The Master Server is used to make matchmaking between servers and clients easy. CONDITIONAL ENABLE_NETWORK CLASS MasterServer // Called on clients or servers when there is a problem connecting to the master server. CSNONE void OnFailedToConnectToMasterServer (NetworkConnectionError error); // Called on clients or servers when reporting events from the MasterServer. CSNONE void OnMasterServerEvent (MasterServerEvent msEvent); // The IP address of the master server. CUSTOM_PROP static string ipAddress { return scripting_string_new(GetMasterServerInterface().GetIPAddress());} { GetMasterServerInterface().SetIPAddress(value);} // The connection port of the master server. CUSTOM_PROP static int port { return GetMasterServerInterface().GetPort();} { GetMasterServerInterface().SetPort(value);} // Request a host list from the master server. CUSTOM static void RequestHostList(string gameTypeName) { GetMasterServerInterface().QueryHostList(gameTypeName); } // Check for the latest host list received by using MasterServer.RequestHostList. CUSTOM static HostData[] PollHostList() { const std::vector& data = GetMasterServerInterface().PollHostList(); MonoClass* hostType = GetMonoManager ().GetCommonClasses ().hostData; //if (data == NULL) return NULL; //count = 0; MonoArray* array = mono_array_new (mono_domain_get (), hostType, data.size()); for (int i = 0; i < data.size(); i++) { MonoObject* element = mono_object_new(mono_domain_get(), hostType); GetMonoArrayElement (array, i) = element; HostDataCpp& dst = ExtractMonoObjectData (element); HostData src = data[i]; dst.useNat = src.useNat; dst.gameType = scripting_string_new(src.gameType); dst.gameName = scripting_string_new(src.gameName); dst.connectedPlayers = src.connectedPlayers; dst.playerLimit = src.playerLimit; MonoArray* ips = mono_array_new (mono_domain_get (), mono_get_string_class(), src.IP.size()); for (int i = 0; i < src.IP.size(); i++) { GetMonoArrayElement (ips, i) = scripting_string_new(src.IP[i]); } dst.IP = ips; dst.port = src.port; dst.passwordProtected = src.passwordProtected; dst.comment = scripting_string_new(src.comment); dst.guid = scripting_string_new(src.guid); } return array; } // Register this server on the master server. CUSTOM static void RegisterHost(string gameTypeName, string gameName, string comment = "") { GetMasterServerInterface().RegisterHost(gameTypeName, gameName, comment); } // Unregister this server from the master server. CUSTOM static void UnregisterHost() { GetMasterServerInterface().UnregisterHost(); } // Clear the host list which was received by MasterServer.PollHostList. CUSTOM static void ClearHostList() { GetMasterServerInterface().ClearHostList(); } // Set the minimum update rate for master server host information update. CUSTOM_PROP static int updateRate { return GetMasterServerInterface().GetUpdateRate();} { GetMasterServerInterface().SetUpdateRate(value);} // Report this machine as a dedicated server. CUSTOM_PROP static bool dedicatedServer { return GetMasterServerInterface().GetDedicatedServer(); } { GetMasterServerInterface().SetDedicatedServer(value); } END // This data structure contains information on a message just received from the network. CONDITIONAL ENABLE_NETWORK STRUCT NetworkMessageInfo CSRAW double m_TimeStamp; NetworkPlayer m_Sender; NetworkViewID m_ViewID; // The time stamp when the Message was sent in seconds. CSRAW public double timestamp { get { return m_TimeStamp; } } // The player who sent this network message (owner) CSRAW public NetworkPlayer sender { get { return m_Sender; } } // The [[NetworkView]] who sent this message CSRAW public NetworkView networkView { get { if (m_ViewID == NetworkViewID.unassigned) { Debug.LogError("No NetworkView is assigned to this NetworkMessageInfo object. Note that this is expected in OnNetworkInstantiate()."); return NullNetworkView(); } return NetworkView.Find(m_ViewID); } } CUSTOM internal NetworkView NullNetworkView() { return Scripting::ScriptingObjectNULL (ScriptingClassFor (NetworkView)); } END CSRAW } #endif