CrowdNavigation.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. //
  2. // Copyright (c) 2008-2017 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/Core/CoreEvents.h>
  23. #include <Urho3D/Engine/Engine.h>
  24. #include <Urho3D/Graphics/AnimatedModel.h>
  25. #include <Urho3D/Graphics/AnimationController.h>
  26. #include <Urho3D/Graphics/Camera.h>
  27. #include <Urho3D/Graphics/DebugRenderer.h>
  28. #include <Urho3D/Graphics/Graphics.h>
  29. #include <Urho3D/Graphics/Light.h>
  30. #include <Urho3D/Graphics/Material.h>
  31. #include <Urho3D/Graphics/Octree.h>
  32. #include <Urho3D/Graphics/Renderer.h>
  33. #include <Urho3D/Graphics/Zone.h>
  34. #include <Urho3D/Input/Input.h>
  35. #include <Urho3D/Navigation/CrowdAgent.h>
  36. #include <Urho3D/Navigation/DynamicNavigationMesh.h>
  37. #include <Urho3D/Navigation/Navigable.h>
  38. #include <Urho3D/Navigation/NavigationEvents.h>
  39. #include <Urho3D/Navigation/Obstacle.h>
  40. #include <Urho3D/Navigation/OffMeshConnection.h>
  41. #include <Urho3D/Resource/ResourceCache.h>
  42. #include <Urho3D/Scene/Scene.h>
  43. #include <Urho3D/UI/Font.h>
  44. #include <Urho3D/UI/Text.h>
  45. #include <Urho3D/UI/UI.h>
  46. #include "CrowdNavigation.h"
  47. #include <Urho3D/DebugNew.h>
  48. static const String INSTRUCTION("instructionText");
  49. URHO3D_DEFINE_APPLICATION_MAIN(CrowdNavigation)
  50. CrowdNavigation::CrowdNavigation(Context* context) :
  51. Sample(context),
  52. streamingDistance_(2),
  53. drawDebug_(false)
  54. {
  55. }
  56. void CrowdNavigation::Start()
  57. {
  58. // Execute base class startup
  59. Sample::Start();
  60. // Create the scene content
  61. CreateScene();
  62. // Create the UI content
  63. CreateUI();
  64. // Setup the viewport for displaying the scene
  65. SetupViewport();
  66. // Hook up to the frame update and render post-update events
  67. SubscribeToEvents();
  68. // Set the mouse mode to use in the sample
  69. Sample::InitMouseMode(MM_ABSOLUTE);
  70. }
  71. void CrowdNavigation::CreateScene()
  72. {
  73. auto* cache = GetSubsystem<ResourceCache>();
  74. scene_ = new Scene(context_);
  75. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  76. // Also create a DebugRenderer component so that we can draw debug geometry
  77. scene_->CreateComponent<Octree>();
  78. scene_->CreateComponent<DebugRenderer>();
  79. // Create scene node & StaticModel component for showing a static plane
  80. Node* planeNode = scene_->CreateChild("Plane");
  81. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  82. auto* planeObject = planeNode->CreateComponent<StaticModel>();
  83. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  84. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  85. // Create a Zone component for ambient lighting & fog control
  86. Node* zoneNode = scene_->CreateChild("Zone");
  87. auto* zone = zoneNode->CreateComponent<Zone>();
  88. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  89. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  90. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  91. zone->SetFogStart(100.0f);
  92. zone->SetFogEnd(300.0f);
  93. // Create a directional light to the world. Enable cascaded shadows on it
  94. Node* lightNode = scene_->CreateChild("DirectionalLight");
  95. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  96. auto* light = lightNode->CreateComponent<Light>();
  97. light->SetLightType(LIGHT_DIRECTIONAL);
  98. light->SetCastShadows(true);
  99. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  100. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  101. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  102. // Create randomly sized boxes. If boxes are big enough, make them occluders
  103. Node* boxGroup = scene_->CreateChild("Boxes");
  104. for (unsigned i = 0; i < 20; ++i)
  105. {
  106. Node* boxNode = boxGroup->CreateChild("Box");
  107. float size = 1.0f + Random(10.0f);
  108. boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
  109. boxNode->SetScale(size);
  110. auto* boxObject = boxNode->CreateComponent<StaticModel>();
  111. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  112. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  113. boxObject->SetCastShadows(true);
  114. if (size >= 3.0f)
  115. boxObject->SetOccluder(true);
  116. }
  117. // Create a DynamicNavigationMesh component to the scene root
  118. auto* navMesh = scene_->CreateComponent<DynamicNavigationMesh>();
  119. // Set small tiles to show navigation mesh streaming
  120. navMesh->SetTileSize(32);
  121. // Enable drawing debug geometry for obstacles and off-mesh connections
  122. navMesh->SetDrawObstacles(true);
  123. navMesh->SetDrawOffMeshConnections(true);
  124. // Set the agent height large enough to exclude the layers under boxes
  125. navMesh->SetAgentHeight(10.0f);
  126. // Set nav mesh cell height to minimum (allows agents to be grounded)
  127. navMesh->SetCellHeight(0.05f);
  128. // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
  129. // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
  130. scene_->CreateComponent<Navigable>();
  131. // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
  132. // in the scene and still update the mesh correctly
  133. navMesh->SetPadding(Vector3(0.0f, 10.0f, 0.0f));
  134. // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
  135. // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
  136. // it will use renderable geometry instead
  137. navMesh->Build();
  138. // Create an off-mesh connection to each box to make them climbable (tiny boxes are skipped). A connection is built from 2 nodes.
  139. // Note that OffMeshConnections must be added before building the navMesh, but as we are adding Obstacles next, tiles will be automatically rebuilt.
  140. // Creating connections post-build here allows us to use FindNearestPoint() to procedurally set accurate positions for the connection
  141. CreateBoxOffMeshConnections(navMesh, boxGroup);
  142. // Create some mushrooms as obstacles. Note that obstacles are non-walkable areas
  143. for (unsigned i = 0; i < 100; ++i)
  144. CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  145. // Create a CrowdManager component to the scene root
  146. auto* crowdManager = scene_->CreateComponent<CrowdManager>();
  147. CrowdObstacleAvoidanceParams params = crowdManager->GetObstacleAvoidanceParams(0);
  148. // Set the params to "High (66)" setting
  149. params.velBias = 0.5f;
  150. params.adaptiveDivs = 7;
  151. params.adaptiveRings = 3;
  152. params.adaptiveDepth = 3;
  153. crowdManager->SetObstacleAvoidanceParams(0, params);
  154. // Create some movable barrels. We create them as crowd agents, as for moving entities it is less expensive and more convenient than using obstacles
  155. CreateMovingBarrels(navMesh);
  156. // Create Jack node as crowd agent
  157. SpawnJack(Vector3(-5.0f, 0.0f, 20.0f), scene_->CreateChild("Jacks"));
  158. // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside the scene, because
  159. // we want it to be unaffected by scene load / save
  160. cameraNode_ = new Node(context_);
  161. auto* camera = cameraNode_->CreateComponent<Camera>();
  162. camera->SetFarClip(300.0f);
  163. // Set an initial position for the camera scene node above the plane and looking down
  164. cameraNode_->SetPosition(Vector3(0.0f, 50.0f, 0.0f));
  165. pitch_ = 80.0f;
  166. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  167. }
  168. void CrowdNavigation::CreateUI()
  169. {
  170. auto* cache = GetSubsystem<ResourceCache>();
  171. auto* ui = GetSubsystem<UI>();
  172. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  173. // control the camera, and when visible, it will point the raycast target
  174. auto* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  175. SharedPtr<Cursor> cursor(new Cursor(context_));
  176. cursor->SetStyleAuto(style);
  177. ui->SetCursor(cursor);
  178. // Set starting position of the cursor at the rendering window center
  179. auto* graphics = GetSubsystem<Graphics>();
  180. cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
  181. // Construct new Text object, set string to display and font to use
  182. auto* instructionText = ui->GetRoot()->CreateChild<Text>(INSTRUCTION);
  183. instructionText->SetText(
  184. "Use WASD keys to move, RMB to rotate view\n"
  185. "LMB to set destination, SHIFT+LMB to spawn a Jack\n"
  186. "MMB or O key to add obstacles or remove obstacles/agents\n"
  187. "F5 to save scene, F7 to load\n"
  188. "Tab to toggle navigation mesh streaming\n"
  189. "Space to toggle debug geometry\n"
  190. "F12 to toggle this instruction text"
  191. );
  192. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  193. // The text has multiple rows. Center them in relation to each other
  194. instructionText->SetTextAlignment(HA_CENTER);
  195. // Position the text relative to the screen center
  196. instructionText->SetHorizontalAlignment(HA_CENTER);
  197. instructionText->SetVerticalAlignment(VA_CENTER);
  198. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  199. }
  200. void CrowdNavigation::SetupViewport()
  201. {
  202. auto* renderer = GetSubsystem<Renderer>();
  203. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  204. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  205. renderer->SetViewport(0, viewport);
  206. }
  207. void CrowdNavigation::SubscribeToEvents()
  208. {
  209. // Subscribe HandleUpdate() function for processing update events
  210. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(CrowdNavigation, HandleUpdate));
  211. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request debug geometry
  212. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(CrowdNavigation, HandlePostRenderUpdate));
  213. // Subscribe HandleCrowdAgentFailure() function for resolving invalidation issues with agents, during which we
  214. // use a larger extents for finding a point on the navmesh to fix the agent's position
  215. SubscribeToEvent(E_CROWD_AGENT_FAILURE, URHO3D_HANDLER(CrowdNavigation, HandleCrowdAgentFailure));
  216. // Subscribe HandleCrowdAgentReposition() function for controlling the animation
  217. SubscribeToEvent(E_CROWD_AGENT_REPOSITION, URHO3D_HANDLER(CrowdNavigation, HandleCrowdAgentReposition));
  218. // Subscribe HandleCrowdAgentFormation() function for positioning agent into a formation
  219. SubscribeToEvent(E_CROWD_AGENT_FORMATION, URHO3D_HANDLER(CrowdNavigation, HandleCrowdAgentFormation));
  220. }
  221. void CrowdNavigation::SpawnJack(const Vector3& pos, Node* jackGroup)
  222. {
  223. auto* cache = GetSubsystem<ResourceCache>();
  224. SharedPtr<Node> jackNode(jackGroup->CreateChild("Jack"));
  225. jackNode->SetPosition(pos);
  226. auto* modelObject = jackNode->CreateComponent<AnimatedModel>();
  227. modelObject->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
  228. modelObject->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
  229. modelObject->SetCastShadows(true);
  230. jackNode->CreateComponent<AnimationController>();
  231. // Create a CrowdAgent component and set its height and realistic max speed/acceleration. Use default radius
  232. auto* agent = jackNode->CreateComponent<CrowdAgent>();
  233. agent->SetHeight(2.0f);
  234. agent->SetMaxSpeed(3.0f);
  235. agent->SetMaxAccel(5.0f);
  236. }
  237. void CrowdNavigation::CreateMushroom(const Vector3& pos)
  238. {
  239. auto* cache = GetSubsystem<ResourceCache>();
  240. Node* mushroomNode = scene_->CreateChild("Mushroom");
  241. mushroomNode->SetPosition(pos);
  242. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  243. mushroomNode->SetScale(2.0f + Random(0.5f));
  244. auto* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  245. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  246. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  247. mushroomObject->SetCastShadows(true);
  248. // Create the navigation Obstacle component and set its height & radius proportional to scale
  249. auto* obstacle = mushroomNode->CreateComponent<Obstacle>();
  250. obstacle->SetRadius(mushroomNode->GetScale().x_);
  251. obstacle->SetHeight(mushroomNode->GetScale().y_);
  252. }
  253. void CrowdNavigation::CreateBoxOffMeshConnections(DynamicNavigationMesh* navMesh, Node* boxGroup)
  254. {
  255. const Vector<SharedPtr<Node> >& boxes = boxGroup->GetChildren();
  256. for (unsigned i=0; i < boxes.Size(); ++i)
  257. {
  258. Node* box = boxes[i];
  259. Vector3 boxPos = box->GetPosition();
  260. float boxHalfSize = box->GetScale().x_ / 2;
  261. // Create 2 empty nodes for the start & end points of the connection. Note that order matters only when using one-way/unidirectional connection.
  262. Node* connectionStart = box->CreateChild("ConnectionStart");
  263. connectionStart->SetWorldPosition(navMesh->FindNearestPoint(boxPos + Vector3(boxHalfSize, -boxHalfSize, 0))); // Base of box
  264. Node* connectionEnd = connectionStart->CreateChild("ConnectionEnd");
  265. connectionEnd->SetWorldPosition(navMesh->FindNearestPoint(boxPos + Vector3(boxHalfSize, boxHalfSize, 0))); // Top of box
  266. // Create the OffMeshConnection component to one node and link the other node
  267. auto* connection = connectionStart->CreateComponent<OffMeshConnection>();
  268. connection->SetEndPoint(connectionEnd);
  269. }
  270. }
  271. void CrowdNavigation::CreateMovingBarrels(DynamicNavigationMesh* navMesh)
  272. {
  273. auto* cache = GetSubsystem<ResourceCache>();
  274. Node* barrel = scene_->CreateChild("Barrel");
  275. auto* model = barrel->CreateComponent<StaticModel>();
  276. model->SetModel(cache->GetResource<Model>("Models/Cylinder.mdl"));
  277. auto* material = cache->GetResource<Material>("Materials/StoneTiled.xml");
  278. model->SetMaterial(material);
  279. material->SetTexture(TU_DIFFUSE, cache->GetResource<Texture2D>("Textures/TerrainDetail2.dds"));
  280. model->SetCastShadows(true);
  281. for (unsigned i = 0; i < 20; ++i)
  282. {
  283. Node* clone = barrel->Clone();
  284. float size = 0.5f + Random(1.0f);
  285. clone->SetScale(Vector3(size / 1.5f, size * 2.0f, size / 1.5f));
  286. clone->SetPosition(navMesh->FindNearestPoint(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f)));
  287. auto* agent = clone->CreateComponent<CrowdAgent>();
  288. agent->SetRadius(clone->GetScale().x_ * 0.5f);
  289. agent->SetHeight(size);
  290. agent->SetNavigationQuality(NAVIGATIONQUALITY_LOW);
  291. }
  292. barrel->Remove();
  293. }
  294. void CrowdNavigation::SetPathPoint(bool spawning)
  295. {
  296. Vector3 hitPos;
  297. Drawable* hitDrawable;
  298. if (Raycast(250.0f, hitPos, hitDrawable))
  299. {
  300. auto* navMesh = scene_->GetComponent<DynamicNavigationMesh>();
  301. Vector3 pathPos = navMesh->FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
  302. Node* jackGroup = scene_->GetChild("Jacks");
  303. if (spawning)
  304. // Spawn a jack at the target position
  305. SpawnJack(pathPos, jackGroup);
  306. else
  307. // Set crowd agents target position
  308. scene_->GetComponent<CrowdManager>()->SetCrowdTarget(pathPos, jackGroup);
  309. }
  310. }
  311. void CrowdNavigation::AddOrRemoveObject()
  312. {
  313. // Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
  314. Vector3 hitPos;
  315. Drawable* hitDrawable;
  316. if (Raycast(250.0f, hitPos, hitDrawable))
  317. {
  318. Node* hitNode = hitDrawable->GetNode();
  319. // Note that navmesh rebuild happens when the Obstacle component is removed
  320. if (hitNode->GetName() == "Mushroom")
  321. hitNode->Remove();
  322. else if (hitNode->GetName() == "Jack")
  323. hitNode->Remove();
  324. else
  325. CreateMushroom(hitPos);
  326. }
  327. }
  328. bool CrowdNavigation::Raycast(float maxDistance, Vector3& hitPos, Drawable*& hitDrawable)
  329. {
  330. hitDrawable = nullptr;
  331. auto* ui = GetSubsystem<UI>();
  332. IntVector2 pos = ui->GetCursorPosition();
  333. // Check the cursor is visible and there is no UI element in front of the cursor
  334. if (!ui->GetCursor()->IsVisible() || ui->GetElementAt(pos, true))
  335. return false;
  336. auto* graphics = GetSubsystem<Graphics>();
  337. auto* camera = cameraNode_->GetComponent<Camera>();
  338. Ray cameraRay = camera->GetScreenRay((float)pos.x_ / graphics->GetWidth(), (float)pos.y_ / graphics->GetHeight());
  339. // Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  340. PODVector<RayQueryResult> results;
  341. RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
  342. scene_->GetComponent<Octree>()->RaycastSingle(query);
  343. if (results.Size())
  344. {
  345. RayQueryResult& result = results[0];
  346. hitPos = result.position_;
  347. hitDrawable = result.drawable_;
  348. return true;
  349. }
  350. return false;
  351. }
  352. void CrowdNavigation::MoveCamera(float timeStep)
  353. {
  354. // Right mouse button controls mouse cursor visibility: hide when pressed
  355. auto* ui = GetSubsystem<UI>();
  356. auto* input = GetSubsystem<Input>();
  357. ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
  358. // Do not move if the UI has a focused element (the console)
  359. if (ui->GetFocusElement())
  360. return;
  361. // Movement speed as world units per second
  362. const float MOVE_SPEED = 20.0f;
  363. // Mouse sensitivity as degrees per pixel
  364. const float MOUSE_SENSITIVITY = 0.1f;
  365. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  366. // Only move the camera when the cursor is hidden
  367. if (!ui->GetCursor()->IsVisible())
  368. {
  369. IntVector2 mouseMove = input->GetMouseMove();
  370. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  371. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  372. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  373. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  374. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  375. }
  376. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  377. if (input->GetKeyDown(KEY_W))
  378. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  379. if (input->GetKeyDown(KEY_S))
  380. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  381. if (input->GetKeyDown(KEY_A))
  382. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  383. if (input->GetKeyDown(KEY_D))
  384. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  385. // Set destination or spawn a new jack with left mouse button
  386. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  387. SetPathPoint(input->GetQualifierDown(QUAL_SHIFT));
  388. // Add new obstacle or remove existing obstacle/agent with middle mouse button
  389. else if (input->GetMouseButtonPress(MOUSEB_MIDDLE) || input->GetKeyPress(KEY_O))
  390. AddOrRemoveObject();
  391. // Check for loading/saving the scene from/to the file Data/Scenes/CrowdNavigation.xml relative to the executable directory
  392. if (input->GetKeyPress(KEY_F5))
  393. {
  394. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CrowdNavigation.xml", FILE_WRITE);
  395. scene_->SaveXML(saveFile);
  396. }
  397. else if (input->GetKeyPress(KEY_F7))
  398. {
  399. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/CrowdNavigation.xml", FILE_READ);
  400. scene_->LoadXML(loadFile);
  401. }
  402. // Toggle debug geometry with space
  403. else if (input->GetKeyPress(KEY_SPACE))
  404. drawDebug_ = !drawDebug_;
  405. // Toggle instruction text with F12
  406. else if (input->GetKeyPress(KEY_F12))
  407. {
  408. UIElement* instruction = ui->GetRoot()->GetChild(INSTRUCTION);
  409. instruction->SetVisible(!instruction->IsVisible());
  410. }
  411. }
  412. void CrowdNavigation::ToggleStreaming(bool enabled)
  413. {
  414. auto* navMesh = scene_->GetComponent<DynamicNavigationMesh>();
  415. if (enabled)
  416. {
  417. int maxTiles = (2 * streamingDistance_ + 1) * (2 * streamingDistance_ + 1);
  418. BoundingBox boundingBox = navMesh->GetBoundingBox();
  419. SaveNavigationData();
  420. navMesh->Allocate(boundingBox, maxTiles);
  421. }
  422. else
  423. navMesh->Build();
  424. }
  425. void CrowdNavigation::UpdateStreaming()
  426. {
  427. // Center the navigation mesh at the crowd of jacks
  428. Vector3 averageJackPosition;
  429. if (Node* jackGroup = scene_->GetChild("Jacks"))
  430. {
  431. const unsigned numJacks = jackGroup->GetNumChildren();
  432. for (unsigned i = 0; i < numJacks; ++i)
  433. averageJackPosition += jackGroup->GetChild(i)->GetWorldPosition();
  434. averageJackPosition /= (float)numJacks;
  435. }
  436. // Compute currently loaded area
  437. auto* navMesh = scene_->GetComponent<DynamicNavigationMesh>();
  438. const IntVector2 jackTile = navMesh->GetTileIndex(averageJackPosition);
  439. const IntVector2 numTiles = navMesh->GetNumTiles();
  440. const IntVector2 beginTile = VectorMax(IntVector2::ZERO, jackTile - IntVector2::ONE * streamingDistance_);
  441. const IntVector2 endTile = VectorMin(jackTile + IntVector2::ONE * streamingDistance_, numTiles - IntVector2::ONE);
  442. // Remove tiles
  443. for (HashSet<IntVector2>::Iterator i = addedTiles_.Begin(); i != addedTiles_.End();)
  444. {
  445. const IntVector2 tileIdx = *i;
  446. if (beginTile.x_ <= tileIdx.x_ && tileIdx.x_ <= endTile.x_ && beginTile.y_ <= tileIdx.y_ && tileIdx.y_ <= endTile.y_)
  447. ++i;
  448. else
  449. {
  450. navMesh->RemoveTile(tileIdx);
  451. i = addedTiles_.Erase(i);
  452. }
  453. }
  454. // Add tiles
  455. for (int z = beginTile.y_; z <= endTile.y_; ++z)
  456. for (int x = beginTile.x_; x <= endTile.x_; ++x)
  457. {
  458. const IntVector2 tileIdx(x, z);
  459. if (!navMesh->HasTile(tileIdx) && tileData_.Contains(tileIdx))
  460. {
  461. addedTiles_.Insert(tileIdx);
  462. navMesh->AddTile(tileData_[tileIdx]);
  463. }
  464. }
  465. }
  466. void CrowdNavigation::SaveNavigationData()
  467. {
  468. auto* navMesh = scene_->GetComponent<DynamicNavigationMesh>();
  469. tileData_.Clear();
  470. addedTiles_.Clear();
  471. const IntVector2 numTiles = navMesh->GetNumTiles();
  472. for (int z = 0; z < numTiles.y_; ++z)
  473. for (int x = 0; x <= numTiles.x_; ++x)
  474. {
  475. const IntVector2 tileIdx = IntVector2(x, z);
  476. tileData_[tileIdx] = navMesh->GetTileData(tileIdx);
  477. }
  478. }
  479. void CrowdNavigation::HandleUpdate(StringHash eventType, VariantMap& eventData)
  480. {
  481. using namespace Update;
  482. // Take the frame time step, which is stored as a float
  483. float timeStep = eventData[P_TIMESTEP].GetFloat();
  484. // Move the camera, scale movement with time step
  485. MoveCamera(timeStep);
  486. // Update streaming
  487. auto* input = GetSubsystem<Input>();
  488. if (input->GetKeyPress(KEY_TAB))
  489. {
  490. useStreaming_ = !useStreaming_;
  491. ToggleStreaming(useStreaming_);
  492. }
  493. if (useStreaming_)
  494. UpdateStreaming();
  495. }
  496. void CrowdNavigation::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  497. {
  498. if (drawDebug_)
  499. {
  500. // Visualize navigation mesh, obstacles and off-mesh connections
  501. scene_->GetComponent<DynamicNavigationMesh>()->DrawDebugGeometry(true);
  502. // Visualize agents' path and position to reach
  503. scene_->GetComponent<CrowdManager>()->DrawDebugGeometry(true);
  504. }
  505. }
  506. void CrowdNavigation::HandleCrowdAgentFailure(StringHash eventType, VariantMap& eventData)
  507. {
  508. using namespace CrowdAgentFailure;
  509. auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  510. auto agentState = (CrowdAgentState)eventData[P_CROWD_AGENT_STATE].GetInt();
  511. // If the agent's state is invalid, likely from spawning on the side of a box, find a point in a larger area
  512. if (agentState == CA_STATE_INVALID)
  513. {
  514. // Get a point on the navmesh using more generous extents
  515. Vector3 newPos = scene_->GetComponent<DynamicNavigationMesh>()->FindNearestPoint(node->GetPosition(), Vector3(5.0f, 5.0f, 5.0f));
  516. // Set the new node position, CrowdAgent component will automatically reset the state of the agent
  517. node->SetPosition(newPos);
  518. }
  519. }
  520. void CrowdNavigation::HandleCrowdAgentReposition(StringHash eventType, VariantMap& eventData)
  521. {
  522. static const char* WALKING_ANI = "Models/Jack_Walk.ani";
  523. using namespace CrowdAgentReposition;
  524. auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  525. auto* agent = static_cast<CrowdAgent*>(eventData[P_CROWD_AGENT].GetPtr());
  526. Vector3 velocity = eventData[P_VELOCITY].GetVector3();
  527. float timeStep = eventData[P_TIMESTEP].GetFloat();
  528. // Only Jack agent has animation controller
  529. auto* animCtrl = node->GetComponent<AnimationController>();
  530. if (animCtrl)
  531. {
  532. float speed = velocity.Length();
  533. if (animCtrl->IsPlaying(WALKING_ANI))
  534. {
  535. float speedRatio = speed / agent->GetMaxSpeed();
  536. // Face the direction of its velocity but moderate the turning speed based on the speed ratio and timeStep
  537. node->SetRotation(node->GetRotation().Slerp(Quaternion(Vector3::FORWARD, velocity), 10.0f * timeStep * speedRatio));
  538. // Throttle the animation speed based on agent speed ratio (ratio = 1 is full throttle)
  539. animCtrl->SetSpeed(WALKING_ANI, speedRatio * 1.5f);
  540. }
  541. else
  542. animCtrl->Play(WALKING_ANI, 0, true, 0.1f);
  543. // If speed is too low then stop the animation
  544. if (speed < agent->GetRadius())
  545. animCtrl->Stop(WALKING_ANI, 0.5f);
  546. }
  547. }
  548. void CrowdNavigation::HandleCrowdAgentFormation(StringHash eventType, VariantMap& eventData)
  549. {
  550. using namespace CrowdAgentFormation;
  551. unsigned index = eventData[P_INDEX].GetUInt();
  552. unsigned size = eventData[P_SIZE].GetUInt();
  553. Vector3 position = eventData[P_POSITION].GetVector3();
  554. // The first agent will always move to the exact position, all other agents will select a random point nearby
  555. if (index)
  556. {
  557. auto* crowdManager = static_cast<CrowdManager*>(GetEventSender());
  558. auto* agent = static_cast<CrowdAgent*>(eventData[P_CROWD_AGENT].GetPtr());
  559. eventData[P_POSITION] = crowdManager->GetRandomPointInCircle(position, agent->GetRadius(), agent->GetQueryFilterType());
  560. }
  561. }