PhysicsStressTest.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. //
  2. // Copyright (c) 2008-2014 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/Urho3D.h>
  23. #include <Urho3D/Graphics/Camera.h>
  24. #include <Urho3D/Physics/CollisionShape.h>
  25. #include <Urho3D/Core/CoreEvents.h>
  26. #include <Urho3D/Graphics/DebugRenderer.h>
  27. #include <Urho3D/Engine/Engine.h>
  28. #include <Urho3D/IO/File.h>
  29. #include <Urho3D/IO/FileSystem.h>
  30. #include <Urho3D/UI/Font.h>
  31. #include <Urho3D/Graphics/Graphics.h>
  32. #include <Urho3D/Input/Input.h>
  33. #include <Urho3D/Graphics/Light.h>
  34. #include <Urho3D/Graphics/Material.h>
  35. #include <Urho3D/Graphics/Model.h>
  36. #include <Urho3D/Graphics/Octree.h>
  37. #include <Urho3D/Physics/PhysicsWorld.h>
  38. #include <Urho3D/Graphics/Renderer.h>
  39. #include <Urho3D/Resource/ResourceCache.h>
  40. #include <Urho3D/Physics/RigidBody.h>
  41. #include <Urho3D/Scene/Scene.h>
  42. #include <Urho3D/Graphics/StaticModel.h>
  43. #include <Urho3D/UI/Text.h>
  44. #include <Urho3D/UI/UI.h>
  45. #include <Urho3D/Graphics/Zone.h>
  46. #include "PhysicsStressTest.h"
  47. #include <Urho3D/DebugNew.h>
  48. DEFINE_APPLICATION_MAIN(PhysicsStressTest)
  49. PhysicsStressTest::PhysicsStressTest(Context* context) :
  50. Sample(context),
  51. drawDebug_(false)
  52. {
  53. }
  54. void PhysicsStressTest::Start()
  55. {
  56. // Execute base class startup
  57. Sample::Start();
  58. // Create the scene content
  59. CreateScene();
  60. // Create the UI content
  61. CreateInstructions();
  62. // Setup the viewport for displaying the scene
  63. SetupViewport();
  64. // Hook up to the frame update and render post-update events
  65. SubscribeToEvents();
  66. }
  67. void PhysicsStressTest::CreateScene()
  68. {
  69. ResourceCache* cache = GetSubsystem<ResourceCache>();
  70. scene_ = new Scene(context_);
  71. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  72. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  73. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  74. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  75. scene_->CreateComponent<Octree>();
  76. scene_->CreateComponent<PhysicsWorld>();
  77. scene_->CreateComponent<DebugRenderer>();
  78. // Create a Zone component for ambient lighting & fog control
  79. Node* zoneNode = scene_->CreateChild("Zone");
  80. Zone* zone = zoneNode->CreateComponent<Zone>();
  81. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  82. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  83. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  84. zone->SetFogStart(100.0f);
  85. zone->SetFogEnd(300.0f);
  86. // Create a directional light to the world. Enable cascaded shadows on it
  87. Node* lightNode = scene_->CreateChild("DirectionalLight");
  88. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  89. Light* light = lightNode->CreateComponent<Light>();
  90. light->SetLightType(LIGHT_DIRECTIONAL);
  91. light->SetCastShadows(true);
  92. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  93. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  94. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  95. {
  96. // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  97. Node* floorNode = scene_->CreateChild("Floor");
  98. floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
  99. floorNode->SetScale(Vector3(500.0f, 1.0f, 500.0f));
  100. StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
  101. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  102. floorObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  103. // Make the floor physical by adding RigidBody and CollisionShape components
  104. /*RigidBody* body = */floorNode->CreateComponent<RigidBody>();
  105. CollisionShape* shape = floorNode->CreateComponent<CollisionShape>();
  106. shape->SetBox(Vector3::ONE);
  107. }
  108. {
  109. // Create static mushrooms with triangle mesh collision
  110. const unsigned NUM_MUSHROOMS = 50;
  111. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  112. {
  113. Node* mushroomNode = scene_->CreateChild("Mushroom");
  114. mushroomNode->SetPosition(Vector3(Random(400.0f) - 200.0f, 0.0f, Random(400.0f) - 200.0f));
  115. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  116. mushroomNode->SetScale(5.0f + Random(5.0f));
  117. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  118. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  119. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  120. mushroomObject->SetCastShadows(true);
  121. /*RigidBody* body = */mushroomNode->CreateComponent<RigidBody>();
  122. CollisionShape* shape = mushroomNode->CreateComponent<CollisionShape>();
  123. // By default the highest LOD level will be used, the LOD level can be passed as an optional parameter
  124. shape->SetTriangleMesh(mushroomObject->GetModel());
  125. }
  126. }
  127. {
  128. // Create a large amount of falling physics objects
  129. const unsigned NUM_OBJECTS = 1000;
  130. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  131. {
  132. Node* boxNode = scene_->CreateChild("Box");
  133. boxNode->SetPosition(Vector3(0.0f, i * 2.0f + 100.0f, 0.0f));
  134. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  135. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  136. boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
  137. boxObject->SetCastShadows(true);
  138. // Give the RigidBody mass to make it movable and also adjust friction
  139. RigidBody* body = boxNode->CreateComponent<RigidBody>();
  140. body->SetMass(1.0f);
  141. body->SetFriction(1.0f);
  142. // Disable collision event signaling to reduce CPU load of the physics simulation
  143. body->SetCollisionEventMode(COLLISION_NEVER);
  144. CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
  145. shape->SetBox(Vector3::ONE);
  146. }
  147. }
  148. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  149. // the scene, because we want it to be unaffected by scene load / save
  150. cameraNode_ = new Node(context_);
  151. Camera* camera = cameraNode_->CreateComponent<Camera>();
  152. camera->SetFarClip(300.0f);
  153. // Set an initial position for the camera scene node above the floor
  154. cameraNode_->SetPosition(Vector3(0.0f, 3.0f, -20.0f));
  155. }
  156. void PhysicsStressTest::CreateInstructions()
  157. {
  158. ResourceCache* cache = GetSubsystem<ResourceCache>();
  159. UI* ui = GetSubsystem<UI>();
  160. // Construct new Text object, set string to display and font to use
  161. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  162. instructionText->SetText(
  163. "Use WASD keys and mouse/touch to move\n"
  164. "LMB to spawn physics objects\n"
  165. "F5 to save scene, F7 to load\n"
  166. "Space to toggle physics debug geometry"
  167. );
  168. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  169. // The text has multiple rows. Center them in relation to each other
  170. instructionText->SetTextAlignment(HA_CENTER);
  171. // Position the text relative to the screen center
  172. instructionText->SetHorizontalAlignment(HA_CENTER);
  173. instructionText->SetVerticalAlignment(VA_CENTER);
  174. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  175. }
  176. void PhysicsStressTest::SetupViewport()
  177. {
  178. Renderer* renderer = GetSubsystem<Renderer>();
  179. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  180. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  181. renderer->SetViewport(0, viewport);
  182. }
  183. void PhysicsStressTest::SubscribeToEvents()
  184. {
  185. // Subscribe HandleUpdate() function for processing update events
  186. SubscribeToEvent(E_UPDATE, HANDLER(PhysicsStressTest, HandleUpdate));
  187. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  188. // debug geometry
  189. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(PhysicsStressTest, HandlePostRenderUpdate));
  190. }
  191. void PhysicsStressTest::MoveCamera(float timeStep)
  192. {
  193. // Do not move if the UI has a focused element (the console)
  194. if (GetSubsystem<UI>()->GetFocusElement())
  195. return;
  196. Input* input = GetSubsystem<Input>();
  197. // Movement speed as world units per second
  198. const float MOVE_SPEED = 20.0f;
  199. // Mouse sensitivity as degrees per pixel
  200. const float MOUSE_SENSITIVITY = 0.1f;
  201. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  202. IntVector2 mouseMove = input->GetMouseMove();
  203. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  204. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  205. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  206. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  207. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  208. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  209. if (input->GetKeyDown('W'))
  210. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  211. if (input->GetKeyDown('S'))
  212. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  213. if (input->GetKeyDown('A'))
  214. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  215. if (input->GetKeyDown('D'))
  216. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  217. // "Shoot" a physics object with left mousebutton
  218. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  219. SpawnObject();
  220. // Check for loading / saving the scene
  221. if (input->GetKeyPress(KEY_F5))
  222. {
  223. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/PhysicsStressTest.xml", FILE_WRITE);
  224. scene_->SaveXML(saveFile);
  225. }
  226. if (input->GetKeyPress(KEY_F7))
  227. {
  228. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/PhysicsStressTest.xml", FILE_READ);
  229. scene_->LoadXML(loadFile);
  230. }
  231. // Toggle physics debug geometry with space
  232. if (input->GetKeyPress(KEY_SPACE))
  233. drawDebug_ = !drawDebug_;
  234. }
  235. void PhysicsStressTest::SpawnObject()
  236. {
  237. ResourceCache* cache = GetSubsystem<ResourceCache>();
  238. // Create a smaller box at camera position
  239. Node* boxNode = scene_->CreateChild("SmallBox");
  240. boxNode->SetPosition(cameraNode_->GetPosition());
  241. boxNode->SetRotation(cameraNode_->GetRotation());
  242. boxNode->SetScale(0.25f);
  243. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  244. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  245. boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
  246. boxObject->SetCastShadows(true);
  247. // Create physics components, use a smaller mass also
  248. RigidBody* body = boxNode->CreateComponent<RigidBody>();
  249. body->SetMass(0.25f);
  250. body->SetFriction(0.75f);
  251. CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
  252. shape->SetBox(Vector3::ONE);
  253. const float OBJECT_VELOCITY = 10.0f;
  254. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  255. // to overcome gravity better
  256. body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);
  257. }
  258. void PhysicsStressTest::HandleUpdate(StringHash eventType, VariantMap& eventData)
  259. {
  260. using namespace Update;
  261. // Take the frame time step, which is stored as a float
  262. float timeStep = eventData[P_TIMESTEP].GetFloat();
  263. // Move the camera, scale movement with time step
  264. MoveCamera(timeStep);
  265. }
  266. void PhysicsStressTest::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  267. {
  268. // If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  269. if (drawDebug_)
  270. scene_->GetComponent<PhysicsWorld>()->DrawDebugGeometry(true);
  271. }