SceneReplication.cpp 24 KB

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