CrowdNavigation.cpp 22 KB

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