VehicleDemo.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 "Camera.h"
  23. #include "CollisionShape.h"
  24. #include "Constraint.h"
  25. #include "CoreEvents.h"
  26. #include "Engine.h"
  27. #include "Font.h"
  28. #include "Input.h"
  29. #include "Light.h"
  30. #include "Material.h"
  31. #include "Model.h"
  32. #include "Octree.h"
  33. #include "PhysicsWorld.h"
  34. #include "ProcessUtils.h"
  35. #include "Renderer.h"
  36. #include "RigidBody.h"
  37. #include "ResourceCache.h"
  38. #include "Scene.h"
  39. #include "StaticModel.h"
  40. #include "Terrain.h"
  41. #include "Text.h"
  42. #include "UI.h"
  43. #include "Vehicle.h"
  44. #include "Zone.h"
  45. #include "VehicleDemo.h"
  46. #include "DebugNew.h"
  47. const float CAMERA_DISTANCE = 10.0f;
  48. DEFINE_APPLICATION_MAIN(VehicleDemo)
  49. VehicleDemo::VehicleDemo(Context* context) :
  50. Sample(context)
  51. {
  52. // Register factory for the Vehicle component so it can be created via CreateComponent
  53. context_->RegisterFactory<Vehicle>();
  54. }
  55. void VehicleDemo::Start()
  56. {
  57. // Execute base class startup
  58. Sample::Start();
  59. // Create static scene content
  60. CreateScene();
  61. // Create the controllable vehicle
  62. CreateVehicle();
  63. // Create the UI content
  64. CreateInstructions();
  65. // Subscribe to necessary events
  66. SubscribeToEvents();
  67. }
  68. void VehicleDemo::CreateScene()
  69. {
  70. ResourceCache* cache = GetSubsystem<ResourceCache>();
  71. scene_ = new Scene(context_);
  72. // Create scene subsystem components
  73. scene_->CreateComponent<Octree>();
  74. scene_->CreateComponent<PhysicsWorld>();
  75. // Create camera and define viewport. Camera does not necessarily have to belong to the scene
  76. cameraNode_ = new Node(context_);
  77. Camera* camera = cameraNode_->CreateComponent<Camera>();
  78. camera->SetFarClip(500.0f);
  79. GetSubsystem<Renderer>()->SetViewport(0, new Viewport(context_, scene_, camera));
  80. // Create static scene content. First create a zone for ambient lighting and fog control
  81. Node* zoneNode = scene_->CreateChild("Zone");
  82. Zone* zone = zoneNode->CreateComponent<Zone>();
  83. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  84. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  85. zone->SetFogStart(300.0f);
  86. zone->SetFogEnd(500.0f);
  87. zone->SetBoundingBox(BoundingBox(-2000.0f, 2000.0f));
  88. // Create a directional light with cascaded shadow mapping
  89. Node* lightNode = scene_->CreateChild("DirectionalLight");
  90. lightNode->SetDirection(Vector3(0.3f, -0.5f, 0.425f));
  91. Light* light = lightNode->CreateComponent<Light>();
  92. light->SetLightType(LIGHT_DIRECTIONAL);
  93. light->SetCastShadows(true);
  94. light->SetShadowBias(BiasParameters(0.0001f, 0.5f));
  95. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  96. light->SetSpecularIntensity(0.5f);
  97. // Create heightmap terrain with collision
  98. Node* terrainNode = scene_->CreateChild("Terrain");
  99. terrainNode->SetPosition(Vector3::ZERO);
  100. Terrain* terrain = terrainNode->CreateComponent<Terrain>();
  101. terrain->SetPatchSize(64);
  102. terrain->SetSpacing(Vector3(2.0f, 0.1f, 2.0f)); // Spacing between vertices and vertical resolution of the height map
  103. terrain->SetSmoothing(true);
  104. terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png"));
  105. terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
  106. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  107. // terrain patches and other objects behind it
  108. terrain->SetOccluder(true);
  109. RigidBody* body = terrainNode->CreateComponent<RigidBody>();
  110. body->SetCollisionLayer(2); // Use layer bitmask 2 for static geometry
  111. CollisionShape* shape = terrainNode->CreateComponent<CollisionShape>();
  112. shape->SetTerrain();
  113. // Create 1000 mushrooms in the terrain. Always face outward along the terrain normal
  114. const unsigned NUM_MUSHROOMS = 1000;
  115. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  116. {
  117. Node* objectNode = scene_->CreateChild("Mushroom");
  118. Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
  119. position.y_ = terrain->GetHeight(position) - 0.1f;
  120. objectNode->SetPosition(position);
  121. // Create a rotation quaternion from up vector to terrain normal
  122. objectNode->SetRotation(Quaternion(Vector3::UP, terrain->GetNormal(position)));
  123. objectNode->SetScale(3.0f);
  124. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  125. object->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  126. object->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  127. object->SetCastShadows(true);
  128. RigidBody* body = objectNode->CreateComponent<RigidBody>();
  129. body->SetCollisionLayer(2);
  130. CollisionShape* shape = objectNode->CreateComponent<CollisionShape>();
  131. shape->SetTriangleMesh(object->GetModel(), 0);
  132. }
  133. }
  134. void VehicleDemo::CreateVehicle()
  135. {
  136. ResourceCache* cache = GetSubsystem<ResourceCache>();
  137. Node* vehicleNode = scene_->CreateChild("Vehicle");
  138. vehicleNode->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  139. // Create the vehicle logic component
  140. vehicle_ = vehicleNode->CreateComponent<Vehicle>();
  141. // Create the rendering and physics components
  142. vehicle_->Init();
  143. }
  144. void VehicleDemo::CreateInstructions()
  145. {
  146. ResourceCache* cache = GetSubsystem<ResourceCache>();
  147. UI* ui = GetSubsystem<UI>();
  148. // Construct new Text object, set string to display and font to use
  149. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  150. instructionText->SetText(
  151. "Use WASD keys to drive, mouse to rotate camera"
  152. );
  153. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  154. // Position the text relative to the screen center
  155. instructionText->SetHorizontalAlignment(HA_CENTER);
  156. instructionText->SetVerticalAlignment(VA_CENTER);
  157. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  158. }
  159. void VehicleDemo::SubscribeToEvents()
  160. {
  161. // Subscribe to Update event for setting the vehicle controls before physics simulation
  162. SubscribeToEvent(E_UPDATE, HANDLER(VehicleDemo, HandleUpdate));
  163. // Subscribe to PostUpdate event for updating the camera position after physics simulation
  164. SubscribeToEvent(E_POSTUPDATE, HANDLER(VehicleDemo, HandlePostUpdate));
  165. }
  166. void VehicleDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  167. {
  168. using namespace Update;
  169. float timeStep = eventData[P_TIMESTEP].GetFloat();
  170. Input* input = GetSubsystem<Input>();
  171. if (vehicle_)
  172. {
  173. UI* ui = GetSubsystem<UI>();
  174. // Get movement controls and assign them to the vehicle component. If UI has a focused element, clear controls
  175. if (!ui->GetFocusElement())
  176. {
  177. vehicle_->controls_.Set(CTRL_FORWARD, input->GetKeyDown('W'));
  178. vehicle_->controls_.Set(CTRL_BACK, input->GetKeyDown('S'));
  179. vehicle_->controls_.Set(CTRL_LEFT, input->GetKeyDown('A'));
  180. vehicle_->controls_.Set(CTRL_RIGHT, input->GetKeyDown('D'));
  181. // Add yaw & pitch from the mouse motion. Used only for the camera, does not affect motion
  182. vehicle_->controls_.yaw_ += (float)input->GetMouseMoveX() * YAW_SENSITIVITY;
  183. vehicle_->controls_.pitch_ += (float)input->GetMouseMoveY() * YAW_SENSITIVITY;
  184. // Limit pitch
  185. vehicle_->controls_.pitch_ = Clamp(vehicle_->controls_.pitch_, 0.0f, 80.0f);
  186. }
  187. else
  188. vehicle_->controls_.Set(CTRL_FORWARD | CTRL_BACK | CTRL_LEFT | CTRL_RIGHT, false);
  189. }
  190. }
  191. void VehicleDemo::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  192. {
  193. if (!vehicle_)
  194. return;
  195. Node* vehicleNode = vehicle_->GetNode();
  196. // Physics update has completed. Position camera behind vehicle
  197. Quaternion dir(vehicleNode->GetRotation().YawAngle(), Vector3::UP);
  198. dir = dir * Quaternion(vehicle_->controls_.yaw_, Vector3::UP);
  199. dir = dir * Quaternion(vehicle_->controls_.pitch_, Vector3::RIGHT);
  200. Vector3 cameraTargetPos = vehicleNode->GetPosition() - dir * Vector3(0.0f, 0.0f, CAMERA_DISTANCE);
  201. Vector3 cameraStartPos = vehicleNode->GetPosition();
  202. // Raycast camera against static objects (physics collision mask 2)
  203. // and move it closer to the vehicle if something in between
  204. Ray cameraRay(cameraStartPos, (cameraTargetPos - cameraStartPos).Normalized());
  205. float cameraRayLength = (cameraTargetPos - cameraStartPos).Length();
  206. PhysicsRaycastResult result;
  207. scene_->GetComponent<PhysicsWorld>()->RaycastSingle(result, cameraRay, cameraRayLength, 2);
  208. if (result.body_)
  209. cameraTargetPos = cameraStartPos + cameraRay.direction_ * (result.distance_ - 0.5f);
  210. cameraNode_->SetPosition(cameraTargetPos);
  211. cameraNode_->SetRotation(dir);
  212. }