Navigation.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Core/CoreEvents.h>
  4. #include <Urho3D/Engine/Engine.h>
  5. #include <Urho3D/Graphics/AnimatedModel.h>
  6. #include <Urho3D/Graphics/Camera.h>
  7. #include <Urho3D/Graphics/DebugRenderer.h>
  8. #include <Urho3D/Graphics/Graphics.h>
  9. #include <Urho3D/Graphics/Light.h>
  10. #include <Urho3D/Graphics/Material.h>
  11. #include <Urho3D/Graphics/Octree.h>
  12. #include <Urho3D/Graphics/Renderer.h>
  13. #include <Urho3D/Graphics/Zone.h>
  14. #include <Urho3D/Input/Input.h>
  15. #include <Urho3D/Navigation/Navigable.h>
  16. #include <Urho3D/Navigation/NavigationMesh.h>
  17. #include <Urho3D/Resource/ResourceCache.h>
  18. #include <Urho3D/Scene/Scene.h>
  19. #include <Urho3D/UI/Font.h>
  20. #include <Urho3D/UI/Text.h>
  21. #include <Urho3D/UI/UI.h>
  22. #include "Navigation.h"
  23. #include <Urho3D/DebugNew.h>
  24. URHO3D_DEFINE_APPLICATION_MAIN(Navigation)
  25. Navigation::Navigation(Context* context) :
  26. Sample(context),
  27. drawDebug_(false),
  28. useStreaming_(false),
  29. streamingDistance_(2)
  30. {
  31. }
  32. void Navigation::Start()
  33. {
  34. // Execute base class startup
  35. Sample::Start();
  36. // Create the scene content
  37. CreateScene();
  38. // Create the UI content
  39. CreateUI();
  40. // Setup the viewport for displaying the scene
  41. SetupViewport();
  42. // Hook up to the frame update and render post-update events
  43. SubscribeToEvents();
  44. // Set the mouse mode to use in the sample
  45. Sample::InitMouseMode(MM_RELATIVE);
  46. }
  47. void Navigation::CreateScene()
  48. {
  49. auto* cache = GetSubsystem<ResourceCache>();
  50. scene_ = new Scene(context_);
  51. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  52. // Also create a DebugRenderer component so that we can draw debug geometry
  53. scene_->CreateComponent<Octree>();
  54. scene_->CreateComponent<DebugRenderer>();
  55. // Create scene node & StaticModel component for showing a static plane
  56. Node* planeNode = scene_->CreateChild("Plane");
  57. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  58. auto* planeObject = planeNode->CreateComponent<StaticModel>();
  59. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  60. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  61. // Create a Zone component for ambient lighting & fog control
  62. Node* zoneNode = scene_->CreateChild("Zone");
  63. auto* zone = zoneNode->CreateComponent<Zone>();
  64. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  65. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  66. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  67. zone->SetFogStart(100.0f);
  68. zone->SetFogEnd(300.0f);
  69. // Create a directional light to the world. Enable cascaded shadows on it
  70. Node* lightNode = scene_->CreateChild("DirectionalLight");
  71. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  72. auto* light = lightNode->CreateComponent<Light>();
  73. light->SetLightType(LIGHT_DIRECTIONAL);
  74. light->SetCastShadows(true);
  75. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  76. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  77. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  78. // Create some mushrooms
  79. const unsigned NUM_MUSHROOMS = 100;
  80. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  81. CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  82. // Create randomly sized boxes. If boxes are big enough, make them occluders
  83. const unsigned NUM_BOXES = 20;
  84. for (unsigned i = 0; i < NUM_BOXES; ++i)
  85. {
  86. Node* boxNode = scene_->CreateChild("Box");
  87. float size = 1.0f + Random(10.0f);
  88. boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
  89. boxNode->SetScale(size);
  90. auto* boxObject = boxNode->CreateComponent<StaticModel>();
  91. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  92. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  93. boxObject->SetCastShadows(true);
  94. if (size >= 3.0f)
  95. boxObject->SetOccluder(true);
  96. }
  97. // Create Jack node that will follow the path
  98. jackNode_ = scene_->CreateChild("Jack");
  99. jackNode_->SetPosition(Vector3(-5.0f, 0.0f, 20.0f));
  100. auto* modelObject = jackNode_->CreateComponent<AnimatedModel>();
  101. modelObject->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
  102. modelObject->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
  103. modelObject->SetCastShadows(true);
  104. // Create a NavigationMesh component to the scene root
  105. auto* navMesh = scene_->CreateComponent<NavigationMesh>();
  106. // Set small tiles to show navigation mesh streaming
  107. navMesh->SetTileSize(32);
  108. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  109. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  110. scene_->CreateComponent<Navigable>();
  111. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  112. // in the scene and still update the mesh correctly
  113. navMesh->SetPadding(Vector3(0.0f, 10.0f, 0.0f));
  114. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  115. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  116. // it will use renderable geometry instead
  117. navMesh->Build();
  118. // Create the camera. Limit far clip distance to match the fog
  119. cameraNode_ = scene_->CreateChild("Camera");
  120. auto* camera = cameraNode_->CreateComponent<Camera>();
  121. camera->SetFarClip(300.0f);
  122. // Set an initial position for the camera scene node above the plane and looking down
  123. cameraNode_->SetPosition(Vector3(0.0f, 50.0f, 0.0f));
  124. pitch_ = 80.0f;
  125. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  126. }
  127. void Navigation::CreateUI()
  128. {
  129. auto* cache = GetSubsystem<ResourceCache>();
  130. auto* ui = GetSubsystem<UI>();
  131. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  132. // control the camera, and when visible, it will point the raycast target
  133. auto* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  134. SharedPtr<Cursor> cursor(new Cursor(context_));
  135. cursor->SetStyleAuto(style);
  136. ui->SetCursor(cursor);
  137. // Set starting position of the cursor at the rendering window center
  138. auto* graphics = GetSubsystem<Graphics>();
  139. cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
  140. // Construct new Text object, set string to display and font to use
  141. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  142. instructionText->SetText(
  143. "Use WASD keys to move, RMB to rotate view\n"
  144. "LMB to set destination, SHIFT+LMB to teleport\n"
  145. "MMB or O key to add or remove obstacles\n"
  146. "Tab to toggle navigation mesh streaming\n"
  147. "Space to toggle debug geometry"
  148. );
  149. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  150. // The text has multiple rows. Center them in relation to each other
  151. instructionText->SetTextAlignment(HA_CENTER);
  152. // Position the text relative to the screen center
  153. instructionText->SetHorizontalAlignment(HA_CENTER);
  154. instructionText->SetVerticalAlignment(VA_CENTER);
  155. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  156. }
  157. void Navigation::SetupViewport()
  158. {
  159. auto* 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 Navigation::SubscribeToEvents()
  165. {
  166. // Subscribe HandleUpdate() function for processing update events
  167. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Navigation, HandleUpdate));
  168. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  169. // debug geometry
  170. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Navigation, HandlePostRenderUpdate));
  171. }
  172. void Navigation::MoveCamera(float timeStep)
  173. {
  174. // Right mouse button controls mouse cursor visibility: hide when pressed
  175. auto* ui = GetSubsystem<UI>();
  176. auto* input = GetSubsystem<Input>();
  177. ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
  178. // Do not move if the UI has a focused element (the console)
  179. if (ui->GetFocusElement())
  180. return;
  181. // Movement speed as world units per second
  182. const float MOVE_SPEED = 20.0f;
  183. // Mouse sensitivity as degrees per pixel
  184. const float MOUSE_SENSITIVITY = 0.1f;
  185. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  186. // Only move the camera when the cursor is hidden
  187. if (!ui->GetCursor()->IsVisible())
  188. {
  189. IntVector2 mouseMove = input->GetMouseMove();
  190. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  191. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  192. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  193. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  194. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  195. }
  196. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  197. if (input->GetKeyDown(KEY_W))
  198. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  199. if (input->GetKeyDown(KEY_S))
  200. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  201. if (input->GetKeyDown(KEY_A))
  202. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  203. if (input->GetKeyDown(KEY_D))
  204. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  205. // Set destination or teleport with left mouse button
  206. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  207. SetPathPoint();
  208. // Add or remove objects with middle mouse button, then rebuild navigation mesh partially
  209. if (input->GetMouseButtonPress(MOUSEB_MIDDLE) || input->GetKeyPress(KEY_O))
  210. AddOrRemoveObject();
  211. // Toggle debug geometry with space
  212. if (input->GetKeyPress(KEY_SPACE))
  213. drawDebug_ = !drawDebug_;
  214. }
  215. void Navigation::SetPathPoint()
  216. {
  217. Vector3 hitPos;
  218. Drawable* hitDrawable;
  219. auto* navMesh = scene_->GetComponent<NavigationMesh>();
  220. if (Raycast(250.0f, hitPos, hitDrawable))
  221. {
  222. Vector3 pathPos = navMesh->FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
  223. if (GetSubsystem<Input>()->GetQualifierDown(QUAL_SHIFT))
  224. {
  225. // Teleport
  226. currentPath_.Clear();
  227. jackNode_->LookAt(Vector3(pathPos.x_, jackNode_->GetPosition().y_, pathPos.z_), Vector3::UP);
  228. jackNode_->SetPosition(pathPos);
  229. }
  230. else
  231. {
  232. // Calculate path from Jack's current position to the end point
  233. endPos_ = pathPos;
  234. navMesh->FindPath(currentPath_, jackNode_->GetPosition(), endPos_);
  235. }
  236. }
  237. }
  238. void Navigation::AddOrRemoveObject()
  239. {
  240. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  241. Vector3 hitPos;
  242. Drawable* hitDrawable;
  243. if (!useStreaming_ && Raycast(250.0f, hitPos, hitDrawable))
  244. {
  245. // The part of the navigation mesh we must update, which is the world bounding box of the associated
  246. // drawable component
  247. BoundingBox updateBox;
  248. Node* hitNode = hitDrawable->GetNode();
  249. if (hitNode->GetName() == "Mushroom")
  250. {
  251. updateBox = hitDrawable->GetWorldBoundingBox();
  252. hitNode->Remove();
  253. }
  254. else
  255. {
  256. Node* newNode = CreateMushroom(hitPos);
  257. updateBox = newNode->GetComponent<StaticModel>()->GetWorldBoundingBox();
  258. }
  259. // Rebuild part of the navigation mesh, then recalculate path if applicable
  260. auto* navMesh = scene_->GetComponent<NavigationMesh>();
  261. navMesh->Build(updateBox);
  262. if (currentPath_.Size())
  263. navMesh->FindPath(currentPath_, jackNode_->GetPosition(), endPos_);
  264. }
  265. }
  266. Node* Navigation::CreateMushroom(const Vector3& pos)
  267. {
  268. auto* cache = GetSubsystem<ResourceCache>();
  269. Node* mushroomNode = scene_->CreateChild("Mushroom");
  270. mushroomNode->SetPosition(pos);
  271. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  272. mushroomNode->SetScale(2.0f + Random(0.5f));
  273. auto* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  274. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  275. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  276. mushroomObject->SetCastShadows(true);
  277. return mushroomNode;
  278. }
  279. bool Navigation::Raycast(float maxDistance, Vector3& hitPos, Drawable*& hitDrawable)
  280. {
  281. hitDrawable = nullptr;
  282. auto* ui = GetSubsystem<UI>();
  283. IntVector2 pos = ui->GetCursorPosition();
  284. // Check the cursor is visible and there is no UI element in front of the cursor
  285. if (!ui->GetCursor()->IsVisible() || ui->GetElementAt(pos, true))
  286. return false;
  287. pos = ui->ConvertUIToSystem(pos);
  288. auto* graphics = GetSubsystem<Graphics>();
  289. auto* camera = cameraNode_->GetComponent<Camera>();
  290. Ray cameraRay = camera->GetScreenRay((float)pos.x_ / graphics->GetWidth(), (float)pos.y_ / graphics->GetHeight());
  291. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  292. Vector<RayQueryResult> results;
  293. RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, maxDistance, DrawableTypes::Geometry);
  294. scene_->GetComponent<Octree>()->RaycastSingle(query);
  295. if (results.Size())
  296. {
  297. RayQueryResult& result = results[0];
  298. hitPos = result.position_;
  299. hitDrawable = result.drawable_;
  300. return true;
  301. }
  302. return false;
  303. }
  304. void Navigation::FollowPath(float timeStep)
  305. {
  306. if (currentPath_.Size())
  307. {
  308. Vector3 nextWaypoint = currentPath_[0]; // NB: currentPath[0] is the next waypoint in order
  309. // Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target
  310. float move = 5.0f * timeStep;
  311. float distance = (jackNode_->GetPosition() - nextWaypoint).Length();
  312. if (move > distance)
  313. move = distance;
  314. jackNode_->LookAt(nextWaypoint, Vector3::UP);
  315. jackNode_->Translate(Vector3::FORWARD * move);
  316. // Remove waypoint if reached it
  317. if (distance < 0.1f)
  318. currentPath_.Erase(0);
  319. }
  320. }
  321. void Navigation::ToggleStreaming(bool enabled)
  322. {
  323. auto* navMesh = scene_->GetComponent<NavigationMesh>();
  324. if (enabled)
  325. {
  326. int maxTiles = (2 * streamingDistance_ + 1) * (2 * streamingDistance_ + 1);
  327. BoundingBox boundingBox = navMesh->GetBoundingBox();
  328. SaveNavigationData();
  329. navMesh->Allocate(boundingBox, maxTiles);
  330. }
  331. else
  332. navMesh->Build();
  333. }
  334. void Navigation::UpdateStreaming()
  335. {
  336. // Center the navigation mesh at the jack
  337. auto* navMesh = scene_->GetComponent<NavigationMesh>();
  338. const IntVector2 jackTile = navMesh->GetTileIndex(jackNode_->GetWorldPosition());
  339. const IntVector2 numTiles = navMesh->GetNumTiles();
  340. const IntVector2 beginTile = VectorMax(IntVector2::ZERO, jackTile - IntVector2::ONE * streamingDistance_);
  341. const IntVector2 endTile = VectorMin(jackTile + IntVector2::ONE * streamingDistance_, numTiles - IntVector2::ONE);
  342. // Remove tiles
  343. for (HashSet<IntVector2>::Iterator i = addedTiles_.Begin(); i != addedTiles_.End();)
  344. {
  345. const IntVector2 tileIdx = *i;
  346. if (beginTile.x_ <= tileIdx.x_ && tileIdx.x_ <= endTile.x_ && beginTile.y_ <= tileIdx.y_ && tileIdx.y_ <= endTile.y_)
  347. ++i;
  348. else
  349. {
  350. navMesh->RemoveTile(tileIdx);
  351. i = addedTiles_.Erase(i);
  352. }
  353. }
  354. // Add tiles
  355. for (int z = beginTile.y_; z <= endTile.y_; ++z)
  356. for (int x = beginTile.x_; x <= endTile.x_; ++x)
  357. {
  358. const IntVector2 tileIdx(x, z);
  359. if (!navMesh->HasTile(tileIdx) && tileData_.Contains(tileIdx))
  360. {
  361. addedTiles_.Insert(tileIdx);
  362. navMesh->AddTile(tileData_[tileIdx]);
  363. }
  364. }
  365. }
  366. void Navigation::SaveNavigationData()
  367. {
  368. auto* navMesh = scene_->GetComponent<NavigationMesh>();
  369. tileData_.Clear();
  370. addedTiles_.Clear();
  371. const IntVector2 numTiles = navMesh->GetNumTiles();
  372. for (int z = 0; z < numTiles.y_; ++z)
  373. for (int x = 0; x <= numTiles.x_; ++x)
  374. {
  375. const IntVector2 tileIdx = IntVector2(x, z);
  376. tileData_[tileIdx] = navMesh->GetTileData(tileIdx);
  377. }
  378. }
  379. void Navigation::HandleUpdate(StringHash eventType, VariantMap& eventData)
  380. {
  381. using namespace Update;
  382. // Take the frame time step, which is stored as a float
  383. float timeStep = eventData[P_TIMESTEP].GetFloat();
  384. // Move the camera, scale movement with time step
  385. MoveCamera(timeStep);
  386. // Make Jack follow the Detour path
  387. FollowPath(timeStep);
  388. // Update streaming
  389. auto* input = GetSubsystem<Input>();
  390. if (input->GetKeyPress(KEY_TAB))
  391. {
  392. useStreaming_ = !useStreaming_;
  393. ToggleStreaming(useStreaming_);
  394. }
  395. if (useStreaming_)
  396. UpdateStreaming();
  397. }
  398. void Navigation::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  399. {
  400. // If draw debug mode is enabled, draw navigation mesh debug geometry
  401. if (drawDebug_)
  402. scene_->GetComponent<NavigationMesh>()->DrawDebugGeometry(true);
  403. if (currentPath_.Size())
  404. {
  405. // Visualize the current calculated path
  406. auto* debug = scene_->GetComponent<DebugRenderer>();
  407. debug->AddBoundingBox(BoundingBox(endPos_ - Vector3(0.1f, 0.1f, 0.1f), endPos_ + Vector3(0.1f, 0.1f, 0.1f)),
  408. Color(1.0f, 1.0f, 1.0f));
  409. // Draw the path with a small upward bias so that it does not clip into the surfaces
  410. Vector3 bias(0.0f, 0.05f, 0.0f);
  411. debug->AddLine(jackNode_->GetPosition() + bias, currentPath_[0] + bias, Color(1.0f, 1.0f, 1.0f));
  412. if (currentPath_.Size() > 1)
  413. {
  414. for (i32 i = 0; i < currentPath_.Size() - 1; ++i)
  415. debug->AddLine(currentPath_[i] + bias, currentPath_[i + 1] + bias, Color(1.0f, 1.0f, 1.0f));
  416. }
  417. }
  418. }