/Core/Dependencies/Engine/MultiplayerOnline/RakNet/NetManager.cpp
C++ | 1059 lines | 562 code | 184 blank | 313 comment | 118 complexity | 1f1f481e29db113099270cdfffaace05 MD5 | raw file
- #include "StdAfx.h"
- #include "NetManager.h"
- using namespace std;
- static const int DEFAULT_SERVER_MILLISECONDS_BETWEEN_UPDATES=250;
- namespace GamePipeGame
- {
- NetTopology topology;
- extern ofstream outputLog;
- /// ~NetManager - Constructor
- NetManager::NetManager(CustomPacketHandler pCustomPacketHandler /*= 0*/) :
- managerStatus(INACTIVE), subsystem(RAKNET), topology(CLIENT),
- maxConnections(1), sleepInterval(100),
- localPort(0), remoteHost("127.0.0.1"), remotePort(60000), password(""),
- isNetworkIDAuthority(false),
- networkInterface(NULL),
- rakPacket(NULL),
- globalLog(NULL),
- m_pCustomPacketHandler(pCustomPacketHandler)
- {
- //networkInterface = RakNetworkFactory::GetRakPeerInterface();
- //raknet 4.0b8
- networkInterface = RakNet::RakPeerInterface::GetInstance();
- }
- /// ~NetManager - Destructor
- NetManager::~NetManager()
- {
- networkInterface->Shutdown(0, 0, HIGH_PRIORITY);
- managerStatus = DESTROYING;
- }
- /// GetStatus - Gets the current NetManager status
- NetManagerStatus NetManager::GetStatus() { return managerStatus; }
- /// GetTopology - Gets the current network topology value (CLIENT, SERVER, PEER)
- NetTopology NetManager::GetTopology() { return topology; }
- /// SetTopology - Sets a new network topology value (CLIENT, SERVER, PEER)
- int
- NetManager::SetTopology(NetTopology newTopology)
- {
- topology = newTopology;
- return NETMANAGER_SUCCESS;
- }
- /// CreateNetworkIDManager - Attaches a NetworkIDManager object to the RakPeerInterface
- ///
- /// Parameters: newAuthority - a flag indicating whether this NetworkIDManager is the ID Authority (usually, a server)
- int
- NetManager::CreateNetworkIDManager(bool newAuthority)
- {
- isNetworkIDAuthority = newAuthority;
-
- if(subsystem == RAKNET)
- {
- //networkInterface->SetNetworkIDManager(&networkIDManager);
- //raknet 4.0b8
- replicaManager.SetNetworkIDManager(&networkIDManager);
- replicaManager.SetAutoSerializeInterval(DEFAULT_SERVER_MILLISECONDS_BETWEEN_UPDATES);
- //networkIDManager.SetIsNetworkIDAuthority(newAuthority);
- }
- return NETMANAGER_SUCCESS;
- }
- /// SetLocalSocketPort - Sets a new port number for local binding
- int
- NetManager::SetLocalSocketPort(unsigned short newLocalPort)
- {
- localPort = newLocalPort;
- return NETMANAGER_SUCCESS;
- }
- /// SetMaxConnections - Sets the maximum number of connections for this RakPeerInterface
- int
- NetManager::SetMaxConnections(int newMaxConnections)
- {
- maxConnections = newMaxConnections;
- return NETMANAGER_SUCCESS;
- }
- /// SetSleepInterval - Sets a new sleep interval for polling
- int
- NetManager::SetSleepInterval(int newSleepIntervalMS)
- {
- sleepInterval = newSleepIntervalMS;
- return NETMANAGER_SUCCESS;
- }
- /// SetRemoteHost - Sets a new remote port host name
- int
- NetManager::SetRemoteHost(const char *newRemoteHost)
- {
- remoteHost.clear();
- remoteHost.assign(newRemoteHost);
- return NETMANAGER_SUCCESS;
- }
- /// SetRemotePort - Sets a new remote port number
- int
- NetManager::SetRemotePort(unsigned short newRemotePort)
- {
- remotePort = newRemotePort;
- return NETMANAGER_SUCCESS;
- }
- /// SetPasswordOptions - Sets a new password string
- int
- NetManager::SetPasswordOptions(const char *newPassword, int length)
- {
- password.clear();
- password.assign(newPassword, length);
- return NETMANAGER_SUCCESS;
- }
- /// EnableRakNetPlugin - Attaches a specific plug-in to the RakPeerInterface
- ///
- /// Parameters: pluginName - a string containing the name of the plug-in to attach
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the subsystem value is not set to RAKNET
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::EnableRakNetPlugin(const char *pluginName)
- {
- if(subsystem != RAKNET) return NETMANAGER_FAILURE;
- if(!strcmp(pluginName, "ReplicaManager3"))
- networkInterface->AttachPlugin(&replicaManager);
- return NETMANAGER_SUCCESS;
- }
- /// Initialize - Sets the initial properties of the RakPeerInterface.
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the call to RakPeerInterface->Startup returns a failure.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::Initialize()
- {
- //bool startupResult = false;
- //raknet 4.0b8
- RakNet::StartupResult startupResult;
- managerStatus = INITIALIZING;
- if(subsystem == RAKNET)
- {
- connectionSD.port = localPort;
- //startupResult = networkInterface->Startup(maxConnections, sleepInterval, &connectionSD, 1);
- //raknet 4.0b8
- startupResult = networkInterface->Startup(maxConnections, &connectionSD, 1);
- //if(startupResult) networkInterface->SetMaximumIncomingConnections(maxConnections);
- //raknet 4.0b8
- if(startupResult==RakNet::RAKNET_STARTED)networkInterface->SetMaximumIncomingConnections(maxConnections);
- }
- //return ((startupResult)? NETMANAGER_SUCCESS : NETMANAGER_FAILURE);
- //raknet 4.0b8
- if(startupResult==RakNet::RAKNET_STARTED)
- {
- return NETMANAGER_SUCCESS;
- }
- else
- {
- return NETMANAGER_FAILURE;
- }
- }
- /// Connect - Connects the network interface to a remote host and port using previously set values.
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if this is a server OR if RakPeerInterface->Connect returns a failure.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::Connect()
- {
- if(topology == SERVER) return NETMANAGER_FAILURE; // should not call Connect() for servers
- //bool connectInitResult = false;
- //raknet 4.0b8
- RakNet::ConnectionAttemptResult connectInitResult;
- if(subsystem == RAKNET)
- {
- connectInitResult = networkInterface->Connect(remoteHost.c_str(), remotePort, password.c_str(), password.length(), 0);
-
- }
- //return ((connectInitResult)? NETMANAGER_SUCCESS : NETMANAGER_FAILURE);
- //raknet 4.0b8
- if(connectInitResult==RakNet::CONNECTION_ATTEMPT_STARTED)
- {
- return NETMANAGER_SUCCESS;
- }
- else
- {
- return NETMANAGER_FAILURE;
- }
- }
- /// Disconnect - Disconnects the network interface from a remote host and port using previously set values.
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if this is a server.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::Disconnect()
- {
- if(topology == SERVER) return NETMANAGER_FAILURE; // should not call Disconnect() for servers
- managerStatus = STOPPING;
- if(subsystem == RAKNET)
- {
- std::vector<Ogre::String> destructionList;
- DestroyMyObjects(destructionList);
- AddLogMessage("Disconnecting from server.");
- //SystemAddress disconnectSystem(remoteHost.c_str(), remotePort);
- //raknet 4.0b8
- RakNet::SystemAddress disconnectSystem(remoteHost.c_str(), remotePort);
- networkInterface->CloseConnection(disconnectSystem, true);
- AddLogMessage("Shutting down the network connection.");
- networkInterface->Shutdown(0);
- //raknet 4.0b8
- RakNet::RakPeerInterface::DestroyInstance(networkInterface);
- managerStatus = INACTIVE;
- }
- return NETMANAGER_SUCCESS;
- }
- /// Shutdown - Calls Disconnect if client, Shutdown if server
- ///
- /// Returns:
- /// NETMANAGER_SUCCESS, if Disconnect() succeeds for a client or after Shutdown is called for a server
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::NetShutdown()
- {
- if(NotStarted()) return NETMANAGER_FAILURE;
- if(subsystem == RAKNET)
- {
- if(topology == CLIENT)
- {
- return NetManager::Disconnect();
- }
- else
- {
- managerStatus = INACTIVE;
- networkInterface->Shutdown(0);
- //raknet 4.0b8
- RakNet::RakPeerInterface::DestroyInstance(networkInterface);
- return NETMANAGER_SUCCESS;
- }
- }
- return NETMANAGER_FAILURE;
- }
- /// NotStarted - Checks to see if the NetManager is in the INACTIVE state
- ///
- /// Returns: True, if managerStatus is INACTIVE. False, otherwise.
- bool NetManager::NotStarted() { return managerStatus == INACTIVE; }
- /// AddObject - Adds a BasicReplica to the replica manager.
- ///
- /// Parameters: replica - a BasicReplica pointer to use for addtion to the replica manager
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the replica pointer is NULL.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- //NetManager::AddObject(BasicReplica *replica)
- //raknet 4.0b8
- NetManager::AddObject(GameObjectReplica *replica)
- {
- if(replica == NULL) return NETMANAGER_FAILURE;
- if(subsystem == RAKNET)
- {
- replicaManager.Reference(replica);
- }
- return NETMANAGER_SUCCESS;
- }
- /// AddObject - Adds a BasicReplica to the replica manager with adding the GUID of client who requested the obect creation.
- ///
- /// Parameters: replica - a BasicReplica pointer to use for addtion to the replica manager
- /// guid - RakNetGUID of client
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the replica pointer is NULL.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- //NetManager::AddObject(BasicReplica *replica, RakNet::RakNetGUID)
- //raknet 4.0b8
- NetManager::AddObject(GameObjectReplica *replica, RakNet::RakNetGUID guid)
- {
- if(replica == NULL) return NETMANAGER_FAILURE;
- if(subsystem == RAKNET)
- {
- replicaManager.Reference(replica);
- listGUID.push_back(guid);
- listNetworkID.push_back(replica->GetNetworkID());
- }
- return NETMANAGER_SUCCESS;
- }
- /// DestroyObjectByPtr - Destroys an object given a pointer
- ///
- /// Parameters: replica - a BasicReplica pointer to use for destruction
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the replica pointer is NULL.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- //NetManager::DestroyObjectByPtr(BasicReplica *replica)
- //raknet 4.0b8
- NetManager::DestroyObjectByPtr(GameObjectReplica *replica)
- {
- if(replica == NULL) return NETMANAGER_FAILURE;
- if(subsystem == RAKNET)
- {
- //
- replica->BroadcastDestruction();
- }
- return NETMANAGER_SUCCESS;
- }
- /// DestroyObjectByName - Destroys an object given a specific name
- ///
- /// Not implemented.
- ///
- /// Parameters: name - a reference to an Ogre string containing the name of the entity to destroy
- int
- NetManager::DestroyObjectByName(Ogre::String name)
- {
- if(subsystem == RAKNET)
- {
- }
- return NETMANAGER_FAILURE;
- }
- /// DestroyObjectByGUID - Destroys an object given a specific GUID
- ///
- /// Not implemented.
- ///
- /// Parameters: guid - a GamePipeNetObjectGUID (typedef'd to some other value) to search for for destruction
- int
- NetManager::DestroyObjectByGUID(GamePipeNetObjectGUID guid)
- {
- if(subsystem == RAKNET)
- {
- }
- return NETMANAGER_FAILURE;
- }
- /// DestroyMyObjects - Destroys all shared objects that were created by the replica manager in this NetManager instance.
- ///
- /// This function destroys only objects that have been allocated a network ID.
- ///
- /// Parameters:
- /// destroyedEntityNames - a vector of Ogre strings containing the names of all successfully destroyed entities
- ///
- /// Returns:
- /// NETMANAGER_SUCCESS
- int
- NetManager::DestroyMyObjects(std::vector<Ogre::String> &destroyedEntityNames)
- {
- if(subsystem == RAKNET)
- {
- destroyedEntityNames.clear();
- DataStructures::List<RakNet::Replica3*> myReplicaList, replicaDestructionList;
- //DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> myReplicaList, replicaDestructionList;
- replicaManager.GetReplicasCreatedByMe(myReplicaList);
- for(unsigned index = 0; index < myReplicaList.Size(); index++)
- {
- //BasicReplica *replica = static_cast<BasicReplica *>(myReplicaList[index]);
- //raknet 4.0b8
- GameObjectReplica *replica = static_cast<GameObjectReplica *>(myReplicaList[index]);
- Ogre::String entityName = replica->GetEntityName();
- // Only delete objects that have already been assigned a network ID, as these objects have been completely
- // set up in the replica manager. Deleting objects with IDs of 65535 (UNASSIGNED) leads to "orphaned" objects.
- //if(replica->GetNetworkID().localSystemAddress != 65535)
- //raknet 4.0b8
- if(replica->GetNetworkID() != 65535)
- {
- destroyedEntityNames.push_back(entityName); // Add to the list of entities to handle later
- replicaDestructionList.Push(replica, _FILE_AND_LINE_); // Add to the local destruction stack
- //cout << "[NetManager/DestroyMyObjects] Queuing replica for destruction, ID = " << replica->GetNetworkID().localSystemAddress << endl;
- //raknet 4.0b8
- cout << "[NetManager/DestroyMyObjects] Queuing replica for destruction, ID = " << replica->GetNetworkID() << endl;
- }
- else
- {
- cout << "[NetManager/DestroyMyObjects] Cannot destroy object (" << entityName << ") yet as it has a network ID of zero" << endl;
- }
- }
- //replicaManager.BroadcastDestructionList(replicaDestructionList, UNASSIGNED_SYSTEM_ADDRESS);
- //raknet 4.0b8
- replicaManager.BroadcastDestructionList(replicaDestructionList, RakNet::UNASSIGNED_SYSTEM_ADDRESS);
- //replicaDestructionList.;
- }
- return NETMANAGER_SUCCESS;
- }
- /// DestroyAllObjects - Destroys all shared objects.
- ///
- /// This function destroys only objects that have been allocated a network ID.
- ///
- /// Parameters:
- /// destroyedEntityNames - a vector of Ogre strings containing the names of all successfully destroyed entities
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the function is called by a NetManager that is not a server.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::DestroyAllObjects(std::vector<Ogre::String> &destroyedEntityNames)
- {
- if(topology != SERVER) return NETMANAGER_FAILURE; // Only the server can attempt to delete all objects in the manager
- if(subsystem == RAKNET)
- {
- destroyedEntityNames.clear();
- DataStructures::List<RakNet::Replica3*> allReplicaList, replicaDestructionList;
- //DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> allReplicaList, replicaDestructionList;
- replicaManager.GetReplicasCreatedByMe(allReplicaList);
- // Remove the objects I created:
- // Remove the objects from the scene (associated entity and scene nodes)
- // Remove the objects from the entity map
- for(unsigned index = 0; index < allReplicaList.Size(); index++)
- {
- //BasicReplica *replica = static_cast<BasicReplica *>(allReplicaList[index]);
- //raknet 4.0b8
- GameObjectReplica *replica = static_cast<GameObjectReplica *>(allReplicaList[index]);
- Ogre::String entityName = replica->GetEntityName();
- //if(replica->GetNetworkID().localSystemAddress != 0)
- //raknet 4.0b8
- if(replica->GetNetworkID() != 0)
- {
- destroyedEntityNames.push_back(entityName);
- replicaDestructionList.Push(replica, _FILE_AND_LINE_);
- }
- else
- {
- cout << "[NetManager/DestroyAllObjects] Cannot destroy object (" << entityName << ") yet as it has a network ID of zero" << endl;
- }
- }
- //replicaManager.BroadcastDestructionList(replicaDestructionList, UNASSIGNED_SYSTEM_ADDRESS);
- //raknet 4.0b8
- replicaManager.BroadcastDestructionList(replicaDestructionList, RakNet::UNASSIGNED_SYSTEM_ADDRESS);
- //replicaDestructionList.ClearPointers();
- }
- return NETMANAGER_SUCCESS;
- }
- /// QueryByObjectName - Returns a pointer to a replica whose object name matches the supplied Ogre String.
- ///
- /// This function returns only the first matching replica in the replica manager. Object names do not have to be unique.
- ///
- /// Parameters: name - a reference to an Ogre string containing the object name to search for
- /// Returns: a BasicReplica pointer matching the object name. NULL if the object name is not found in the replica manager.
- //BasicReplica *
- //raknet 4.0b8
- GameObjectReplica *
- NetManager::QueryByObjectName(Ogre::String &name)
- {
- if(subsystem == RAKNET)
- {
- DataStructures::List<RakNet::Replica3*> fullReplicaList;
- //DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> fullReplicaList;
- replicaManager.GetReferencedReplicaList(fullReplicaList);
- for(unsigned index = 0; index < replicaManager.GetReplicaCount(); index++)
- {
- //BasicReplica *replica = static_cast<BasicReplica *>(replicaManager.GetReplicaAtIndex(index));
- //raknet 4.0b8
- GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaManager.GetReplicaAtIndex(index));
- if(!name.compare(replica->GetObjectName()))
- return replica;
- }
- }
- return NULL;
- }
- /// QueryByEntityName - Returns a pointer to a replica whose entity name matches the supplied Ogre String.
- ///
- /// This function returns only the first matching replica in the replica manager. Entity names should generally be unique.
- ///
- /// Parameters: name - a reference to an Ogre string containing the entity name to search for
- ///
- /// Returns: a BasicReplica pointer matching the entity name. NULL if the entity name is not found in the replica manager.
- //BasicReplica *
- //raknet 4.0b8
- GameObjectReplica *
- NetManager::QueryByEntityName(Ogre::String &name)
- {
- if(subsystem == RAKNET)
- {
- DataStructures::List<RakNet::Replica3*> fullReplicaList;
- // DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> fullReplicaList;
- replicaManager.GetReferencedReplicaList(fullReplicaList);
- for(unsigned index = 0; index < replicaManager.GetReplicaCount(); index++)
- {
- //BasicReplica *replica = static_cast<BasicReplica *>(replicaManager.GetReplicaAtIndex(index));
- //raknet 4.0b8
- GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaManager.GetReplicaAtIndex(index));
- if(!name.compare(replica->GetEntityName()))
- return replica;
- }
- }
- return NULL;
- }
- /// QueryAllObjects - Returns a list of BasicReplica pointers containing all objects in the replica manager.
- ///
- /// Not implemented.
- ///
- /// Parameters: objectList - a reference to a std::vector of BasicReplica pointers
- int
- //NetManager::QueryAllObjects(std::vector<BasicReplica *> &objectList)
- //raknet 4.0b8
- NetManager::QueryAllObjects(std::vector<GameObjectReplica *> &objectList)
- {
- return NETMANAGER_FAILURE;
- }
- //BasicReplica *
- //raknet 4.03
- int NetManager::QueryObjectsByGUID(std::vector<GameObjectReplica *> &objectList,RakNet::RakNetGUID guid)
- {
- if(subsystem == RAKNET)
- {
- DataStructures::List<RakNet::Replica3*> fullReplicaList;
- // DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> fullReplicaList;
- replicaManager.GetReferencedReplicaList(fullReplicaList);
- vector<RakNet::NetworkID> listByGuid;
- for(int listIndex = 0;listIndex<(int)listGUID.size();listIndex++)
- {
- if(listGUID[listIndex]==guid)
- {
- listByGuid.push_back(listNetworkID[listIndex]);
- }
- }
- for(unsigned index = 0; index < replicaManager.GetReplicaCount(); index++)
- {
- GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaManager.GetReplicaAtIndex(index));
- for(int listIndex = 0;listIndex<(int)listByGuid.size();listIndex++)
- {
- if(listByGuid[listIndex]==replica->GetNetworkID())
- {
- //listByGuid.push_back(listNetworkID[listIndex]);
- objectList.push_back(replica);
- break;
- }
- }
- }
- }
- return NETMANAGER_SUCCESS;
- }
- /// SelectNextObject - Iterates through the replicas in the replica manager, returning a reference to the next replica.
- ///
- /// Only servers are allowed to iterate through the entire known replica list, clients and peers can only iterate
- /// through objects they own.
- ///
- /// Parameters:
- /// currentEntityPtr - a pointer to the current object selected
- /// forward - whether to return the next object forward or backward in the list from the replica manager. Default value is true.
- ///
- /// Returns: a BasicReplica pointer to the next object to be selected. NULL is returned if currentEntityPtr is the
- /// last object in the replica list.
- //BasicReplica *
- //raknet 4.0b8
- GameObjectReplica *
- //NetManager::SelectNextObject(BasicReplica *currentEntityPtr, bool forward)
- //raknet 4.0b8
- NetManager::SelectNextObject(GameObjectReplica *currentEntityPtr, bool forward)
- {
- if(subsystem == RAKNET)
- {
- DataStructures::List<RakNet::Replica3*> replicaList;
- //DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> replicaList;
- if(topology == SERVER)
- replicaManager.GetReferencedReplicaList(replicaList); // Only the server can select all objects
- else
- replicaManager.GetReplicasCreatedByMe(replicaList); // Clients and peers can only select objects they won
- // If there's no selectable entities to select, just return null
- if(replicaList.Size() == 0)
- {
- AddLogMessage("No entities to select.");
- return NULL;
- }
- // If nothing was selected before, just return the first object
- if(currentEntityPtr == NULL && replicaList.Size() > 0)
- {
- //BasicReplica *replica = static_cast<BasicReplica *>(replicaList[0]);
- //raknet 4.0b8
- GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaList[0]);
- AddLogMessage("Selected entity: " + replica->GetEntityName());
- return replica;
- }
- // Otherwise, find the current object and then return the next one on the stack.
- // If the current object was the last one on the list, return null (deselect object)
- //DataStructures::DefaultIndexType i = 0;
- for(unsigned i = 0; i < replicaList.Size(); i++)
- {
- //BasicReplica *replica = static_cast<BasicReplica *>(replicaList[i]);
- //raknet 4.0b8
- GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaList[i]);
- if(currentEntityPtr == replica)
- {
- //BasicReplica *replicaToReturn = (i+1 < replicaList.GetSize())? static_cast<BasicReplica *>(replicaList[i+1]) : NULL;
- //
- GameObjectReplica *replicaToReturn = (i+1 < replicaList.Size())? static_cast<GameObjectReplica *>(replicaList[i+1]) : NULL;
- if(replicaToReturn != NULL)
- AddLogMessage("Selected entity: " + replicaToReturn->GetEntityName());
- else
- AddLogMessage("Reset selection.");
- return replicaToReturn;
- }
- }
- }
- return NULL;
- }
- /// ProcessMessages - Processes incoming messages through the RakPeerInterface.
- ///
- /// This function can be edited to handle custom ID types (the first byte of rakPacket->data)
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the NetManager is not started (ie., in INACTIVE state)
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::ProcessMessages()
- {
- if(NotStarted()) return NETMANAGER_FAILURE;
- if(subsystem == RAKNET)
- {
- for (rakPacket = networkInterface->Receive(); rakPacket; networkInterface->DeallocatePacket(rakPacket), rakPacket = networkInterface->Receive())
- {
- switch (rakPacket->data[0])
- {
- case ID_CONNECTION_ATTEMPT_FAILED:
- {
- AddLogMessage("ID_CONNECTION_ATTEMPT_FAILED\n");
- networkInterface->Shutdown(0);
- managerStatus = INACTIVE;
- if(outputLog.is_open()) outputLog << "[NetManager] ID_CONNECTION_ATTEMPT_FAILED" << endl;
- break;
- }
- case ID_NO_FREE_INCOMING_CONNECTIONS:
- {
- AddLogMessage("ID_NO_FREE_INCOMING_CONNECTIONS\n");
- networkInterface->Shutdown(0);
- managerStatus = INACTIVE;
- if(outputLog.is_open()) outputLog << "[NetManager] ID_NO_FREE_INCOMING_CONNECTION" << endl;
- break;
- }
- case ID_CONNECTION_REQUEST_ACCEPTED:
- {
- AddLogMessage("ID_CONNECTION_REQUEST_ACCEPTED\n");
- managerStatus = RUNNING;
- if(outputLog.is_open()) outputLog << "[NetManager] ID_CONNECTION_REQUEST_ACCEPTED" << endl;
- break;
- }
- case ID_NEW_INCOMING_CONNECTION:
- {
- std::string buffer = "ID_NEW_INCOMING_CONNECTION from ";
- buffer.append(rakPacket->systemAddress.ToString());
- AddLogMessage(buffer);
- if(outputLog.is_open()) outputLog << "[NetManager] ID_NEW_INCOMING_CONNECTION" << endl;
- break;
- }
- case ID_DISCONNECTION_NOTIFICATION:
- {
- AddLogMessage("ID_DISCONNECTION_NOTIFICATION\n");
- if(outputLog.is_open()) outputLog << "[NetManager] ID_DISCONNECTION_NOTIFICATION" << endl;
- break;
- }
- case ID_CONNECTION_LOST:
- {
- AddLogMessage("ID_CONNECTION_LOST\n");
- if(outputLog.is_open()) outputLog << "[NetManager] ID_CONNECTION_LOST" << endl;
- break;
- }
- case ID_ADVERTISE_SYSTEM:
- {
- //Edited: Originally, rakPacket->systemAddress.port
- //Dustin Farris: RakNet 4.033 rakPacket->systemAddress.GetPort() changed from rakPacket->systemAddress.port
- networkInterface->Connect(rakPacket->systemAddress.ToString(false), rakPacket->systemAddress.GetPort(),0,0);
- if(outputLog.is_open()) outputLog << "[NetManager] ID_ADVERTISE_SYSTEM" << endl;
- break;
- }
- default:
- {
- break;
- }
- } // end of switch(rakPacket->data[0])
- // if we have a custom packet handler, pass the message on
- // in case the application wants to do something special
- // in response to the packet we just received
- if (m_pCustomPacketHandler)
- (*m_pCustomPacketHandler)(rakPacket);
- } // end of for(rakPacket = networkInterface->Receive();...
- } // end of if(subsystem == RAKNET)
- return NETMANAGER_SUCCESS;
- }
- /// SendPacket - Sends data to a connection.
- ///
- /// Parameters:
- /// messageType - an ID value representing the message type. Taken from the enum DefaultMessageIDTypes or user-defined.
- /// message - the data to be sent
- /// messageLength - the length of the data to send
- /// messagePriority - the message priority value, taken from enum PacketPriority
- /// messageReliability - the message reliability value, taken from enum PacketReliability
- /// channel - the ordering channel. Default value is 0
- /// destination - the destination system information (IP, port). Default value is UNASSIGNED_SYSTEM_ADDRESS (RakNet value reserved for unknown system)
- /// broadcast - whether to broadcast the message to all connected systems. When this is true, destination refers to which system to skip.
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the call to RakPeerInterface->Send() returns false (send failure) or the system isn't connected.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- //NetManager::SendPacket(int messageType, const char *message, int messageLength, int messagePriority, int messageReliability, int channel, SystemAddress destination, bool broadcast)
- //raknet 4.0b8
- NetManager::SendPacket(int messageType, const char *message, int messageLength, int messagePriority, int messageReliability, int channel, RakNet::SystemAddress destination, bool broadcast)
- {
- if(NotStarted()) return NETMANAGER_FAILURE;
- //bool sendResult = false;
- //raknet 4.0b8
- uint32_t sendResult;
- if(subsystem == RAKNET)
- {
- RakNet::BitStream messageOut;
- messageOut.Write((unsigned char)messageType);
- messageOut.Write(message, messageLength);
- sendResult = networkInterface->Send(&messageOut, static_cast<PacketPriority>(messagePriority), static_cast<PacketReliability>(messageReliability),
- (char)channel, destination, broadcast);
- }
- //return( (sendResult)? NETMANAGER_SUCCESS : NETMANAGER_FAILURE );
- //RakNet 4.0b8
- if(sendResult==0)
- {
- return NETMANAGER_FAILURE;
- }
- else
- {
- return NETMANAGER_SUCCESS;
- }
- }
- /// SendPacket - Sends data saved in a BitStream to a connection.
- ///
- /// This function assumes that the data--including the messageType ID--has been previously written to a BitStream object.
- ///
- /// Parameters:
- /// message - the data previously written to the BitStream
- /// messagePriority - the message priority value, taken from enum PacketPriority
- /// messageReliability - the message reliability value, taken from enum PacketReliability
- /// channel - the ordering channel. Default value is 0
- /// destination - the destination system information (IP, port). Default value is UNASSIGNED_SYSTEM_ADDRESS (RakNet value reserved for unknown system)
- /// broadcast - whether to broadcast the message to all connected systems. When this is true, destination refers to which system to skip.
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the call to RakPeerInterface->Send() returns false (send failure) or the system isn't connected.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- //NetManager::SendPacket(RakNet::BitStream &message, int messagePriority, int messageReliability, int channel, SystemAddress destination, bool broadcast)
- // raknet 4.0b8
- NetManager::SendPacket(RakNet::BitStream &message, int messagePriority, int messageReliability, int channel, RakNet::SystemAddress destination, bool broadcast)
- {
- if(NotStarted()) return NETMANAGER_FAILURE;
- //bool sendResult = false;
- //raknet 4.0b8
- uint32_t sendResult;
- if(subsystem == RAKNET)
- {
- sendResult = networkInterface->Send(&message, static_cast<PacketPriority>(messagePriority), static_cast<PacketReliability>(messageReliability),
- (char)channel, destination, broadcast);
-
- }
- //return( (sendResult)? NETMANAGER_SUCCESS : NETMANAGER_FAILURE );
- //raknet 4.0b8
- if(sendResult==0)
- {
- return NETMANAGER_FAILURE;
- }
- else
- {
- return NETMANAGER_SUCCESS;
- }
- }
- /// UpdateNetworkObjectsInScene - Updates the local replicas with Ogre information and sets scene data.
- ///
- /// This function assumes that the replica will create needed Ogre entities and scene nodes.
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the pointer to the Ogre scene manager is NULL.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::UpdateNetworkObjectsInScene(Ogre::SceneManager *pSceneManager, EntityMapType &entityMap)
- {
- if(pSceneManager == NULL) return NETMANAGER_FAILURE;
- if(subsystem == RAKNET)
- {
- DataStructures::List<RakNet::Replica3*> fullReplicaList;
- // DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> fullReplicaList;
- replicaManager.GetReferencedReplicaList(fullReplicaList);
- // For each replica in the replica manager
- // Determine the entity name (replica.entityName)
- // Determine the scene node name (replica.entityName + ".SN")
- // If the entity does not exist in the scene
- // Create a new scene node and assign it the determined scene node name
- // Create a new entity and assign it the determined entity name
- // Attach the new entity to the new scene node
- // Get a reference to the entity and its scene node
- for(unsigned index = 0; index < replicaManager.GetReplicaCount(); index++)
- {
- //BasicReplica *replica = static_cast<BasicReplica *>(replicaManager.GetReplicaAtIndex(index));
- //raknet 4.0b8
- GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaManager.GetReplicaAtIndex(index));
- if(replica != NULL)
- {
- Ogre::String objectName = replica->GetObjectName();
- Ogre::String entityName = replica->GetEntityName();
- // If the entity name isn't set and this is a server or a peer, set the entity name now
- // This case only appears to happen for server instances when objects are created before
- // any client has ever connected.
- //
- // The problem doesn't appear to occur if objects are created after all clients have
- // been disconnected.
- //
- // We cannot do this for objects that are not NetworkIDAuthorities because the name
- // contains the unique shared network object value, which is invalid for non-authorities.
- if(entityName.empty())
- {
- //if(networkIDManager.IsNetworkIDAuthority())
- //raknet 4.0b8
- if(topology==SERVER)
- {
- // Entity base name format: "objectName.guid"
- Ogre::String newEntityName = objectName + ".";
- //newEntityName.append(Ogre::StringConverter::toString((int)(replica->GetNetworkID().localSystemAddress)));
- //ranket 4.0b8
- newEntityName.append(Ogre::StringConverter::toString((int)(replica->GetNetworkID())));
- replica->SetEntityName(newEntityName.c_str());
- entityName = replica->GetEntityName();
- }
- else
- {
- // If the entity name isn't set and this is a client, skip this object because we don't yet have
- // a valid network ID to construct an entity name and the object shouldn't be rendered
- continue;
- }
- }
- Ogre::String derivedSceneNodeName = entityName + ".SN"; // Scene node name format: "objectName.guid.SN"
- Ogre::SceneNode *node;
- Ogre::Entity *entity;
- if(!pSceneManager->hasEntity(entityName))
- {
- node = pSceneManager->getRootSceneNode()->createChildSceneNode(derivedSceneNodeName);
- entity = pSceneManager->createEntity(entityName, replica->GetMeshName());
- node->attachObject(entity);
- }
- else
- {
- node = pSceneManager->getSceneNode(derivedSceneNodeName);
- entity = pSceneManager->getEntity(entityName);
- }
- // Originally I wanted to be able to change the mesh of an object if that value was
- // changed, but it appears you would have to destroy and then recreate the entity
- // with the new mesh, so I'm excluding that functionality for now.
- // Update the scene with the information in the replica
- node->setScale(replica->GetScale());
- node->setOrientation(replica->GetOrientation());
- //node->setPosition(replica->UpdateRenderPosition(replica->GetCreatingSystemGUID() == networkIDManager.GetGuid()));
- //raknet 4.0b8
- node->setPosition(replica->UpdateRenderPosition(replica->GetCreatingSystemGUID() == networkInterface->GetMyGUID()));
- // Update the entity name indicating that this entity was seen in the replica manager
- entityMap[entityName] = true;
- } // end of if(replica != NULL)
- } // end of for(DataStructures::DefaultIndexType index = 0;...
- } // end of if(subsystem == RAKNET)
- return NETMANAGER_SUCCESS;
- }
- /// SetMessageLog - Sets a pointer to a LogMessage deque, used for on-screen feedback
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the pointer to the LogMessage deque is NULL.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::SetMessageLog(std::deque<LogMessage *> *newLog)
- {
- if(newLog == NULL) return NETMANAGER_FAILURE;
- globalLog = newLog;
- return NETMANAGER_SUCCESS;
- }
- /// AddLogMessage - Adds a new message to the LogMessage deque
- ///
- /// Returns:
- /// NETMANAGER_FAILURE, if the pointer to the LogMessage deque is NULL.
- /// NETMANAGER_SUCCESS, otherwise.
- int
- NetManager::AddLogMessage(std::string newMessage, int priority)
- {
- if(globalLog == NULL) return NETMANAGER_FAILURE;
- if(!globalLog->empty())
- globalLog->front()->messageAge += 1;
- globalLog->push_back(new LogMessage(newMessage, priority));
- return NETMANAGER_SUCCESS;
- }
- // LogMessage class stuff
- LogMessage::LogMessage() : messageAge(0), messagePriority(0), messageText("")
- {
-
- }
-
- LogMessage::LogMessage(std::string newMessage, int newPriority) : messageAge(0), messagePriority(newPriority), messageText(newMessage)
- {
-
- }
-
- LogMessage::~LogMessage()
- {
-
- }
- }