CrowdManager.cpp 26 KB

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