Bläddra i källkod

p2p flow updated

Arnis Lielturkss 7 år sedan
förälder
incheckning
153ada2bde

+ 37 - 2
Source/Samples/54_P2PMultiplayer/P2PMultiplayer.cpp

@@ -183,6 +183,12 @@ void P2PMultiplayer::HandleUnready(StringHash eventType, VariantMap& eventData)
 void P2PMultiplayer::HandleUpdate(StringHash eventType, VariantMap& eventData)
 void P2PMultiplayer::HandleUpdate(StringHash eventType, VariantMap& eventData)
 {
 {
     static int i = 0;
     static int i = 0;
+    auto input = GetSubsystem<Input>();
+    if (input->GetKeyDown(KEY_R) && GetSubsystem<Network>()->P2PIsHostSystem()) {
+        if (body_) {
+            body_->SetLinearVelocity(Vector3(0, 2, 0));
+        }
+    }
     if (timer_.GetMSec(false) > 500) {
     if (timer_.GetMSec(false) > 500) {
         i++;
         i++;
         timer_.Reset();
         timer_.Reset();
@@ -214,7 +220,7 @@ void P2PMultiplayer::Init()
 {
 {
 //    GetSubsystem<Network>()->SetNATServerInfo("frameskippers.com", 61111);
 //    GetSubsystem<Network>()->SetNATServerInfo("frameskippers.com", 61111);
     GetSubsystem<Network>()->SetNATServerInfo("frameskippers.com", 61111);
     GetSubsystem<Network>()->SetNATServerInfo("frameskippers.com", 61111);
-    GetSubsystem<Network>()->Connect("frameskippers.com", 61111, nullptr);
+    GetSubsystem<Network>()->P2PConnectNAT("frameskippers.com", 61111);
 }
 }
 
 
 //
 //
@@ -359,6 +365,32 @@ void P2PMultiplayer::CreateScene()
     // Set an initial position for the camera scene node above the plane
     // Set an initial position for the camera scene node above the plane
     cameraNode_->SetPosition(Vector3(-10.0f, 10.0f, 10.0f));
     cameraNode_->SetPosition(Vector3(-10.0f, 10.0f, 10.0f));
     cameraNode_->LookAt(Vector3(0, 0, 0));
     cameraNode_->LookAt(Vector3(0, 0, 0));
+
+    // Create the scene node & visual representation. This will be a replicated object
+    Node* ballNode = scene_->CreateChild("Ball");
+    ballNode->SetPosition(Vector3(0, 10, 0));
+    ballNode->SetScale(0.5f);
+    auto* ballObject = ballNode->CreateComponent<StaticModel>();
+    ballObject->SetModel(cache->GetResource<Model>("Models/Sphere.mdl"));
+    ballObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
+
+    // Create the physics components
+    auto* body = ballNode->CreateComponent<RigidBody>();
+    body->SetMass(1.0f);
+    body->SetFriction(1.0f);
+    body_ = body;
+    // In addition to friction, use motion damping so that the ball can not accelerate limitlessly
+//    body->SetLinearDamping(0.5f);
+//    body->SetAngularDamping(0.5f);
+    //body->SetLinearVelocity(Vector3(0.1, 1, 0.1));
+    auto* shape = ballNode->CreateComponent<CollisionShape>();
+    shape->SetSphere(1.0f);
+
+    // Create a random colored point light at the ball so that can see better where is going
+    auto* light2 = ballNode->CreateComponent<Light>();
+    light2->SetRange(3.0f);
+    light2->SetColor(
+        Color(0.5f + ((unsigned)Rand() & 1u) * 0.5f, 0.5f + ((unsigned)Rand() & 1u) * 0.5f, 0.5f + ((unsigned)Rand() & 1u) * 0.5f));
 }
 }
 
 
 void P2PMultiplayer::SetupViewport()
 void P2PMultiplayer::SetupViewport()
@@ -382,6 +414,7 @@ void P2PMultiplayer::HandleClientConnected(StringHash eventType, VariantMap& eve
     auto* newConnection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
     auto* newConnection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
     newConnection->SetScene(scene_);
     newConnection->SetScene(scene_);
 
 
+    return;
     // Then create a controllable object for that client
     // Then create a controllable object for that client
 //    Node* newObject = CreateControllableObject();
 //    Node* newObject = CreateControllableObject();
 //    serverObjects_[newConnection] = newObject;
 //    serverObjects_[newConnection] = newObject;
@@ -404,10 +437,11 @@ void P2PMultiplayer::HandleClientConnected(StringHash eventType, VariantMap& eve
     auto* body = ballNode->CreateComponent<RigidBody>();
     auto* body = ballNode->CreateComponent<RigidBody>();
     body->SetMass(1.0f);
     body->SetMass(1.0f);
     body->SetFriction(1.0f);
     body->SetFriction(1.0f);
+    body_ = body;
     // In addition to friction, use motion damping so that the ball can not accelerate limitlessly
     // In addition to friction, use motion damping so that the ball can not accelerate limitlessly
 //    body->SetLinearDamping(0.5f);
 //    body->SetLinearDamping(0.5f);
 //    body->SetAngularDamping(0.5f);
 //    body->SetAngularDamping(0.5f);
-    body->SetLinearVelocity(Vector3(0.1, 1, 0.1));
+    //body->SetLinearVelocity(Vector3(0.1, 1, 0.1));
     auto* shape = ballNode->CreateComponent<CollisionShape>();
     auto* shape = ballNode->CreateComponent<CollisionShape>();
     shape->SetSphere(1.0f);
     shape->SetSphere(1.0f);
 
 
@@ -422,6 +456,7 @@ void P2PMultiplayer::HandleClientDisconnected(StringHash eventType, VariantMap&
 {
 {
 //    return;
 //    return;
     using namespace ClientConnected;
     using namespace ClientConnected;
+    return;
 //
 //
 //    // When a client disconnects, remove the controlled object
 //    // When a client disconnects, remove the controlled object
     auto* connection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
     auto* connection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());

+ 1 - 0
Source/Samples/54_P2PMultiplayer/P2PMultiplayer.h

@@ -121,4 +121,5 @@ private:
 	SharedPtr<Text> clientCount_;
 	SharedPtr<Text> clientCount_;
     SharedPtr<Text> myGuid_;
     SharedPtr<Text> myGuid_;
     SharedPtr<Text> hostGuid_;
     SharedPtr<Text> hostGuid_;
+    SharedPtr<RigidBody> body_;
 };
 };

+ 2 - 0
Source/Samples/Sample.inl

@@ -209,6 +209,8 @@ void Sample::CreateConsoleAndDebugHud()
     Console* console = engine_->CreateConsole();
     Console* console = engine_->CreateConsole();
     console->SetDefaultStyle(xmlFile);
     console->SetDefaultStyle(xmlFile);
     console->GetBackground()->SetOpacity(0.8f);
     console->GetBackground()->SetOpacity(0.8f);
+    console->SetNumHistoryRows(1000);
+    console->SetNumBufferedRows(100);
 
 
     // Create debug HUD.
     // Create debug HUD.
     DebugHud* debugHud = engine_->CreateDebugHud();
     DebugHud* debugHud = engine_->CreateDebugHud();

+ 1 - 1
Source/ThirdParty/SLikeNet/Source/src/FullyConnectedMesh2.cpp

@@ -1113,7 +1113,7 @@ PluginReceiveResult FullyConnectedMesh2::OnVerifiedJoinCapable(Packet *packet)
 	DecomposeJoinCapable(packet, &vjip);
 	DecomposeJoinCapable(packet, &vjip);
 
 
 	// If this assert hits, AddParticipant() was called on this system, or another system, which it should not have been.
 	// If this assert hits, AddParticipant() was called on this system, or another system, which it should not have been.
-	RakAssert(HasParticipant(packet->guid)==false);
+	//RakAssert(HasParticipant(packet->guid)==false);
 
 
 	DataStructures::List<RakNetGUID> participatingMembersOnClientSucceeded;
 	DataStructures::List<RakNetGUID> participatingMembersOnClientSucceeded;
 	DataStructures::List<RakNetGUID> participatingMembersOnClientFailed;
 	DataStructures::List<RakNetGUID> participatingMembersOnClientFailed;

+ 1 - 0
Source/Urho3D/Network/Connection.cpp

@@ -399,6 +399,7 @@ void Connection::ProcessPendingLatestData()
 
 
 bool Connection::ProcessMessage(int msgID, MemoryBuffer& msg)
 bool Connection::ProcessMessage(int msgID, MemoryBuffer& msg)
 {
 {
+    URHO3D_LOGINFO("Process message " + String(msgID));
     // New incomming message, reset last heard timer
     // New incomming message, reset last heard timer
     lastHeardTimer_.Reset();
     lastHeardTimer_.Reset();
     tempPacketCounter_.x_++;
     tempPacketCounter_.x_++;

+ 71 - 35
Source/Urho3D/Network/Network.cpp

@@ -214,17 +214,16 @@ Network::Network(Context* context) :
     rakPeer_ = SLNet::RakPeerInterface::GetInstance();
     rakPeer_ = SLNet::RakPeerInterface::GetInstance();
     rakPeerClient_ = SLNet::RakPeerInterface::GetInstance();
     rakPeerClient_ = SLNet::RakPeerInterface::GetInstance();
 
 
-#if NETWORK_P2P
     fullyConnectedMesh2_ = SLNet::FullyConnectedMesh2::GetInstance();
     fullyConnectedMesh2_ = SLNet::FullyConnectedMesh2::GetInstance();
-    rakPeerClient_->AttachPlugin(fullyConnectedMesh2_);
+    rakPeer_->AttachPlugin(fullyConnectedMesh2_);
     fullyConnectedMesh2_->SetAutoparticipateConnections(false);
     fullyConnectedMesh2_->SetAutoparticipateConnections(false);
     readyEvent_ = SLNet::ReadyEvent::GetInstance();
     readyEvent_ = SLNet::ReadyEvent::GetInstance();
-    rakPeerClient_->AttachPlugin(readyEvent_);
+    rakPeer_->AttachPlugin(readyEvent_);
     connectionGraph2_ = SLNet::ConnectionGraph2::GetInstance();
     connectionGraph2_ = SLNet::ConnectionGraph2::GetInstance();
-    rakPeerClient_->AttachPlugin(connectionGraph2_);
-#endif
+    rakPeer_->AttachPlugin(connectionGraph2_);
 
 
     rakPeer_->SetTimeoutTime(SERVER_TIMEOUT_TIME, SLNet::UNASSIGNED_SYSTEM_ADDRESS);
     rakPeer_->SetTimeoutTime(SERVER_TIMEOUT_TIME, SLNet::UNASSIGNED_SYSTEM_ADDRESS);
+    rakPeerClient_->SetTimeoutTime(SERVER_TIMEOUT_TIME, SLNet::UNASSIGNED_SYSTEM_ADDRESS);
     SetPassword("");
     SetPassword("");
     SetDiscoveryBeacon(VariantMap());
     SetDiscoveryBeacon(VariantMap());
 
 
@@ -287,6 +286,9 @@ Network::~Network()
 {
 {
     rakPeer_->DetachPlugin(natPunchthroughServerClient_);
     rakPeer_->DetachPlugin(natPunchthroughServerClient_);
     rakPeerClient_->DetachPlugin(natPunchthroughClient_);
     rakPeerClient_->DetachPlugin(natPunchthroughClient_);
+    rakPeer_->DetachPlugin(fullyConnectedMesh2_);
+    rakPeer_->DetachPlugin(connectionGraph2_);
+    rakPeer_->DetachPlugin(readyEvent_);
     // If server connection exists, disconnect, but do not send an event because we are shutting down
     // If server connection exists, disconnect, but do not send an event because we are shutting down
     Disconnect(100);
     Disconnect(100);
     serverConnection_.Reset();
     serverConnection_.Reset();
@@ -304,11 +306,11 @@ Network::~Network()
 
 
     SLNet::RakPeerInterface::DestroyInstance(rakPeer_);
     SLNet::RakPeerInterface::DestroyInstance(rakPeer_);
     SLNet::RakPeerInterface::DestroyInstance(rakPeerClient_);
     SLNet::RakPeerInterface::DestroyInstance(rakPeerClient_);
-#if NETWORK_P2P
+
     SLNet::FullyConnectedMesh2::DestroyInstance(fullyConnectedMesh2_);
     SLNet::FullyConnectedMesh2::DestroyInstance(fullyConnectedMesh2_);
     SLNet::ReadyEvent::DestroyInstance(readyEvent_);
     SLNet::ReadyEvent::DestroyInstance(readyEvent_);
     SLNet::ConnectionGraph2::DestroyInstance(connectionGraph2_);
     SLNet::ConnectionGraph2::DestroyInstance(connectionGraph2_);
-#endif
+
     rakPeer_ = nullptr;
     rakPeer_ = nullptr;
     rakPeerClient_ = nullptr;
     rakPeerClient_ = nullptr;
 }
 }
@@ -340,7 +342,7 @@ void Network::NewConnectionEstablished(const SLNet::AddressOrGUID& connection)
 {
 {
     URHO3D_LOGINFO("NewConnectionEstablished ---------------------------");
     URHO3D_LOGINFO("NewConnectionEstablished ---------------------------");
     // Create a new client connection corresponding to this MessageConnection
     // Create a new client connection corresponding to this MessageConnection
-    SharedPtr<Connection> newConnection(new Connection(context_, true, connection, rakPeerClient_));
+    SharedPtr<Connection> newConnection(new Connection(context_, true, connection, rakPeer_));
     newConnection->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
     newConnection->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
     clientConnections_[connection] = newConnection;
     clientConnections_[connection] = newConnection;
     URHO3D_LOGINFO("Client " + newConnection->ToString() + " connected");
     URHO3D_LOGINFO("Client " + newConnection->ToString() + " connected");
@@ -435,6 +437,38 @@ bool Network::Connect(const String& address, unsigned short port, Scene* scene,
     }
     }
 }
 }
 
 
+bool Network::P2PConnectNAT(const String& address, unsigned short port)
+{
+    URHO3D_PROFILE(P2PConnectNAT);
+
+    if (!rakPeer_->IsActive())
+    {
+        URHO3D_LOGINFO("Initializing client connection...");
+        SLNet::SocketDescriptor socket;
+        // Startup local connection with max 2 incoming connections(first param) and 1 socket description (third param)
+        rakPeer_->Startup(32, &socket, 1);
+        rakPeer_->SetMaximumIncomingConnections(32);
+    }
+    else {
+        OnServerDisconnected();
+    }
+
+    //isServer_ = false;
+    SLNet::ConnectionAttemptResult connectResult = rakPeer_->Connect(address.CString(), port, password_.CString(), password_.Length());
+    if (connectResult != SLNet::CONNECTION_ATTEMPT_STARTED)
+    {
+        URHO3D_LOGERROR("Failed to connect to server " + address + ":" + String(port) + ", error code: " + String((int)connectResult));
+        SendEvent(E_CONNECTFAILED);
+        return false;
+    }
+    else
+    {
+
+        URHO3D_LOGINFO("Connecting to server " + address + ":" + String(port));
+        return true;
+    }
+}
+
 void Network::Disconnect(int waitMSec)
 void Network::Disconnect(int waitMSec)
 {
 {
     if (!serverConnection_)
     if (!serverConnection_)
@@ -765,7 +799,7 @@ void Network::HandleIncomingPacket(SLNet::Packet* packet, bool isServer)
         URHO3D_LOGINFOF("ID_REMOTE_NEW_INCOMING_CONNECTION from %s. guid=%s.", packet->systemAddress.ToString(true), packet->guid.ToString());
         URHO3D_LOGINFOF("ID_REMOTE_NEW_INCOMING_CONNECTION from %s. guid=%s.", packet->systemAddress.ToString(true), packet->guid.ToString());
         if (isServer)
         if (isServer)
         {
         {
-            NewConnectionEstablished(packet->systemAddress);
+            //NewConnectionEstablished(packet->systemAddress);
         }
         }
 //        fullyConnectedMesh2_->ResetHostCalculation();
 //        fullyConnectedMesh2_->ResetHostCalculation();
         packetHandled = true;
         packetHandled = true;
@@ -801,7 +835,7 @@ void Network::HandleIncomingPacket(SLNet::Packet* packet, bool isServer)
 //                OnServerConnected(packet->systemAddress);
 //                OnServerConnected(packet->systemAddress);
             SLNet::BitStream bsOut;
             SLNet::BitStream bsOut;
             bsOut.Write((unsigned char)MSG_P2P_REQUEST);
             bsOut.Write((unsigned char)MSG_P2P_REQUEST);
-            rakPeerClient_->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false);
+            rakPeer_->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false);
             URHO3D_LOGINFO("ID_CONNECTION_REQUEST_ACCEPTED");
             URHO3D_LOGINFO("ID_CONNECTION_REQUEST_ACCEPTED");
         }
         }
         packetHandled = true;
         packetHandled = true;
@@ -864,7 +898,7 @@ void Network::HandleIncomingPacket(SLNet::Packet* packet, bool isServer)
             URHO3D_LOGINFO("Connecting to server behind NAT: " + String(remotePeer.ToString()));
             URHO3D_LOGINFO("Connecting to server behind NAT: " + String(remotePeer.ToString()));
             Connect(String(remotePeer.ToString(false)), remotePeer.GetPort(), scene_, identity_);
             Connect(String(remotePeer.ToString(false)), remotePeer.GetPort(), scene_, identity_);
         } else {
         } else {
-            SLNet::ConnectionAttemptResult car = rakPeerClient_->Connect(packet->systemAddress.ToString(false), packet->systemAddress.GetPort(), 0, 0);
+            SLNet::ConnectionAttemptResult car = rakPeer_->Connect(packet->systemAddress.ToString(false), packet->systemAddress.GetPort(), 0, 0);
         }
         }
         packetHandled = true;
         packetHandled = true;
     }
     }
@@ -947,7 +981,6 @@ void Network::HandleIncomingPacket(SLNet::Packet* packet, bool isServer)
         }
         }
         packetHandled = true;
         packetHandled = true;
     }
     }
-#if NETWORK_P2P
     else if (packetID == ID_FCM2_NEW_HOST)
     else if (packetID == ID_FCM2_NEW_HOST)
     {
     {
         URHO3D_LOGINFO("");
         URHO3D_LOGINFO("");
@@ -957,7 +990,7 @@ void Network::HandleIncomingPacket(SLNet::Packet* packet, bool isServer)
         SLNet::RakNetGUID oldHost;
         SLNet::RakNetGUID oldHost;
         bs.Read(oldHost);
         bs.Read(oldHost);
 
 
-        if (packet->guid == rakPeerClient_->GetMyGUID())
+        if (packet->guid == rakPeer_->GetMyGUID())
         {
         {
             if (oldHost != SLNet::UNASSIGNED_RAKNET_GUID)
             if (oldHost != SLNet::UNASSIGNED_RAKNET_GUID)
             {
             {
@@ -1002,14 +1035,14 @@ void Network::HandleIncomingPacket(SLNet::Packet* packet, bool isServer)
     else if (packetID == ID_FCM2_VERIFIED_JOIN_START) {
     else if (packetID == ID_FCM2_VERIFIED_JOIN_START) {
 
 
         URHO3D_LOGINFO("ID_FCM2_VERIFIED_JOIN_START");
         URHO3D_LOGINFO("ID_FCM2_VERIFIED_JOIN_START");
-        DataStructures::List <SLNet::SystemAddress> addresses;
-        DataStructures::List <SLNet::RakNetGUID> guids;
-        DataStructures::List < SLNet::BitStream * > userData;
-        fullyConnectedMesh2_->GetVerifiedJoinRequiredProcessingList(packet->guid, addresses, guids, userData);
-        for (unsigned int i = 0; i < guids.Size(); i++)
-        {
-            natPunchthroughClient_->OpenNAT(guids[i], *natPunchServerAddress_);
-        }
+        //DataStructures::List <SLNet::SystemAddress> addresses;
+        //DataStructures::List <SLNet::RakNetGUID> guids;
+        //DataStructures::List < SLNet::BitStream * > userData;
+        //fullyConnectedMesh2_->GetVerifiedJoinRequiredProcessingList(packet->guid, addresses, guids, userData);
+        //for (unsigned int i = 0; i < guids.Size(); i++)
+        //{
+        //    //natPunchthroughServerClient_->OpenNAT(guids[i], *natPunchServerAddress_);
+        //}
 
 
     }
     }
     else if (packetID == ID_FCM2_VERIFIED_JOIN_CAPABLE)
     else if (packetID == ID_FCM2_VERIFIED_JOIN_CAPABLE)
@@ -1053,8 +1086,6 @@ void Network::HandleIncomingPacket(SLNet::Packet* packet, bool isServer)
     {
     {
         URHO3D_LOGINFO("ID_FCM2_UPDATE_USER_CONTEXT");
         URHO3D_LOGINFO("ID_FCM2_UPDATE_USER_CONTEXT");
     }
     }
-
-#endif
     // Urho3D messages
     // Urho3D messages
     if (packetID >= ID_USER_PACKET_ENUM)
     if (packetID >= ID_USER_PACKET_ENUM)
     {
     {
@@ -1065,7 +1096,7 @@ void Network::HandleIncomingPacket(SLNet::Packet* packet, bool isServer)
             fullyConnectedMesh2_->StartVerifiedJoin(packet->guid);
             fullyConnectedMesh2_->StartVerifiedJoin(packet->guid);
         } else if (packetID == MSG_P2P_DENY) {
         } else if (packetID == MSG_P2P_DENY) {
             URHO3D_LOGERROR("MSG_P2P_DENY");
             URHO3D_LOGERROR("MSG_P2P_DENY");
-        } else if (isServer)
+        } else if (1 == 1 || isServer)
         {
         {
             HandleMessage(packet->systemAddress, 0, packetID, (const char*)(packet->data + dataStart), packet->length - dataStart);
             HandleMessage(packet->systemAddress, 0, packetID, (const char*)(packet->data + dataStart), packet->length - dataStart);
         }
         }
@@ -1097,7 +1128,12 @@ void Network::Update(float timeStep)
     {
     {
         while (SLNet::Packet* packet = rakPeer_->Receive())
         while (SLNet::Packet* packet = rakPeer_->Receive())
         {
         {
-            HandleIncomingPacket(packet, true);
+            if (P2PIsHostSystem()) {
+                HandleIncomingPacket(packet, true);
+            }
+            else {
+                HandleIncomingPacket(packet, false);
+            }
             rakPeer_->DeallocatePacket(packet);
             rakPeer_->DeallocatePacket(packet);
         }
         }
     }
     }
@@ -1105,11 +1141,11 @@ void Network::Update(float timeStep)
     // Process all incoming messages for the client
     // Process all incoming messages for the client
     if (rakPeerClient_->IsActive())
     if (rakPeerClient_->IsActive())
     {
     {
-        bool isHost = P2PIsHostSystem();
+        //bool isHost = P2PIsHostSystem();
         while (SLNet::Packet* packet = rakPeerClient_->Receive())
         while (SLNet::Packet* packet = rakPeerClient_->Receive())
         {
         {
-            HandleIncomingPacket(packet, isHost);
-//            HandleIncomingPacket(packet, false);
+//            HandleIncomingPacket(packet, isHost);
+            HandleIncomingPacket(packet, false);
             rakPeerClient_->DeallocatePacket(packet);
             rakPeerClient_->DeallocatePacket(packet);
         }
         }
     }
     }
@@ -1232,13 +1268,13 @@ void Network::ConfigureNetworkSimulator()
 bool Network::StartP2PSession(Scene* scene, const VariantMap& identity)
 bool Network::StartP2PSession(Scene* scene, const VariantMap& identity)
 {
 {
     if (!serverConnection_) {
     if (!serverConnection_) {
-        serverConnection_ = new Connection(context_, false, rakPeerClient_->GetMyBoundAddress(), rakPeerClient_);
+        serverConnection_ = new Connection(context_, false, rakPeer_->GetMyBoundAddress(), rakPeer_);
         serverConnection_->SetScene(scene);
         serverConnection_->SetScene(scene);
         serverConnection_->SetIdentity(identity);
         serverConnection_->SetIdentity(identity);
         serverConnection_->SetConnectPending(true);
         serverConnection_->SetConnectPending(true);
         serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
         serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
     }
     }
-    rakPeerClient_->AttachPlugin(natPunchthroughClient_);
+    rakPeer_->AttachPlugin(natPunchthroughServerClient_);
     fullyConnectedMesh2_->Clear();
     fullyConnectedMesh2_->Clear();
     fullyConnectedMesh2_->ResetHostCalculation();
     fullyConnectedMesh2_->ResetHostCalculation();
     P2PSetReady(false);
     P2PSetReady(false);
@@ -1249,21 +1285,21 @@ void Network::JoinP2PSession(String guid, Scene* scene, const VariantMap& identi
 {
 {
     P2PSetReady(false);
     P2PSetReady(false);
     if (!serverConnection_) {
     if (!serverConnection_) {
-        serverConnection_ = new Connection(context_, false, rakPeerClient_->GetMyBoundAddress(), rakPeerClient_);
+        serverConnection_ = new Connection(context_, false, rakPeer_->GetMyBoundAddress(), rakPeer_);
         serverConnection_->SetScene(scene);
         serverConnection_->SetScene(scene);
         serverConnection_->SetIdentity(identity);
         serverConnection_->SetIdentity(identity);
         serverConnection_->SetConnectPending(true);
         serverConnection_->SetConnectPending(true);
         serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
         serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
     }
     }
 
 
-    rakPeerClient_->AttachPlugin(natPunchthroughClient_);
+    rakPeer_->AttachPlugin(natPunchthroughServerClient_);
     fullyConnectedMesh2_->ResetHostCalculation();
     fullyConnectedMesh2_->ResetHostCalculation();
     fullyConnectedMesh2_->Clear();
     fullyConnectedMesh2_->Clear();
     SLNet::RakNetGUID remoteGUID;
     SLNet::RakNetGUID remoteGUID;
 
 
     remoteGUID.FromString(guid.CString());
     remoteGUID.FromString(guid.CString());
     URHO3D_LOGINFO("Attempting to Join P2P Session : " + guid);
     URHO3D_LOGINFO("Attempting to Join P2P Session : " + guid);
-    natPunchthroughClient_->OpenNAT(remoteGUID, *natPunchServerAddress_);
+    natPunchthroughServerClient_->OpenNAT(remoteGUID, *natPunchServerAddress_);
 }
 }
 
 
 int Network::GetP2PParticipantCount()
 int Network::GetP2PParticipantCount()
@@ -1296,7 +1332,7 @@ String Network::P2PGetGUID()
 {
 {
 //    URHO3D_LOGINFO("HOST GUID: " + String(fullyConnectedMesh2_->GetHostSystem().ToString()));
 //    URHO3D_LOGINFO("HOST GUID: " + String(fullyConnectedMesh2_->GetHostSystem().ToString()));
 //    URHO3D_LOGINFO("MY GUID: " + String(rakPeerClient_->GetGuidFromSystemAddress(SLNet::UNASSIGNED_SYSTEM_ADDRESS).ToString()));
 //    URHO3D_LOGINFO("MY GUID: " + String(rakPeerClient_->GetGuidFromSystemAddress(SLNet::UNASSIGNED_SYSTEM_ADDRESS).ToString()));
-    return String(rakPeerClient_->GetGuidFromSystemAddress(SLNet::UNASSIGNED_SYSTEM_ADDRESS).ToString());
+    return String(rakPeer_->GetGuidFromSystemAddress(SLNet::UNASSIGNED_SYSTEM_ADDRESS).ToString());
 }
 }
 
 
 void Network::P2PShowReadyStatus()
 void Network::P2PShowReadyStatus()
@@ -1304,7 +1340,7 @@ void Network::P2PShowReadyStatus()
     DataStructures::List<SLNet::RakNetGUID> participantList;
     DataStructures::List<SLNet::RakNetGUID> participantList;
     fullyConnectedMesh2_->GetParticipantList(participantList);
     fullyConnectedMesh2_->GetParticipantList(participantList);
     for (unsigned int i = 0; i < participantList.Size(); i++) {
     for (unsigned int i = 0; i < participantList.Size(); i++) {
-        if (participantList[i] != rakPeerClient_->GetMyGUID()) {
+        if (participantList[i] != rakPeer_->GetMyGUID()) {
             bool ready = readyEvent_->GetReadyStatus(0, participantList[i]) == SLNet::RES_READY;
             bool ready = readyEvent_->GetReadyStatus(0, participantList[i]) == SLNet::RES_READY;
             URHO3D_LOGINFO( String(participantList[i].ToString()) + " Ready: " + String(ready));
             URHO3D_LOGINFO( String(participantList[i].ToString()) + " Ready: " + String(ready));
         }
         }

+ 5 - 6
Source/Urho3D/Network/Network.h

@@ -27,8 +27,6 @@
 #include "../IO/VectorBuffer.h"
 #include "../IO/VectorBuffer.h"
 #include "../Network/Connection.h"
 #include "../Network/Connection.h"
 
 
-#define NETWORK_P2P true
-
 namespace Urho3D
 namespace Urho3D
 {
 {
 
 
@@ -68,19 +66,20 @@ public:
     void Disconnect(int waitMSec = 0);
     void Disconnect(int waitMSec = 0);
     /// Start a server on a port using UDP protocol. Return true if successful.
     /// Start a server on a port using UDP protocol. Return true if successful.
     bool StartServer(unsigned short port);
     bool StartServer(unsigned short port);
-#if NETWORK_P2P
+
     /// Start P2P session
     /// Start P2P session
     bool StartP2PSession(Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
     bool StartP2PSession(Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
     void JoinP2PSession(String guid, Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
     void JoinP2PSession(String guid, Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
     int GetP2PParticipantCount();
     int GetP2PParticipantCount();
     bool P2PIsConnectedHost();
     bool P2PIsConnectedHost();
+    bool P2PConnectNAT(const String& address, unsigned short port);
     bool P2PIsHostSystem();
     bool P2PIsHostSystem();
     String P2PGetHostAddress();
     String P2PGetHostAddress();
     String P2PGetGUID();
     String P2PGetGUID();
     void P2PSetReady(bool value);
     void P2PSetReady(bool value);
     void P2PShowReadyStatus();
     void P2PShowReadyStatus();
     void P2PResetHost();
     void P2PResetHost();
-#endif
+
     /// Stop the server.
     /// Stop the server.
     void StopServer();
     void StopServer();
     /// Start NAT punchtrough client to allow remote connections.
     /// Start NAT punchtrough client to allow remote connections.
@@ -165,10 +164,10 @@ private:
     SLNet::RakPeerInterface* rakPeer_;
     SLNet::RakPeerInterface* rakPeer_;
     /// SLikeNet peer instance for client connection.
     /// SLikeNet peer instance for client connection.
     SLNet::RakPeerInterface* rakPeerClient_;
     SLNet::RakPeerInterface* rakPeerClient_;
-#if NETWORK_P2P
+
     /// P2P functionality
     /// P2P functionality
     SLNet::FullyConnectedMesh2 *fullyConnectedMesh2_;
     SLNet::FullyConnectedMesh2 *fullyConnectedMesh2_;
-#endif
+
     /// Client's server connection.
     /// Client's server connection.
     SharedPtr<Connection> serverConnection_;
     SharedPtr<Connection> serverConnection_;
     /// Server's client connections.
     /// Server's client connections.