CrowdManager.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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 "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/Log.h"
  27. #include "../Navigation/CrowdAgent.h"
  28. #include "../Navigation/CrowdManager.h"
  29. #include "../Navigation/DynamicNavigationMesh.h"
  30. #include "../Navigation/NavigationEvents.h"
  31. #include "../Scene/Node.h"
  32. #include "../Scene/Scene.h"
  33. #include "../Scene/SceneEvents.h"
  34. // ATOMIC BEGIN
  35. #include <DetourCrowd/include/DetourCrowd.h>
  36. // ATOMIC END
  37. #include "../DebugNew.h"
  38. namespace Atomic
  39. {
  40. extern const char* NAVIGATION_CATEGORY;
  41. static const unsigned DEFAULT_MAX_AGENTS = 512;
  42. static const float DEFAULT_MAX_AGENT_RADIUS = 0.f;
  43. const char* filterTypesStructureElementNames[] =
  44. {
  45. "Query Filter Type Count",
  46. " Include Flags",
  47. " Exclude Flags",
  48. " >AreaCost",
  49. 0
  50. };
  51. const char* obstacleAvoidanceTypesStructureElementNames[] =
  52. {
  53. "Obstacle Avoid. Type Count",
  54. " Velocity Bias",
  55. " Desired Velocity Weight",
  56. " Current Velocity Weight",
  57. " Side Bias Weight",
  58. " Time of Impact Weight",
  59. " Time Horizon",
  60. " Grid Size",
  61. " Adaptive Divs",
  62. " Adaptive Rings",
  63. " Adaptive Depth",
  64. 0
  65. };
  66. void CrowdAgentUpdateCallback(dtCrowdAgent* ag, float dt)
  67. {
  68. static_cast<CrowdAgent*>(ag->params.userData)->OnCrowdUpdate(ag, dt);
  69. }
  70. CrowdManager::CrowdManager(Context* context) :
  71. Component(context),
  72. crowd_(0),
  73. navigationMeshId_(0),
  74. maxAgents_(DEFAULT_MAX_AGENTS),
  75. maxAgentRadius_(DEFAULT_MAX_AGENT_RADIUS),
  76. numQueryFilterTypes_(0),
  77. numObstacleAvoidanceTypes_(0)
  78. {
  79. // The actual buffer is allocated inside dtCrowd, we only track the number of "slots" being configured explicitly
  80. numAreas_.Reserve(DT_CROWD_MAX_QUERY_FILTER_TYPE);
  81. for (unsigned i = 0; i < DT_CROWD_MAX_QUERY_FILTER_TYPE; ++i)
  82. numAreas_.Push(0);
  83. }
  84. CrowdManager::~CrowdManager()
  85. {
  86. dtFreeCrowd(crowd_);
  87. crowd_ = 0;
  88. }
  89. void CrowdManager::RegisterObject(Context* context)
  90. {
  91. context->RegisterFactory<CrowdManager>(NAVIGATION_CATEGORY);
  92. ATOMIC_ATTRIBUTE("Max Agents", unsigned, maxAgents_, DEFAULT_MAX_AGENTS, AM_DEFAULT);
  93. ATOMIC_ATTRIBUTE("Max Agent Radius", float, maxAgentRadius_, DEFAULT_MAX_AGENT_RADIUS, AM_DEFAULT);
  94. ATOMIC_ATTRIBUTE("Navigation Mesh", unsigned, navigationMeshId_, 0, AM_DEFAULT | AM_COMPONENTID);
  95. ATOMIC_MIXED_ACCESSOR_VARIANT_VECTOR_STRUCTURE_ATTRIBUTE("Filter Types", GetQueryFilterTypesAttr, SetQueryFilterTypesAttr,
  96. VariantVector, Variant::emptyVariantVector,
  97. filterTypesStructureElementNames, AM_DEFAULT);
  98. ATOMIC_MIXED_ACCESSOR_VARIANT_VECTOR_STRUCTURE_ATTRIBUTE("Obstacle Avoidance Types", GetObstacleAvoidanceTypesAttr, SetObstacleAvoidanceTypesAttr,
  99. VariantVector, Variant::emptyVariantVector,
  100. obstacleAvoidanceTypesStructureElementNames, AM_DEFAULT);
  101. }
  102. void CrowdManager::ApplyAttributes()
  103. {
  104. // Values from Editor, saved-file, or network must be checked before applying
  105. maxAgents_ = Max(1U, maxAgents_);
  106. maxAgentRadius_ = Max(0.f, maxAgentRadius_);
  107. bool navMeshChange = false;
  108. Scene* scene = GetScene();
  109. if (scene && navigationMeshId_)
  110. {
  111. NavigationMesh* navMesh = dynamic_cast<NavigationMesh*>(scene->GetComponent(navigationMeshId_));
  112. if (navMesh && navMesh != navigationMesh_)
  113. {
  114. SetNavigationMesh(navMesh); // This will also CreateCrowd(), so the rest of the function is unnecessary
  115. return;
  116. }
  117. }
  118. // In case of receiving an invalid component id, revert it back to the existing navmesh component id (if any)
  119. navigationMeshId_ = navigationMesh_ ? navigationMesh_->GetID() : 0;
  120. // If the Detour crowd initialization parameters have changed then recreate it
  121. if (crowd_ && (navMeshChange || crowd_->getAgentCount() != maxAgents_ || crowd_->getMaxAgentRadius() != maxAgentRadius_))
  122. CreateCrowd();
  123. }
  124. void CrowdManager::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  125. {
  126. if (debug && crowd_)
  127. {
  128. // Current position-to-target line
  129. for (int i = 0; i < crowd_->getAgentCount(); i++)
  130. {
  131. const dtCrowdAgent* ag = crowd_->getAgent(i);
  132. if (!ag->active)
  133. continue;
  134. // Draw CrowdAgent shape (from its radius & height)
  135. CrowdAgent* crowdAgent = static_cast<CrowdAgent*>(ag->params.userData);
  136. crowdAgent->DrawDebugGeometry(debug, depthTest);
  137. // Draw move target if any
  138. if (crowdAgent->GetTargetState() == CA_TARGET_NONE || crowdAgent->GetTargetState() == CA_TARGET_VELOCITY)
  139. continue;
  140. Color color(0.6f, 0.2f, 0.2f, 1.0f);
  141. // Draw line to target
  142. Vector3 pos1(ag->npos[0], ag->npos[1], ag->npos[2]);
  143. Vector3 pos2;
  144. for (int i = 0; i < ag->ncorners; ++i)
  145. {
  146. pos2.x_ = ag->cornerVerts[i * 3];
  147. pos2.y_ = ag->cornerVerts[i * 3 + 1];
  148. pos2.z_ = ag->cornerVerts[i * 3 + 2];
  149. debug->AddLine(pos1, pos2, color, depthTest);
  150. pos1 = pos2;
  151. }
  152. pos2.x_ = ag->targetPos[0];
  153. pos2.y_ = ag->targetPos[1];
  154. pos2.z_ = ag->targetPos[2];
  155. debug->AddLine(pos1, pos2, color, depthTest);
  156. // Draw target circle
  157. debug->AddSphere(Sphere(pos2, 0.5f), color, depthTest);
  158. }
  159. }
  160. }
  161. void CrowdManager::DrawDebugGeometry(bool depthTest)
  162. {
  163. Scene* scene = GetScene();
  164. if (scene)
  165. {
  166. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  167. if (debug)
  168. DrawDebugGeometry(debug, depthTest);
  169. }
  170. }
  171. void CrowdManager::SetCrowdTarget(const Vector3& position, Node* node)
  172. {
  173. if (!crowd_)
  174. return;
  175. PODVector<CrowdAgent*> agents = GetAgents(node, false); // Get all crowd agent components
  176. Vector3 moveTarget(position);
  177. for (unsigned i = 0; i < agents.Size(); ++i)
  178. {
  179. // Give application a chance to determine the desired crowd formation when they reach the target position
  180. CrowdAgent* agent = agents[i];
  181. using namespace CrowdAgentFormation;
  182. VariantMap& map = GetEventDataMap();
  183. map[P_NODE] = agent->GetNode();
  184. map[P_CROWD_AGENT] = agent;
  185. map[P_INDEX] = i;
  186. map[P_SIZE] = agents.Size();
  187. map[P_POSITION] = moveTarget; // Expect the event handler will modify this position accordingly
  188. SendEvent(E_CROWD_AGENT_FORMATION, map);
  189. moveTarget = map[P_POSITION].GetVector3();
  190. agent->SetTargetPosition(moveTarget);
  191. }
  192. }
  193. void CrowdManager::SetCrowdVelocity(const Vector3& velocity, Node* node)
  194. {
  195. if (!crowd_)
  196. return;
  197. PODVector<CrowdAgent*> agents = GetAgents(node, true); // Get only crowd agent components already in the crowd
  198. for (unsigned i = 0; i < agents.Size(); ++i)
  199. agents[i]->SetTargetVelocity(velocity);
  200. }
  201. void CrowdManager::ResetCrowdTarget(Node* node)
  202. {
  203. if (!crowd_)
  204. return;
  205. PODVector<CrowdAgent*> agents = GetAgents(node, true);
  206. for (unsigned i = 0; i < agents.Size(); ++i)
  207. agents[i]->ResetTarget();
  208. }
  209. void CrowdManager::SetMaxAgents(unsigned maxAgents)
  210. {
  211. if (maxAgents != maxAgents_ && maxAgents > 0)
  212. {
  213. maxAgents_ = maxAgents;
  214. CreateCrowd();
  215. MarkNetworkUpdate();
  216. }
  217. }
  218. void CrowdManager::SetMaxAgentRadius(float maxAgentRadius)
  219. {
  220. if (maxAgentRadius != maxAgentRadius_ && maxAgentRadius > 0.f)
  221. {
  222. maxAgentRadius_ = maxAgentRadius;
  223. CreateCrowd();
  224. MarkNetworkUpdate();
  225. }
  226. }
  227. void CrowdManager::SetNavigationMesh(NavigationMesh* navMesh)
  228. {
  229. UnsubscribeFromEvent(E_COMPONENTADDED);
  230. UnsubscribeFromEvent(E_NAVIGATION_MESH_REBUILT);
  231. UnsubscribeFromEvent(E_COMPONENTREMOVED);
  232. if (navMesh != navigationMesh_) // It is possible to reset navmesh pointer back to 0
  233. {
  234. Scene* scene = GetScene();
  235. navigationMesh_ = navMesh;
  236. navigationMeshId_ = navMesh ? navMesh->GetID() : 0;
  237. if (navMesh)
  238. {
  239. SubscribeToEvent(navMesh, E_NAVIGATION_MESH_REBUILT, ATOMIC_HANDLER(CrowdManager, HandleNavMeshChanged));
  240. SubscribeToEvent(scene, E_COMPONENTREMOVED, ATOMIC_HANDLER(CrowdManager, HandleNavMeshChanged));
  241. }
  242. CreateCrowd();
  243. MarkNetworkUpdate();
  244. }
  245. }
  246. void CrowdManager::SetQueryFilterTypesAttr(const VariantVector& value)
  247. {
  248. if (!crowd_)
  249. return;
  250. unsigned index = 0;
  251. unsigned queryFilterType = 0;
  252. numQueryFilterTypes_ = index < value.Size() ? Min(value[index++].GetUInt(), (unsigned)DT_CROWD_MAX_QUERY_FILTER_TYPE) : 0;
  253. while (queryFilterType < numQueryFilterTypes_)
  254. {
  255. if (index + 3 <= value.Size())
  256. {
  257. dtQueryFilter* filter = crowd_->getEditableFilter(queryFilterType);
  258. assert(filter);
  259. filter->setIncludeFlags((unsigned short)value[index++].GetUInt());
  260. filter->setExcludeFlags((unsigned short)value[index++].GetUInt());
  261. unsigned prevNumAreas = numAreas_[queryFilterType];
  262. numAreas_[queryFilterType] = Min(value[index++].GetUInt(), (unsigned)DT_MAX_AREAS);
  263. // Must loop through based on previous number of areas, the new area cost (if any) can only be set in the next attribute get/set iteration
  264. if (index + prevNumAreas <= value.Size())
  265. {
  266. for (unsigned i = 0; i < prevNumAreas; ++i)
  267. filter->setAreaCost(i, value[index++].GetFloat());
  268. }
  269. }
  270. ++queryFilterType;
  271. }
  272. }
  273. void CrowdManager::SetIncludeFlags(unsigned queryFilterType, unsigned short flags)
  274. {
  275. dtQueryFilter* filter = const_cast<dtQueryFilter*>(GetDetourQueryFilter(queryFilterType));
  276. if (filter)
  277. {
  278. filter->setIncludeFlags(flags);
  279. if (numQueryFilterTypes_ < queryFilterType + 1)
  280. numQueryFilterTypes_ = queryFilterType + 1;
  281. MarkNetworkUpdate();
  282. }
  283. }
  284. void CrowdManager::SetExcludeFlags(unsigned queryFilterType, unsigned short flags)
  285. {
  286. dtQueryFilter* filter = const_cast<dtQueryFilter*>(GetDetourQueryFilter(queryFilterType));
  287. if (filter)
  288. {
  289. filter->setExcludeFlags(flags);
  290. if (numQueryFilterTypes_ < queryFilterType + 1)
  291. numQueryFilterTypes_ = queryFilterType + 1;
  292. MarkNetworkUpdate();
  293. }
  294. }
  295. void CrowdManager::SetAreaCost(unsigned queryFilterType, unsigned areaID, float cost)
  296. {
  297. dtQueryFilter* filter = const_cast<dtQueryFilter*>(GetDetourQueryFilter(queryFilterType));
  298. if (filter && areaID < DT_MAX_AREAS)
  299. {
  300. filter->setAreaCost((int)areaID, cost);
  301. if (numQueryFilterTypes_ < queryFilterType + 1)
  302. numQueryFilterTypes_ = queryFilterType + 1;
  303. if (numAreas_[queryFilterType] < areaID + 1)
  304. numAreas_[queryFilterType] = areaID + 1;
  305. MarkNetworkUpdate();
  306. }
  307. }
  308. void CrowdManager::SetObstacleAvoidanceTypesAttr(const VariantVector& value)
  309. {
  310. if (!crowd_)
  311. return;
  312. unsigned index = 0;
  313. unsigned obstacleAvoidanceType = 0;
  314. numObstacleAvoidanceTypes_ = index < value.Size() ? Min(value[index++].GetUInt(), (unsigned)DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS) : 0;
  315. while (obstacleAvoidanceType < numObstacleAvoidanceTypes_)
  316. {
  317. if (index + 10 <= value.Size())
  318. {
  319. dtObstacleAvoidanceParams params;
  320. params.velBias = value[index++].GetFloat();
  321. params.weightDesVel = value[index++].GetFloat();
  322. params.weightCurVel = value[index++].GetFloat();
  323. params.weightSide = value[index++].GetFloat();
  324. params.weightToi = value[index++].GetFloat();
  325. params.horizTime = value[index++].GetFloat();
  326. params.gridSize = (unsigned char)value[index++].GetUInt();
  327. params.adaptiveDivs = (unsigned char)value[index++].GetUInt();
  328. params.adaptiveRings = (unsigned char)value[index++].GetUInt();
  329. params.adaptiveDepth = (unsigned char)value[index++].GetUInt();
  330. crowd_->setObstacleAvoidanceParams(obstacleAvoidanceType, &params);
  331. }
  332. ++obstacleAvoidanceType;
  333. }
  334. }
  335. void CrowdManager::SetObstacleAvoidanceParams(unsigned obstacleAvoidanceType, const CrowdObstacleAvoidanceParams& params)
  336. {
  337. if (crowd_ && obstacleAvoidanceType < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS)
  338. {
  339. crowd_->setObstacleAvoidanceParams(obstacleAvoidanceType, reinterpret_cast<const dtObstacleAvoidanceParams*>(&params));
  340. if (numObstacleAvoidanceTypes_ < obstacleAvoidanceType + 1)
  341. numObstacleAvoidanceTypes_ = obstacleAvoidanceType + 1;
  342. MarkNetworkUpdate();
  343. }
  344. }
  345. Vector3 CrowdManager::FindNearestPoint(const Vector3& point, int queryFilterType, dtPolyRef* nearestRef)
  346. {
  347. if (nearestRef)
  348. *nearestRef = 0;
  349. return crowd_ && navigationMesh_ ?
  350. navigationMesh_->FindNearestPoint(point, Vector3(crowd_->getQueryExtents()), crowd_->getFilter(queryFilterType), nearestRef) : point;
  351. }
  352. Vector3 CrowdManager::MoveAlongSurface(const Vector3& start, const Vector3& end, int queryFilterType, int maxVisited)
  353. {
  354. return crowd_ && navigationMesh_ ?
  355. navigationMesh_->MoveAlongSurface(start, end, Vector3(crowd_->getQueryExtents()), maxVisited, crowd_->getFilter(queryFilterType)) :
  356. end;
  357. }
  358. void CrowdManager::FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, int queryFilterType)
  359. {
  360. if (crowd_ && navigationMesh_)
  361. navigationMesh_->FindPath(dest, start, end, Vector3(crowd_->getQueryExtents()), crowd_->getFilter(queryFilterType));
  362. }
  363. Vector3 CrowdManager::GetRandomPoint(int queryFilterType, dtPolyRef* randomRef)
  364. {
  365. if (randomRef)
  366. *randomRef = 0;
  367. return crowd_ && navigationMesh_ ? navigationMesh_->GetRandomPoint(crowd_->getFilter(queryFilterType), randomRef) :
  368. Vector3::ZERO;
  369. }
  370. Vector3 CrowdManager::GetRandomPointInCircle(const Vector3& center, float radius, int queryFilterType, dtPolyRef* randomRef)
  371. {
  372. if (randomRef)
  373. *randomRef = 0;
  374. return crowd_ && navigationMesh_ ?
  375. navigationMesh_->GetRandomPointInCircle(center, radius, Vector3(crowd_->getQueryExtents()),
  376. crowd_->getFilter(queryFilterType), randomRef) : center;
  377. }
  378. float CrowdManager::GetDistanceToWall(const Vector3& point, float radius, int queryFilterType, Vector3* hitPos, Vector3* hitNormal)
  379. {
  380. if (hitPos)
  381. *hitPos = Vector3::ZERO;
  382. if (hitNormal)
  383. *hitNormal = Vector3::DOWN;
  384. return crowd_ && navigationMesh_ ?
  385. navigationMesh_->GetDistanceToWall(point, radius, Vector3(crowd_->getQueryExtents()), crowd_->getFilter(queryFilterType),
  386. hitPos, hitNormal) : radius;
  387. }
  388. Vector3 CrowdManager::Raycast(const Vector3& start, const Vector3& end, int queryFilterType, Vector3* hitNormal)
  389. {
  390. if (hitNormal)
  391. *hitNormal = Vector3::DOWN;
  392. return crowd_ && navigationMesh_ ?
  393. navigationMesh_->Raycast(start, end, Vector3(crowd_->getQueryExtents()), crowd_->getFilter(queryFilterType), hitNormal)
  394. : end;
  395. }
  396. unsigned CrowdManager::GetNumAreas(unsigned queryFilterType) const
  397. {
  398. return queryFilterType < numQueryFilterTypes_ ? numAreas_[queryFilterType] : 0;
  399. }
  400. VariantVector CrowdManager::GetQueryFilterTypesAttr() const
  401. {
  402. VariantVector ret;
  403. if (crowd_)
  404. {
  405. unsigned totalNumAreas = 0;
  406. for (unsigned i = 0; i < numQueryFilterTypes_; ++i)
  407. totalNumAreas += numAreas_[i];
  408. ret.Reserve(numQueryFilterTypes_ * 3 + totalNumAreas + 1);
  409. ret.Push(numQueryFilterTypes_);
  410. for (unsigned i = 0; i < numQueryFilterTypes_; ++i)
  411. {
  412. const dtQueryFilter* filter = crowd_->getFilter(i);
  413. assert(filter);
  414. ret.Push(filter->getIncludeFlags());
  415. ret.Push(filter->getExcludeFlags());
  416. ret.Push(numAreas_[i]);
  417. for (unsigned j = 0; j < numAreas_[i]; ++j)
  418. ret.Push(filter->getAreaCost(j));
  419. }
  420. }
  421. else
  422. ret.Push(0);
  423. return ret;
  424. }
  425. unsigned short CrowdManager::GetIncludeFlags(unsigned queryFilterType) const
  426. {
  427. if (queryFilterType >= numQueryFilterTypes_)
  428. ATOMIC_LOGWARNINGF("Query filter type %d is not configured yet, returning the default include flags initialized by dtCrowd",
  429. queryFilterType);
  430. const dtQueryFilter* filter = GetDetourQueryFilter(queryFilterType);
  431. return (unsigned short)(filter ? filter->getIncludeFlags() : 0xffff);
  432. }
  433. unsigned short CrowdManager::GetExcludeFlags(unsigned queryFilterType) const
  434. {
  435. if (queryFilterType >= numQueryFilterTypes_)
  436. ATOMIC_LOGWARNINGF("Query filter type %d is not configured yet, returning the default exclude flags initialized by dtCrowd",
  437. queryFilterType);
  438. const dtQueryFilter* filter = GetDetourQueryFilter(queryFilterType);
  439. return (unsigned short)(filter ? filter->getExcludeFlags() : 0);
  440. }
  441. float CrowdManager::GetAreaCost(unsigned queryFilterType, unsigned areaID) const
  442. {
  443. if (queryFilterType >= numQueryFilterTypes_ || areaID >= numAreas_[queryFilterType])
  444. ATOMIC_LOGWARNINGF(
  445. "Query filter type %d and/or area id %d are not configured yet, returning the default area cost initialized by dtCrowd",
  446. queryFilterType, areaID);
  447. const dtQueryFilter* filter = GetDetourQueryFilter(queryFilterType);
  448. return filter ? filter->getAreaCost((int)areaID) : 1.f;
  449. }
  450. VariantVector CrowdManager::GetObstacleAvoidanceTypesAttr() const
  451. {
  452. VariantVector ret;
  453. if (crowd_)
  454. {
  455. ret.Reserve(numObstacleAvoidanceTypes_ * 10 + 1);
  456. ret.Push(numObstacleAvoidanceTypes_);
  457. for (unsigned i = 0; i < numObstacleAvoidanceTypes_; ++i)
  458. {
  459. const dtObstacleAvoidanceParams* params = crowd_->getObstacleAvoidanceParams(i);
  460. assert(params);
  461. ret.Push(params->velBias);
  462. ret.Push(params->weightDesVel);
  463. ret.Push(params->weightCurVel);
  464. ret.Push(params->weightSide);
  465. ret.Push(params->weightToi);
  466. ret.Push(params->horizTime);
  467. ret.Push(params->gridSize);
  468. ret.Push(params->adaptiveDivs);
  469. ret.Push(params->adaptiveRings);
  470. ret.Push(params->adaptiveDepth);
  471. }
  472. }
  473. else
  474. ret.Push(0);
  475. return ret;
  476. }
  477. const CrowdObstacleAvoidanceParams& CrowdManager::GetObstacleAvoidanceParams(unsigned obstacleAvoidanceType) const
  478. {
  479. static const CrowdObstacleAvoidanceParams EMPTY_PARAMS = CrowdObstacleAvoidanceParams();
  480. const dtObstacleAvoidanceParams* params = crowd_ ? crowd_->getObstacleAvoidanceParams(obstacleAvoidanceType) : 0;
  481. return params ? *reinterpret_cast<const CrowdObstacleAvoidanceParams*>(params) : EMPTY_PARAMS;
  482. }
  483. PODVector<CrowdAgent*> CrowdManager::GetAgents(Node* node, bool inCrowdFilter) const
  484. {
  485. if (!node)
  486. node = GetScene();
  487. PODVector<CrowdAgent*> agents;
  488. node->GetComponents<CrowdAgent>(agents, true);
  489. if (inCrowdFilter)
  490. {
  491. PODVector<CrowdAgent*>::Iterator i = agents.Begin();
  492. while (i != agents.End())
  493. {
  494. if ((*i)->IsInCrowd())
  495. ++i;
  496. else
  497. i = agents.Erase(i);
  498. }
  499. }
  500. return agents;
  501. }
  502. bool CrowdManager::CreateCrowd()
  503. {
  504. if (!navigationMesh_ || !navigationMesh_->InitializeQuery())
  505. return false;
  506. // Preserve the existing crowd configuration before recreating it
  507. VariantVector queryFilterTypeConfiguration, obstacleAvoidanceTypeConfiguration;
  508. bool recreate = crowd_ != 0;
  509. if (recreate)
  510. {
  511. queryFilterTypeConfiguration = GetQueryFilterTypesAttr();
  512. obstacleAvoidanceTypeConfiguration = GetObstacleAvoidanceTypesAttr();
  513. dtFreeCrowd(crowd_);
  514. }
  515. crowd_ = dtAllocCrowd();
  516. // Initialize the crowd
  517. if (maxAgentRadius_ == 0.f)
  518. maxAgentRadius_ = navigationMesh_->GetAgentRadius();
  519. if (!crowd_->init(maxAgents_, maxAgentRadius_, navigationMesh_->navMesh_, CrowdAgentUpdateCallback))
  520. {
  521. ATOMIC_LOGERROR("Could not initialize DetourCrowd");
  522. return false;
  523. }
  524. if (recreate)
  525. {
  526. // Reconfigure the newly initialized crowd
  527. SetQueryFilterTypesAttr(queryFilterTypeConfiguration);
  528. SetObstacleAvoidanceTypesAttr(obstacleAvoidanceTypeConfiguration);
  529. // Re-add the existing crowd agents
  530. PODVector<CrowdAgent*> agents = GetAgents();
  531. for (unsigned i = 0; i < agents.Size(); ++i)
  532. {
  533. // Keep adding until the crowd cannot take it anymore
  534. if (agents[i]->AddAgentToCrowd(true) == -1)
  535. {
  536. ATOMIC_LOGWARNINGF("CrowdManager: %d crowd agents orphaned", agents.Size() - i);
  537. break;
  538. }
  539. }
  540. }
  541. return true;
  542. }
  543. int CrowdManager::AddAgent(CrowdAgent* agent, const Vector3& pos)
  544. {
  545. if (!crowd_ || !navigationMesh_ || !agent)
  546. return -1;
  547. dtCrowdAgentParams params;
  548. params.userData = agent;
  549. if (agent->radius_ == 0.f)
  550. agent->radius_ = navigationMesh_->GetAgentRadius();
  551. if (agent->height_ == 0.f)
  552. agent->height_ = navigationMesh_->GetAgentHeight();
  553. // dtCrowd::addAgent() requires the query filter type to find the nearest position on navmesh as the initial agent's position
  554. params.queryFilterType = (unsigned char)agent->GetQueryFilterType();
  555. return crowd_->addAgent(pos.Data(), &params);
  556. }
  557. void CrowdManager::RemoveAgent(CrowdAgent* agent)
  558. {
  559. if (!crowd_ || !agent)
  560. return;
  561. dtCrowdAgent* agt = crowd_->getEditableAgent(agent->GetAgentCrowdId());
  562. if (agt)
  563. agt->params.userData = 0;
  564. crowd_->removeAgent(agent->GetAgentCrowdId());
  565. }
  566. void CrowdManager::OnSceneSet(Scene* scene)
  567. {
  568. // Subscribe to the scene subsystem update, which will trigger the crowd update step, and grab a reference
  569. // to the scene's NavigationMesh
  570. if (scene)
  571. {
  572. if (scene != node_)
  573. {
  574. ATOMIC_LOGERROR("CrowdManager is a scene component and should only be attached to the scene node");
  575. return;
  576. }
  577. SubscribeToEvent(scene, E_SCENESUBSYSTEMUPDATE, ATOMIC_HANDLER(CrowdManager, HandleSceneSubsystemUpdate));
  578. // Attempt to auto discover a NavigationMesh component (or its derivative) under the scene node
  579. if (navigationMeshId_ == 0)
  580. {
  581. NavigationMesh* navMesh = scene->GetDerivedComponent<NavigationMesh>(true);
  582. if (navMesh)
  583. SetNavigationMesh(navMesh);
  584. else
  585. {
  586. // If not found, attempt to find in a delayed manner
  587. SubscribeToEvent(scene, E_COMPONENTADDED, ATOMIC_HANDLER(CrowdManager, HandleComponentAdded));
  588. }
  589. }
  590. }
  591. else
  592. {
  593. UnsubscribeFromEvent(E_SCENESUBSYSTEMUPDATE);
  594. UnsubscribeFromEvent(E_NAVIGATION_MESH_REBUILT);
  595. UnsubscribeFromEvent(E_COMPONENTADDED);
  596. UnsubscribeFromEvent(E_COMPONENTREMOVED);
  597. navigationMesh_ = 0;
  598. }
  599. }
  600. void CrowdManager::Update(float delta)
  601. {
  602. assert(crowd_ && navigationMesh_);
  603. ATOMIC_PROFILE(UpdateCrowd);
  604. crowd_->update(delta, 0);
  605. }
  606. const dtCrowdAgent* CrowdManager::GetDetourCrowdAgent(int agent) const
  607. {
  608. return crowd_ ? crowd_->getAgent(agent) : 0;
  609. }
  610. const dtQueryFilter* CrowdManager::GetDetourQueryFilter(unsigned queryFilterType) const
  611. {
  612. return crowd_ ? crowd_->getFilter(queryFilterType) : 0;
  613. }
  614. void CrowdManager::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  615. {
  616. // Perform update tick as long as the crowd is initialized and the associated navmesh has not been removed
  617. if (crowd_ && navigationMesh_)
  618. {
  619. using namespace SceneSubsystemUpdate;
  620. if (IsEnabledEffective())
  621. Update(eventData[P_TIMESTEP].GetFloat());
  622. }
  623. }
  624. void CrowdManager::HandleNavMeshChanged(StringHash eventType, VariantMap& eventData)
  625. {
  626. NavigationMesh* navMesh;
  627. if (eventType == E_NAVIGATION_MESH_REBUILT)
  628. {
  629. navMesh = static_cast<NavigationMesh*>(eventData[NavigationMeshRebuilt::P_MESH].GetPtr());
  630. // Reset internal pointer so that the same navmesh can be reassigned and the crowd creation be reattempted
  631. if (navMesh == navigationMesh_)
  632. navigationMesh_.Reset();
  633. }
  634. else
  635. {
  636. // eventType == E_COMPONENTREMOVED
  637. navMesh = static_cast<NavigationMesh*>(eventData[ComponentRemoved::P_COMPONENT].GetPtr());
  638. // Only interested in navmesh component being used to initialized the crowd
  639. if (navMesh != navigationMesh_)
  640. return;
  641. // Since this is a component removed event, reset our own navmesh pointer
  642. navMesh = 0;
  643. }
  644. SetNavigationMesh(navMesh);
  645. }
  646. void CrowdManager::HandleComponentAdded(StringHash eventType, VariantMap& eventData)
  647. {
  648. Scene* scene = GetScene();
  649. if (scene)
  650. {
  651. NavigationMesh* navMesh = scene->GetDerivedComponent<NavigationMesh>(true);
  652. if (navMesh)
  653. SetNavigationMesh(navMesh);
  654. }
  655. }
  656. }