SceneReplication.cpp 20 KB

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