RaycastVehicleDemo.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Core/CoreEvents.h>
  4. #include <Urho3D/Core/ProcessUtils.h>
  5. #include <Urho3D/Engine/Engine.h>
  6. #include <Urho3D/Graphics/Camera.h>
  7. #include <Urho3D/Graphics/Light.h>
  8. #include <Urho3D/Graphics/Material.h>
  9. #include <Urho3D/Graphics/Model.h>
  10. #include <Urho3D/Graphics/Octree.h>
  11. #include <Urho3D/Graphics/Renderer.h>
  12. #include <Urho3D/Graphics/StaticModel.h>
  13. #include <Urho3D/Graphics/Terrain.h>
  14. #include <Urho3D/Graphics/Zone.h>
  15. #include <Urho3D/IO/FileSystem.h>
  16. #include <Urho3D/Input/Input.h>
  17. #include <Urho3D/Physics/CollisionShape.h>
  18. #include <Urho3D/Physics/Constraint.h>
  19. #include <Urho3D/Physics/PhysicsWorld.h>
  20. #include <Urho3D/Physics/RaycastVehicle.h>
  21. #include <Urho3D/Physics/RigidBody.h>
  22. #include <Urho3D/Resource/ResourceCache.h>
  23. #include <Urho3D/Scene/Scene.h>
  24. #include <Urho3D/UI/Font.h>
  25. #include <Urho3D/UI/Text.h>
  26. #include <Urho3D/UI/UI.h>
  27. #include "RaycastVehicleDemo.h"
  28. #include "Vehicle.h"
  29. #include <Urho3D/DebugNew.h>
  30. const float CAMERA_DISTANCE = 10.0f;
  31. URHO3D_DEFINE_APPLICATION_MAIN(RaycastVehicleDemo)
  32. RaycastVehicleDemo::RaycastVehicleDemo(Context* context)
  33. : Sample(context)
  34. {
  35. // Register factory and attributes for the Vehicle component so it can be created via CreateComponent, and loaded / saved
  36. Vehicle::RegisterObject(context);
  37. }
  38. void RaycastVehicleDemo::Start()
  39. {
  40. // Execute base class startup
  41. Sample::Start();
  42. // Create static scene content
  43. CreateScene();
  44. // Create the controllable vehicle
  45. CreateVehicle();
  46. // Create the UI content
  47. CreateInstructions();
  48. // Subscribe to necessary events
  49. SubscribeToEvents();
  50. // Set the mouse mode to use in the sample
  51. Sample::InitMouseMode(MM_RELATIVE);
  52. }
  53. void RaycastVehicleDemo::CreateScene()
  54. {
  55. auto* cache = GetSubsystem<ResourceCache>();
  56. scene_ = new Scene(context_);
  57. // Create scene subsystem components
  58. scene_->CreateComponent<Octree>();
  59. scene_->CreateComponent<PhysicsWorld>();
  60. // Create camera and define viewport. We will be doing load / save, so it's convenient to create the camera outside the scene,
  61. // so that it won't be destroyed and recreated, and we don't have to redefine the viewport on load
  62. cameraNode_ = new Node(context_);
  63. auto* camera = cameraNode_->CreateComponent<Camera>();
  64. camera->SetFarClip(500.0f);
  65. GetSubsystem<Renderer>()->SetViewport(0, new Viewport(context_, scene_, camera));
  66. // Create static scene content. First create a zone for ambient lighting and fog control
  67. Node* zoneNode = scene_->CreateChild("Zone");
  68. auto* zone = zoneNode->CreateComponent<Zone>();
  69. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  70. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  71. zone->SetFogStart(300.0f);
  72. zone->SetFogEnd(500.0f);
  73. zone->SetBoundingBox(BoundingBox(-2000.0f, 2000.0f));
  74. // Create a directional light with cascaded shadow mapping
  75. Node* lightNode = scene_->CreateChild("DirectionalLight");
  76. lightNode->SetDirection(Vector3(0.3f, -0.5f, 0.425f));
  77. auto* light = lightNode->CreateComponent<Light>();
  78. light->SetLightType(LIGHT_DIRECTIONAL);
  79. light->SetCastShadows(true);
  80. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  81. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  82. light->SetSpecularIntensity(0.5f);
  83. // Create heightmap terrain with collision
  84. Node* terrainNode = scene_->CreateChild("Terrain");
  85. terrainNode->SetPosition(Vector3::ZERO);
  86. auto* terrain = terrainNode->CreateComponent<Terrain>();
  87. terrain->SetPatchSize(64);
  88. terrain->SetSpacing(Vector3(3.0f, 0.1f, 3.0f)); // Spacing between vertices and vertical resolution of the height map
  89. terrain->SetSmoothing(true);
  90. terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png"));
  91. terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
  92. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  93. // terrain patches and other objects behind it
  94. terrain->SetOccluder(true);
  95. auto* body = terrainNode->CreateComponent<RigidBody>();
  96. body->SetCollisionLayer(2); // Use layer bitmask 2 for static geometry
  97. auto* shape =
  98. terrainNode->CreateComponent<CollisionShape>();
  99. shape->SetTerrain();
  100. // Create 1000 mushrooms in the terrain. Always face outward along the terrain normal
  101. const unsigned NUM_MUSHROOMS = 1000;
  102. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  103. {
  104. Node* objectNode = scene_->CreateChild("Mushroom");
  105. Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
  106. position.y_ = terrain->GetHeight(position) - 0.1f;
  107. objectNode->SetPosition(position);
  108. // Create a rotation quaternion from up vector to terrain normal
  109. objectNode->SetRotation(Quaternion(Vector3::UP, terrain->GetNormal(position)));
  110. objectNode->SetScale(3.0f);
  111. auto* object = objectNode->CreateComponent<StaticModel>();
  112. object->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  113. object->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  114. object->SetCastShadows(true);
  115. auto* body = objectNode->CreateComponent<RigidBody>();
  116. body->SetCollisionLayer(2);
  117. auto* shape = objectNode->CreateComponent<CollisionShape>();
  118. shape->SetTriangleMesh(object->GetModel(), 0);
  119. }
  120. }
  121. void RaycastVehicleDemo::CreateVehicle()
  122. {
  123. Node* vehicleNode = scene_->CreateChild("Vehicle");
  124. vehicleNode->SetPosition(Vector3(0.0f, 25.0f, 0.0f));
  125. // Create the vehicle logic component
  126. vehicle_ = vehicleNode->CreateComponent<Vehicle>();
  127. // Create the rendering and physics components
  128. vehicle_->Init();
  129. }
  130. void RaycastVehicleDemo::CreateInstructions()
  131. {
  132. auto* cache = GetSubsystem<ResourceCache>();
  133. auto* ui = GetSubsystem<UI>();
  134. // Construct new Text object, set string to display and font to use
  135. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  136. instructionText->SetText(
  137. "Use WASD keys to drive, F to brake, mouse/touch to rotate camera\n"
  138. "F5 to save scene, F7 to load");
  139. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  140. // The text has multiple rows. Center them in relation to each other
  141. instructionText->SetTextAlignment(HA_CENTER);
  142. // Position the text relative to the screen center
  143. instructionText->SetHorizontalAlignment(HA_CENTER);
  144. instructionText->SetVerticalAlignment(VA_CENTER);
  145. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  146. }
  147. void RaycastVehicleDemo::SubscribeToEvents()
  148. {
  149. // Subscribe to Update event for setting the vehicle controls before physics simulation
  150. SubscribeToEvent(E_UPDATE,
  151. URHO3D_HANDLER(RaycastVehicleDemo, HandleUpdate));
  152. // Subscribe to PostUpdate event for updating the camera position after physics simulation
  153. SubscribeToEvent(E_POSTUPDATE,
  154. URHO3D_HANDLER(RaycastVehicleDemo,
  155. HandlePostUpdate));
  156. // Unsubscribe the SceneUpdate event from base class as the camera node is being controlled in HandlePostUpdate() in this sample
  157. UnsubscribeFromEvent(E_SCENEUPDATE);
  158. }
  159. void RaycastVehicleDemo::HandleUpdate(StringHash eventType,
  160. VariantMap& eventData)
  161. {
  162. using namespace Update;
  163. auto* input = GetSubsystem<Input>();
  164. if (vehicle_)
  165. {
  166. auto* ui = GetSubsystem<UI>();
  167. // Get movement controls and assign them to the vehicle component. If UI has a focused element, clear controls
  168. if (!ui->GetFocusElement())
  169. {
  170. vehicle_->controls_.Set(CTRL_FORWARD, input->GetKeyDown(KEY_W));
  171. vehicle_->controls_.Set(CTRL_BACK, input->GetKeyDown(KEY_S));
  172. vehicle_->controls_.Set(CTRL_LEFT, input->GetKeyDown(KEY_A));
  173. vehicle_->controls_.Set(CTRL_RIGHT, input->GetKeyDown(KEY_D));
  174. vehicle_->controls_.Set(CTRL_BRAKE, input->GetKeyDown(KEY_F));
  175. // Add yaw & pitch from the mouse motion or touch input. Used only for the camera, does not affect motion
  176. if (touchEnabled_)
  177. {
  178. for (i32 i = 0; i < input->GetNumTouches(); ++i)
  179. {
  180. TouchState* state = input->GetTouch(i);
  181. if (!state->touchedElement_) // Touch on empty space
  182. {
  183. auto* camera = cameraNode_->GetComponent<Camera>();
  184. if (!camera)
  185. {
  186. return;
  187. }
  188. auto* graphics = GetSubsystem<Graphics>();
  189. vehicle_->controls_.yaw_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.x_;
  190. vehicle_->controls_.pitch_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.y_;
  191. }
  192. }
  193. }
  194. else
  195. {
  196. vehicle_->controls_.yaw_ += (float)input->GetMouseMoveX() * YAW_SENSITIVITY;
  197. vehicle_->controls_.pitch_ += (float)input->GetMouseMoveY() * YAW_SENSITIVITY;
  198. }
  199. // Limit pitch
  200. vehicle_->controls_.pitch_ = Clamp(vehicle_->controls_.pitch_, 0.0f, 80.0f);
  201. // Check for loading / saving the scene
  202. if (input->GetKeyPress(KEY_F5))
  203. {
  204. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/RaycastVehicleDemo.xml",
  205. FILE_WRITE);
  206. scene_->SaveXML(saveFile);
  207. }
  208. if (input->GetKeyPress(KEY_F7))
  209. {
  210. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/RaycastVehicleDemo.xml",
  211. FILE_READ);
  212. scene_->LoadXML(loadFile);
  213. // After loading we have to reacquire the weak pointer to the Vehicle component, as it has been recreated
  214. // Simply find the vehicle's scene node by name as there's only one of them
  215. Node* vehicleNode = scene_->GetChild("Vehicle", true);
  216. if (vehicleNode)
  217. {
  218. vehicle_ = vehicleNode->GetComponent<Vehicle>();
  219. }
  220. }
  221. }
  222. else
  223. {
  224. vehicle_->controls_.Set(CTRL_FORWARD | CTRL_BACK | CTRL_LEFT | CTRL_RIGHT | CTRL_BRAKE, false);
  225. }
  226. }
  227. }
  228. void RaycastVehicleDemo::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  229. {
  230. if (!vehicle_)
  231. {
  232. return;
  233. }
  234. Node* vehicleNode = vehicle_->GetNode();
  235. // Physics update has completed. Position camera behind vehicle
  236. Quaternion dir(vehicleNode->GetRotation().YawAngle(), Vector3::UP);
  237. dir = dir * Quaternion(vehicle_->controls_.yaw_, Vector3::UP);
  238. dir = dir * Quaternion(vehicle_->controls_.pitch_, Vector3::RIGHT);
  239. Vector3 cameraTargetPos =
  240. vehicleNode->GetPosition() - dir * Vector3(0.0f, 0.0f, CAMERA_DISTANCE);
  241. Vector3 cameraStartPos = vehicleNode->GetPosition();
  242. // Raycast camera against static objects (physics collision mask 2)
  243. // and move it closer to the vehicle if something in between
  244. Ray cameraRay(cameraStartPos, cameraTargetPos - cameraStartPos);
  245. float cameraRayLength = (cameraTargetPos - cameraStartPos).Length();
  246. PhysicsRaycastResult result;
  247. scene_->GetComponent<PhysicsWorld>()->RaycastSingle(result, cameraRay, cameraRayLength, 2);
  248. if (result.body_)
  249. {
  250. cameraTargetPos = cameraStartPos + cameraRay.direction_ * (result.distance_ - 0.5f);
  251. }
  252. cameraNode_->SetPosition(cameraTargetPos);
  253. cameraNode_->SetRotation(dir);
  254. }