SceneReplication.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #define URHO3D_WEBSOCKETS
  23. #include <Urho3D/Core/CoreEvents.h>
  24. #include <Urho3D/Engine/Engine.h>
  25. #include <Urho3D/Graphics/Camera.h>
  26. #include <Urho3D/Graphics/Graphics.h>
  27. #include <Urho3D/Graphics/Light.h>
  28. #include <Urho3D/Graphics/Material.h>
  29. #include <Urho3D/Graphics/Model.h>
  30. #include <Urho3D/Graphics/Octree.h>
  31. #include <Urho3D/Graphics/Renderer.h>
  32. #include <Urho3D/Graphics/StaticModel.h>
  33. #include <Urho3D/Graphics/Zone.h>
  34. #include <Urho3D/Input/Controls.h>
  35. #include <Urho3D/Input/Input.h>
  36. #include <Urho3D/IO/Log.h>
  37. #include <Urho3D/Network/Connection.h>
  38. #include <Urho3D/Network/Network.h>
  39. #include <Urho3D/Network/NetworkEvents.h>
  40. #include <Urho3D/Physics/CollisionShape.h>
  41. #include <Urho3D/Physics/PhysicsEvents.h>
  42. #include <Urho3D/Physics/PhysicsWorld.h>
  43. #include <Urho3D/Physics/RigidBody.h>
  44. #include <Urho3D/Resource/ResourceCache.h>
  45. #include <Urho3D/Scene/Scene.h>
  46. #include <Urho3D/UI/Button.h>
  47. #include <Urho3D/UI/Font.h>
  48. #include <Urho3D/UI/LineEdit.h>
  49. #include <Urho3D/UI/Text.h>
  50. #include <Urho3D/UI/UI.h>
  51. #include <Urho3D/UI/UIEvents.h>
  52. #include "SceneReplication.h"
  53. #include <Urho3D/DebugNew.h>
  54. // UDP port we will use
  55. static const unsigned short SERVER_PORT = 2345;
  56. // Identifier for our custom remote event we use to tell the client which object they control
  57. static const StringHash E_CLIENTOBJECTID("ClientObjectID");
  58. // Identifier for the node ID parameter in the event data
  59. static const StringHash P_ID("ID");
  60. // Control bits we define
  61. static const unsigned CTRL_FORWARD = 1;
  62. static const unsigned CTRL_BACK = 2;
  63. static const unsigned CTRL_LEFT = 4;
  64. static const unsigned CTRL_RIGHT = 8;
  65. URHO3D_DEFINE_APPLICATION_MAIN(SceneReplication)
  66. bool isClient = false;
  67. SceneReplication::SceneReplication(Context* context) :
  68. Sample(context)
  69. {
  70. }
  71. void SceneReplication::Start()
  72. {
  73. // Execute base class startup
  74. Sample::Start();
  75. // Create the scene content
  76. CreateScene();
  77. // Create the UI content
  78. CreateUI();
  79. // Setup the viewport for displaying the scene
  80. SetupViewport();
  81. // Hook up to necessary events
  82. SubscribeToEvents();
  83. // Set the mouse mode to use in the sample
  84. Sample::InitMouseMode(MM_RELATIVE);
  85. auto* network = GetSubsystem<Network>();
  86. network->SetUpdateFps(30);
  87. }
  88. void SceneReplication::CreateScene()
  89. {
  90. scene_ = new Scene(context_);
  91. auto* cache = GetSubsystem<ResourceCache>();
  92. // Create octree and physics world with default settings. Create them as local so that they are not needlessly replicated
  93. // when a client connects
  94. scene_->CreateComponent<Octree>(LOCAL);
  95. scene_->CreateComponent<PhysicsWorld>(LOCAL);
  96. // All static scene content and the camera are also created as local, so that they are unaffected by scene replication and are
  97. // not removed from the client upon connection. Create a Zone component first for ambient lighting & fog control.
  98. Node* zoneNode = scene_->CreateChild("Zone", LOCAL);
  99. auto* zone = zoneNode->CreateComponent<Zone>();
  100. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  101. zone->SetAmbientColor(Color(0.1f, 0.1f, 0.1f));
  102. zone->SetFogStart(100.0f);
  103. zone->SetFogEnd(300.0f);
  104. // Create a directional light without shadows
  105. Node* lightNode = scene_->CreateChild("DirectionalLight", LOCAL);
  106. lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
  107. auto* light = lightNode->CreateComponent<Light>();
  108. light->SetLightType(LIGHT_DIRECTIONAL);
  109. light->SetColor(Color(0.2f, 0.2f, 0.2f));
  110. light->SetSpecularIntensity(1.0f);
  111. // Create a "floor" consisting of several tiles. Make the tiles physical but leave small cracks between them
  112. for (int y = -20; y <= 20; ++y)
  113. {
  114. for (int x = -20; x <= 20; ++x)
  115. {
  116. Node* floorNode = scene_->CreateChild("FloorTile", LOCAL);
  117. floorNode->SetPosition(Vector3(x * 20.2f, -0.5f, y * 20.2f));
  118. floorNode->SetScale(Vector3(20.0f, 1.0f, 20.0f));
  119. auto* floorObject = floorNode->CreateComponent<StaticModel>();
  120. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  121. floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  122. auto* body = floorNode->CreateComponent<RigidBody>();
  123. body->SetFriction(1.0f);
  124. auto* shape = floorNode->CreateComponent<CollisionShape>();
  125. shape->SetBox(Vector3::ONE);
  126. }
  127. }
  128. // Create the camera. Limit far clip distance to match the fog
  129. // The camera needs to be created into a local node so that each client can retain its own camera, that is unaffected by
  130. // network messages. Furthermore, because the client removes all replicated scene nodes when connecting to a server scene,
  131. // the screen would become blank if the camera node was replicated (as only the locally created camera is assigned to a
  132. // viewport in SetupViewports() below)
  133. cameraNode_ = scene_->CreateChild("Camera", LOCAL);
  134. auto* camera = cameraNode_->CreateComponent<Camera>();
  135. camera->SetFarClip(300.0f);
  136. // Set an initial position for the camera scene node above the plane
  137. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  138. }
  139. void SceneReplication::CreateUI()
  140. {
  141. auto* cache = GetSubsystem<ResourceCache>();
  142. auto* ui = GetSubsystem<UI>();
  143. UIElement* root = ui->GetRoot();
  144. auto* uiStyle = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  145. // Set style to the UI root so that elements will inherit it
  146. root->SetDefaultStyle(uiStyle);
  147. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  148. // control the camera, and when visible, it can interact with the login UI
  149. SharedPtr<Cursor> cursor(new Cursor(context_));
  150. cursor->SetStyleAuto(uiStyle);
  151. ui->SetCursor(cursor);
  152. // Set starting position of the cursor at the rendering window center
  153. auto* graphics = GetSubsystem<Graphics>();
  154. cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
  155. // Construct the instructions text element
  156. instructionsText_ = ui->GetRoot()->CreateChild<Text>();
  157. instructionsText_->SetText(
  158. "Use WASD keys to move and RMB to rotate view"
  159. );
  160. instructionsText_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  161. // Position the text relative to the screen center
  162. instructionsText_->SetHorizontalAlignment(HA_CENTER);
  163. instructionsText_->SetVerticalAlignment(VA_CENTER);
  164. instructionsText_->SetPosition(0, graphics->GetHeight() / 4);
  165. // Hide until connected
  166. instructionsText_->SetVisible(false);
  167. packetsIn_ = ui->GetRoot()->CreateChild<Text>();
  168. packetsIn_->SetText("Packets in : 0");
  169. packetsIn_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  170. packetsIn_->SetHorizontalAlignment(HA_LEFT);
  171. packetsIn_->SetVerticalAlignment(VA_CENTER);
  172. packetsIn_->SetPosition(10, -10);
  173. packetsOut_ = ui->GetRoot()->CreateChild<Text>();
  174. packetsOut_->SetText("Packets out: 0");
  175. packetsOut_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  176. packetsOut_->SetHorizontalAlignment(HA_LEFT);
  177. packetsOut_->SetVerticalAlignment(VA_CENTER);
  178. packetsOut_->SetPosition(10, 10);
  179. buttonContainer_ = root->CreateChild<UIElement>();
  180. buttonContainer_->SetFixedSize(500, 20);
  181. buttonContainer_->SetPosition(20, 20);
  182. buttonContainer_->SetLayoutMode(LM_HORIZONTAL);
  183. textEdit_ = buttonContainer_->CreateChild<LineEdit>();
  184. textEdit_->SetStyleAuto();
  185. connectButton_ = CreateButton("Connect", 90);
  186. disconnectButton_ = CreateButton("Disconnect", 100);
  187. startServerButton_ = CreateButton("Start Server", 110);
  188. UpdateButtons();
  189. }
  190. void SceneReplication::SetupViewport()
  191. {
  192. auto* renderer = GetSubsystem<Renderer>();
  193. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  194. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  195. renderer->SetViewport(0, viewport);
  196. }
  197. void SceneReplication::SubscribeToEvents()
  198. {
  199. // Subscribe to fixed timestep physics updates for setting or applying controls
  200. SubscribeToEvent(E_PHYSICSPRESTEP, URHO3D_HANDLER(SceneReplication, HandlePhysicsPreStep));
  201. // Subscribe HandlePostUpdate() method for processing update events. Subscribe to PostUpdate instead
  202. // of the usual Update so that physics simulation has already proceeded for the frame, and can
  203. // accurately follow the object with the camera
  204. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(SceneReplication, HandlePostUpdate));
  205. // Subscribe to button actions
  206. SubscribeToEvent(connectButton_, E_RELEASED, URHO3D_HANDLER(SceneReplication, HandleConnect));
  207. SubscribeToEvent(disconnectButton_, E_RELEASED, URHO3D_HANDLER(SceneReplication, HandleDisconnect));
  208. SubscribeToEvent(startServerButton_, E_RELEASED, URHO3D_HANDLER(SceneReplication, HandleStartServer));
  209. // Subscribe to network events
  210. SubscribeToEvent(E_SERVERCONNECTED, URHO3D_HANDLER(SceneReplication, HandleConnectionStatus));
  211. SubscribeToEvent(E_SERVERDISCONNECTED, URHO3D_HANDLER(SceneReplication, HandleConnectionStatus));
  212. SubscribeToEvent(E_CONNECTFAILED, URHO3D_HANDLER(SceneReplication, HandleConnectionStatus));
  213. SubscribeToEvent(E_CLIENTCONNECTED, URHO3D_HANDLER(SceneReplication, HandleClientConnected));
  214. SubscribeToEvent(E_CLIENTDISCONNECTED, URHO3D_HANDLER(SceneReplication, HandleClientDisconnected));
  215. // This is a custom event, sent from the server to the client. It tells the node ID of the object the client should control
  216. SubscribeToEvent(E_CLIENTOBJECTID, URHO3D_HANDLER(SceneReplication, HandleClientObjectID));
  217. // Events sent between client & server (remote events) must be explicitly registered or else they are not allowed to be received
  218. GetSubsystem<Network>()->RegisterRemoteEvent(E_CLIENTOBJECTID);
  219. }
  220. Button* SceneReplication::CreateButton(const String& text, int width)
  221. {
  222. auto* cache = GetSubsystem<ResourceCache>();
  223. auto* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
  224. auto* button = buttonContainer_->CreateChild<Button>();
  225. button->SetStyleAuto();
  226. button->SetFixedWidth(width);
  227. auto* buttonText = button->CreateChild<Text>();
  228. buttonText->SetFont(font, 12);
  229. buttonText->SetAlignment(HA_CENTER, VA_CENTER);
  230. buttonText->SetText(text);
  231. return button;
  232. }
  233. void SceneReplication::UpdateButtons()
  234. {
  235. auto* network = GetSubsystem<Network>();
  236. Connection* serverConnection = network->GetServerConnection();
  237. bool serverRunning = network->IsServerRunning();
  238. // Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time
  239. connectButton_->SetVisible(!serverConnection && !serverRunning);
  240. disconnectButton_->SetVisible(serverConnection || serverRunning);
  241. startServerButton_->SetVisible(!serverConnection && !serverRunning);
  242. textEdit_->SetVisible(!serverConnection && !serverRunning);
  243. }
  244. Node* SceneReplication::CreateControllableObject()
  245. {
  246. auto* cache = GetSubsystem<ResourceCache>();
  247. // Create the scene node & visual representation. This will be a replicated object
  248. Node* ballNode = scene_->CreateChild("Ball");
  249. ballNode->SetPosition(Vector3(Random(40.0f) - 20.0f, 5.0f, Random(40.0f) - 20.0f));
  250. ballNode->SetScale(0.5f);
  251. auto* ballObject = ballNode->CreateComponent<StaticModel>();
  252. ballObject->SetModel(cache->GetResource<Model>("Models/Sphere.mdl"));
  253. ballObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
  254. // Create the physics components
  255. auto* body = ballNode->CreateComponent<RigidBody>();
  256. body->SetMass(1.0f);
  257. body->SetFriction(1.0f);
  258. // In addition to friction, use motion damping so that the ball can not accelerate limitlessly
  259. body->SetLinearDamping(0.5f);
  260. body->SetAngularDamping(0.5f);
  261. auto* shape = ballNode->CreateComponent<CollisionShape>();
  262. shape->SetSphere(1.0f);
  263. // Create a random colored point light at the ball so that can see better where is going
  264. auto* light = ballNode->CreateComponent<Light>();
  265. light->SetRange(3.0f);
  266. light->SetColor(
  267. Color(0.5f + ((unsigned)Rand() & 1u) * 0.5f, 0.5f + ((unsigned)Rand() & 1u) * 0.5f, 0.5f + ((unsigned)Rand() & 1u) * 0.5f));
  268. return ballNode;
  269. }
  270. void SceneReplication::MoveCamera()
  271. {
  272. // Right mouse button controls mouse cursor visibility: hide when pressed
  273. auto* ui = GetSubsystem<UI>();
  274. auto* input = GetSubsystem<Input>();
  275. ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
  276. // Mouse sensitivity as degrees per pixel
  277. const float MOUSE_SENSITIVITY = 0.1f;
  278. if (input->GetKeyPress(KEY_P)) {
  279. // scene_->SetUpdateEnabled(!scene_->IsUpdateEnabled());
  280. // scene_->CreateComponent<PhysicsWorld>(LOCAL);
  281. // UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  282. // SubscribeToEvent(E_PHYSICSPRESTEP, URHO3D_HANDLER(SceneReplication, HandlePhysicsPreStep));
  283. }
  284. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch and only move the camera
  285. // when the cursor is hidden
  286. if (!ui->GetCursor()->IsVisible())
  287. {
  288. IntVector2 mouseMove = input->GetMouseMove();
  289. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  290. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  291. pitch_ = Clamp(pitch_, 1.0f, 90.0f);
  292. }
  293. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  294. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  295. // Only move the camera / show instructions if we have a controllable object
  296. bool showInstructions = false;
  297. if (clientObjectID_)
  298. {
  299. Node* ballNode = scene_->GetNode(clientObjectID_);
  300. if (ballNode)
  301. {
  302. const float CAMERA_DISTANCE = 5.0f;
  303. // Move camera some distance away from the ball
  304. cameraNode_->SetPosition(ballNode->GetPosition() + cameraNode_->GetRotation() * Vector3::BACK * CAMERA_DISTANCE);
  305. showInstructions = true;
  306. }
  307. }
  308. instructionsText_->SetVisible(showInstructions);
  309. }
  310. void SceneReplication::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  311. {
  312. // We only rotate the camera according to mouse movement since last frame, so do not need the time step
  313. MoveCamera();
  314. if (packetCounterTimer_.GetMSec(false) > 1000 && GetSubsystem<Network>()->GetServerConnection())
  315. {
  316. packetsIn_->SetText("Packets in (as client) : " + String(GetSubsystem<Network>()->GetServerConnection()->GetPacketsInPerSec()));
  317. packetsOut_->SetText("Packets out (as client): " + String(GetSubsystem<Network>()->GetServerConnection()->GetPacketsOutPerSec()));
  318. packetCounterTimer_.Reset();
  319. }
  320. else if (packetCounterTimer_.GetMSec(false) > 1000 && GetSubsystem<Network>()->IsServerRunning())
  321. {
  322. int packetsIn = 0;
  323. int packetsOut = 0;
  324. auto connections = GetSubsystem<Network>()->GetClientConnections();
  325. for (auto it = connections.Begin(); it != connections.End(); ++it ) {
  326. packetsIn += (*it)->GetPacketsInPerSec();
  327. packetsOut += (*it)->GetPacketsOutPerSec();
  328. }
  329. packetsIn_->SetText("Packets in (as server)[" + String(connections.Size()) + "] : " + String(packetsIn));
  330. packetsOut_->SetText("Packets out (as server)[" + String(connections.Size()) + "]: " + String(packetsOut));
  331. packetCounterTimer_.Reset();
  332. } else if (packetCounterTimer_.GetMSec(false) > 1000) {
  333. packetsIn_->SetText("Packets in : 0");
  334. packetsOut_->SetText("Packets out : 0");
  335. }
  336. }
  337. void SceneReplication::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  338. {
  339. // This function is different on the client and server. The client collects controls (WASD controls + yaw angle)
  340. // and sets them to its server connection object, so that they will be sent to the server automatically at a
  341. // fixed rate, by default 30 FPS. The server will actually apply the controls (authoritative simulation.)
  342. auto* network = GetSubsystem<Network>();
  343. Connection* serverConnection = network->GetServerConnection();
  344. if (isClient) {
  345. serverConnection;
  346. }
  347. // Client: collect controls
  348. if (serverConnection)
  349. {
  350. auto* ui = GetSubsystem<UI>();
  351. auto* input = GetSubsystem<Input>();
  352. Controls controls;
  353. // Copy mouse yaw
  354. controls.yaw_ = yaw_;
  355. // Only apply WASD controls if there is no focused UI element
  356. if (!ui->GetFocusElement())
  357. {
  358. controls.Set(CTRL_FORWARD, input->GetKeyDown(KEY_W));
  359. controls.Set(CTRL_BACK, input->GetKeyDown(KEY_S));
  360. controls.Set(CTRL_LEFT, input->GetKeyDown(KEY_A));
  361. controls.Set(CTRL_RIGHT, input->GetKeyDown(KEY_D));
  362. }
  363. serverConnection->SetControls(controls);
  364. // In case the server wants to do position-based interest management using the NetworkPriority components, we should also
  365. // tell it our observer (camera) position. In this sample it is not in use, but eg. the NinjaSnowWar game uses it
  366. serverConnection->SetPosition(cameraNode_->GetPosition());
  367. }
  368. // Server: apply controls to client objects
  369. else if (network->IsServerRunning())
  370. {
  371. const Vector<SharedPtr<Connection> >& connections = network->GetClientConnections();
  372. for (unsigned i = 0; i < connections.Size(); ++i)
  373. {
  374. Connection* connection = connections[i];
  375. // Get the object this connection is controlling
  376. Node* ballNode = serverObjects_[connection];
  377. if (!ballNode)
  378. continue;
  379. auto* body = ballNode->GetComponent<RigidBody>();
  380. // Get the last controls sent by the client
  381. const Controls& controls = connection->GetControls();
  382. // Torque is relative to the forward vector
  383. Quaternion rotation(0.0f, controls.yaw_, 0.0f);
  384. const float MOVE_TORQUE = 3.0f;
  385. // Movement torque is applied before each simulation step, which happen at 60 FPS. This makes the simulation
  386. // independent from rendering framerate. We could also apply forces (which would enable in-air control),
  387. // but want to emphasize that it's a ball which should only control its motion by rolling along the ground
  388. if (controls.buttons_ & CTRL_FORWARD)
  389. body->ApplyTorque(rotation * Vector3::RIGHT * MOVE_TORQUE);
  390. if (controls.buttons_ & CTRL_BACK)
  391. body->ApplyTorque(rotation * Vector3::LEFT * MOVE_TORQUE);
  392. if (controls.buttons_ & CTRL_LEFT)
  393. body->ApplyTorque(rotation * Vector3::FORWARD * MOVE_TORQUE);
  394. if (controls.buttons_ & CTRL_RIGHT)
  395. body->ApplyTorque(rotation * Vector3::BACK * MOVE_TORQUE);
  396. body->ApplyTorque(rotation * Vector3::RIGHT * MOVE_TORQUE * 0.1);
  397. }
  398. }
  399. }
  400. void SceneReplication::HandleConnect(StringHash eventType, VariantMap& eventData)
  401. {
  402. auto* network = GetSubsystem<Network>();
  403. String address = textEdit_->GetText().Trimmed();
  404. if (address.Empty())
  405. address = "localhost"; // Use localhost to connect if nothing else specified
  406. // Connect to server, specify scene to use as a client for replication
  407. clientObjectID_ = 0; // Reset own object ID from possible previous connection
  408. // network->Connect(address, SERVER_PORT, scene_);
  409. network->ConnectWS(address, SERVER_PORT, scene_);
  410. isClient = true;
  411. UpdateButtons();
  412. }
  413. void SceneReplication::HandleDisconnect(StringHash eventType, VariantMap& eventData)
  414. {
  415. auto* network = GetSubsystem<Network>();
  416. Connection* serverConnection = network->GetServerConnection();
  417. // If we were connected to server, disconnect. Or if we were running a server, stop it. In both cases clear the
  418. // scene of all replicated content, but let the local nodes & components (the static world + camera) stay
  419. if (serverConnection)
  420. {
  421. serverConnection->Disconnect();
  422. scene_->Clear(true, false);
  423. clientObjectID_ = 0;
  424. }
  425. // Or if we were running a server, stop it
  426. else if (network->IsServerRunning())
  427. {
  428. network->StopServer();
  429. scene_->Clear(true, false);
  430. }
  431. UpdateButtons();
  432. }
  433. void SceneReplication::HandleStartServer(StringHash eventType, VariantMap& eventData)
  434. {
  435. auto* network = GetSubsystem<Network>();
  436. network->StartServer(SERVER_PORT);
  437. UpdateButtons();
  438. }
  439. void SceneReplication::HandleConnectionStatus(StringHash eventType, VariantMap& eventData)
  440. {
  441. UpdateButtons();
  442. }
  443. void SceneReplication::HandleClientConnected(StringHash eventType, VariantMap& eventData)
  444. {
  445. using namespace ClientConnected;
  446. // When a client connects, assign to scene to begin scene replication
  447. auto* newConnection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
  448. newConnection->SetScene(scene_);
  449. // Then create a controllable object for that client
  450. Node* newObject = CreateControllableObject();
  451. serverObjects_[newConnection] = newObject;
  452. cameraNode_->SetPosition(newObject->GetWorldPosition());
  453. // Finally send the object's node ID using a remote event
  454. VariantMap remoteEventData;
  455. remoteEventData[P_ID] = newObject->GetID();
  456. newConnection->SendRemoteEvent(E_CLIENTOBJECTID, true, remoteEventData);
  457. }
  458. void SceneReplication::HandleClientDisconnected(StringHash eventType, VariantMap& eventData)
  459. {
  460. using namespace ClientConnected;
  461. // When a client disconnects, remove the controlled object
  462. auto* connection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
  463. Node* object = serverObjects_[connection];
  464. if (object)
  465. object->Remove();
  466. serverObjects_.Erase(connection);
  467. }
  468. void SceneReplication::HandleClientObjectID(StringHash eventType, VariantMap& eventData)
  469. {
  470. clientObjectID_ = eventData[P_ID].GetUInt();
  471. URHO3D_LOGINFOF("Received client object ID %d", clientObjectID_);
  472. }