Physics3D.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/Core/CoreEvents.h>
  24. #include <Atomic/Engine/Engine.h>
  25. #include <Atomic/Graphics/Camera.h>
  26. #include <Atomic/Graphics/DebugRenderer.h>
  27. #include <Atomic/Graphics/Graphics.h>
  28. #include <Atomic/Graphics/Light.h>
  29. #include <Atomic/Graphics/Material.h>
  30. #include <Atomic/Graphics/Model.h>
  31. #include <Atomic/Graphics/Octree.h>
  32. #include <Atomic/Graphics/Renderer.h>
  33. #include <Atomic/Graphics/Skybox.h>
  34. #include <Atomic/Graphics/Zone.h>
  35. #include <Atomic/Input/Input.h>
  36. #include <Atomic/IO/File.h>
  37. #include <Atomic/IO/FileSystem.h>
  38. #include <Atomic/Physics/CollisionShape.h>
  39. #include <Atomic/Physics/PhysicsWorld.h>
  40. #include <Atomic/Physics/RigidBody.h>
  41. #include <Atomic/Resource/ResourceCache.h>
  42. #include <Atomic/Scene/Scene.h>
  43. #include <Atomic/UI/UI.h>
  44. #include "Physics3D.h"
  45. #include <Atomic/DebugNew.h>
  46. Physics3D::Physics3D(Context* context) :
  47. Sample(context),
  48. drawDebug_(false)
  49. {
  50. }
  51. void Physics3D::Start()
  52. {
  53. // Execute base class startup
  54. Sample::Start();
  55. // Create the scene content
  56. CreateScene();
  57. // Create the UI content
  58. CreateInstructions();
  59. // Setup the viewport for displaying the scene
  60. SetupViewport();
  61. // Hook up to the frame update and render post-update events
  62. SubscribeToEvents();
  63. // Set the mouse mode to use in the sample
  64. Sample::InitMouseMode(MM_RELATIVE);
  65. }
  66. void Physics3D::CreateScene()
  67. {
  68. ResourceCache* cache = GetSubsystem<ResourceCache>();
  69. scene_ = new Scene(context_);
  70. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  71. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  72. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  73. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  74. scene_->CreateComponent<Octree>();
  75. scene_->CreateComponent<PhysicsWorld>();
  76. scene_->CreateComponent<DebugRenderer>();
  77. // Create a Zone component for ambient lighting & fog control
  78. Node* zoneNode = scene_->CreateChild("Zone");
  79. Zone* zone = zoneNode->CreateComponent<Zone>();
  80. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  81. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  82. zone->SetFogColor(Color(1.0f, 1.0f, 1.0f));
  83. zone->SetFogStart(300.0f);
  84. zone->SetFogEnd(500.0f);
  85. // Create a directional light to the world. Enable cascaded shadows on it
  86. Node* lightNode = scene_->CreateChild("DirectionalLight");
  87. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  88. Light* light = lightNode->CreateComponent<Light>();
  89. light->SetLightType(LIGHT_DIRECTIONAL);
  90. light->SetCastShadows(true);
  91. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  92. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  93. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  94. // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  95. // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  96. // generate the necessary 3D texture coordinates for cube mapping
  97. Node* skyNode = scene_->CreateChild("Sky");
  98. skyNode->SetScale(500.0f); // The scale actually does not matter
  99. Skybox* skybox = skyNode->CreateComponent<Skybox>();
  100. skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  101. skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
  102. {
  103. // Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y
  104. Node* floorNode = scene_->CreateChild("Floor");
  105. floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
  106. floorNode->SetScale(Vector3(1000.0f, 1.0f, 1000.0f));
  107. StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
  108. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  109. floorObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  110. // Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default
  111. // parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate
  112. // in the physics simulation
  113. /*RigidBody* body = */floorNode->CreateComponent<RigidBody>();
  114. CollisionShape* shape = floorNode->CreateComponent<CollisionShape>();
  115. // Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
  116. // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  117. shape->SetBox(Vector3::ONE);
  118. }
  119. {
  120. // Create a pyramid of movable physics objects
  121. for (int y = 0; y < 8; ++y)
  122. {
  123. for (int x = -y; x <= y; ++x)
  124. {
  125. Node* boxNode = scene_->CreateChild("Box");
  126. boxNode->SetPosition(Vector3((float)x, -(float)y + 8.0f, 0.0f));
  127. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  128. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  129. boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneEnvMapSmall.xml"));
  130. boxObject->SetCastShadows(true);
  131. // Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable
  132. // and also adjust friction. The actual mass is not important; only the mass ratios between colliding
  133. // objects are significant
  134. RigidBody* body = boxNode->CreateComponent<RigidBody>();
  135. body->SetMass(1.0f);
  136. body->SetFriction(0.75f);
  137. CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
  138. shape->SetBox(Vector3::ONE);
  139. }
  140. }
  141. }
  142. // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside the scene, because
  143. // we want it to be unaffected by scene load / save
  144. cameraNode_ = new Node(context_);
  145. Camera* camera = cameraNode_->CreateComponent<Camera>();
  146. camera->SetFarClip(500.0f);
  147. // Set an initial position for the camera scene node above the floor
  148. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, -20.0f));
  149. }
  150. void Physics3D::CreateInstructions()
  151. {
  152. SimpleCreateInstructions( "Use WASD keys and mouse/touch to move\n"
  153. "LMB to spawn physics objects\n"
  154. "F5 to save scene, F7 to load\n"
  155. "Space to toggle physics debug geometry" );
  156. }
  157. void Physics3D::SetupViewport()
  158. {
  159. Renderer* renderer = GetSubsystem<Renderer>();
  160. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  161. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  162. renderer->SetViewport(0, viewport);
  163. }
  164. void Physics3D::SubscribeToEvents()
  165. {
  166. // Subscribe HandleUpdate() function for processing update events
  167. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(Physics3D, HandleUpdate));
  168. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  169. // debug geometry
  170. SubscribeToEvent(E_POSTRENDERUPDATE, ATOMIC_HANDLER(Physics3D, HandlePostRenderUpdate));
  171. }
  172. void Physics3D::MoveCamera(float timeStep)
  173. {
  174. Input* input = GetSubsystem<Input>();
  175. // Movement speed as world units per second
  176. const float MOVE_SPEED = 20.0f;
  177. // Mouse sensitivity as degrees per pixel
  178. const float MOUSE_SENSITIVITY = 0.1f;
  179. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  180. IntVector2 mouseMove = input->GetMouseMove();
  181. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  182. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  183. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  184. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  185. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  186. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  187. if (input->GetKeyDown(KEY_W))
  188. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  189. if (input->GetKeyDown(KEY_S))
  190. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  191. if (input->GetKeyDown(KEY_A))
  192. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  193. if (input->GetKeyDown(KEY_D))
  194. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  195. // "Shoot" a physics object with left mousebutton
  196. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  197. SpawnObject();
  198. // Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
  199. // directory
  200. if (input->GetKeyPress(KEY_F5))
  201. {
  202. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/Physics.xml", FILE_WRITE);
  203. scene_->SaveXML(saveFile);
  204. }
  205. if (input->GetKeyPress(KEY_F7))
  206. {
  207. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/Physics.xml", FILE_READ);
  208. scene_->LoadXML(loadFile);
  209. }
  210. // Toggle physics debug geometry with space
  211. if (input->GetKeyPress(KEY_SPACE))
  212. drawDebug_ = !drawDebug_;
  213. }
  214. void Physics3D::SpawnObject()
  215. {
  216. ResourceCache* cache = GetSubsystem<ResourceCache>();
  217. // Create a smaller box at camera position
  218. Node* boxNode = scene_->CreateChild("SmallBox");
  219. boxNode->SetPosition(cameraNode_->GetPosition());
  220. boxNode->SetRotation(cameraNode_->GetRotation());
  221. boxNode->SetScale(0.25f);
  222. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  223. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  224. boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneEnvMapSmall.xml"));
  225. boxObject->SetCastShadows(true);
  226. // Create physics components, use a smaller mass also
  227. RigidBody* body = boxNode->CreateComponent<RigidBody>();
  228. body->SetMass(0.25f);
  229. body->SetFriction(0.75f);
  230. CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
  231. shape->SetBox(Vector3::ONE);
  232. const float OBJECT_VELOCITY = 10.0f;
  233. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  234. // to overcome gravity better
  235. body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);
  236. }
  237. void Physics3D::HandleUpdate(StringHash eventType, VariantMap& eventData)
  238. {
  239. using namespace Update;
  240. // Take the frame time step, which is stored as a float
  241. float timeStep = eventData[P_TIMESTEP].GetFloat();
  242. // Move the camera, scale movement with time step
  243. MoveCamera(timeStep);
  244. }
  245. void Physics3D::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  246. {
  247. // If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  248. if (drawDebug_)
  249. scene_->GetComponent<PhysicsWorld>()->DrawDebugGeometry(true);
  250. }