CrowdAgent.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Context.h"
  5. #include "../Core/Profiler.h"
  6. #include "../Graphics/DebugRenderer.h"
  7. #include "../IO/Log.h"
  8. #include "../IO/MemoryBuffer.h"
  9. #include "../Navigation/NavigationEvents.h"
  10. #include "../Navigation/NavigationMesh.h"
  11. #include "../Navigation/CrowdAgent.h"
  12. #include "../Scene/Node.h"
  13. #include "../Scene/Scene.h"
  14. #include <Detour/DetourCommon.h>
  15. #include <DetourCrowd/DetourCrowd.h>
  16. #include "../DebugNew.h"
  17. namespace Urho3D
  18. {
  19. extern const char* NAVIGATION_CATEGORY;
  20. static const CrowdAgentRequestedTarget DEFAULT_AGENT_REQUEST_TARGET_TYPE = CA_REQUESTEDTARGET_NONE;
  21. static const float DEFAULT_AGENT_MAX_SPEED = 0.f;
  22. static const float DEFAULT_AGENT_MAX_ACCEL = 0.f;
  23. static const unsigned DEFAULT_AGENT_QUERY_FILTER_TYPE = 0;
  24. static const unsigned DEFAULT_AGENT_OBSTACLE_AVOIDANCE_TYPE = 0;
  25. static const NavigationQuality DEFAULT_AGENT_AVOIDANCE_QUALITY = NAVIGATIONQUALITY_HIGH;
  26. static const NavigationPushiness DEFAULT_AGENT_NAVIGATION_PUSHINESS = NAVIGATIONPUSHINESS_MEDIUM;
  27. static const unsigned SCOPE_NAVIGATION_QUALITY_PARAMS = 1;
  28. static const unsigned SCOPE_NAVIGATION_PUSHINESS_PARAMS = 2;
  29. static const unsigned SCOPE_BASE_PARAMS = M_MAX_UNSIGNED & ~SCOPE_NAVIGATION_QUALITY_PARAMS & ~SCOPE_NAVIGATION_PUSHINESS_PARAMS;
  30. static const char* crowdAgentRequestedTargetTypeNames[] = {
  31. "None",
  32. "Position",
  33. "Velocity",
  34. nullptr
  35. };
  36. static const char* crowdAgentAvoidanceQualityNames[] = {
  37. "Low",
  38. "Medium",
  39. "High",
  40. nullptr
  41. };
  42. static const char* crowdAgentPushinessNames[] = {
  43. "Low",
  44. "Medium",
  45. "High",
  46. "None",
  47. nullptr
  48. };
  49. CrowdAgent::CrowdAgent(Context* context) :
  50. Component(context),
  51. agentCrowdId_(-1),
  52. requestedTargetType_(DEFAULT_AGENT_REQUEST_TARGET_TYPE),
  53. updateNodePosition_(true),
  54. maxAccel_(DEFAULT_AGENT_MAX_ACCEL),
  55. maxSpeed_(DEFAULT_AGENT_MAX_SPEED),
  56. radius_(0.0f),
  57. height_(0.0f),
  58. queryFilterType_(DEFAULT_AGENT_QUERY_FILTER_TYPE),
  59. obstacleAvoidanceType_(DEFAULT_AGENT_OBSTACLE_AVOIDANCE_TYPE),
  60. navQuality_(DEFAULT_AGENT_AVOIDANCE_QUALITY),
  61. navPushiness_(DEFAULT_AGENT_NAVIGATION_PUSHINESS),
  62. previousTargetState_(CA_TARGET_NONE),
  63. previousAgentState_(CA_STATE_WALKING),
  64. ignoreTransformChanges_(false)
  65. {
  66. SubscribeToEvent(E_NAVIGATION_TILE_ADDED, URHO3D_HANDLER(CrowdAgent, HandleNavigationTileAdded));
  67. }
  68. CrowdAgent::~CrowdAgent()
  69. {
  70. RemoveAgentFromCrowd();
  71. }
  72. void CrowdAgent::RegisterObject(Context* context)
  73. {
  74. context->RegisterFactory<CrowdAgent>(NAVIGATION_CATEGORY);
  75. URHO3D_ATTRIBUTE("Target Position", targetPosition_, Vector3::ZERO, AM_DEFAULT);
  76. URHO3D_ATTRIBUTE("Target Velocity", targetVelocity_, Vector3::ZERO, AM_DEFAULT);
  77. URHO3D_ENUM_ATTRIBUTE("Requested Target Type", requestedTargetType_, crowdAgentRequestedTargetTypeNames,
  78. DEFAULT_AGENT_REQUEST_TARGET_TYPE, AM_DEFAULT);
  79. URHO3D_ACCESSOR_ATTRIBUTE("Update Node Position", GetUpdateNodePosition, SetUpdateNodePosition, true, AM_DEFAULT);
  80. URHO3D_ATTRIBUTE("Max Accel", maxAccel_, DEFAULT_AGENT_MAX_ACCEL, AM_DEFAULT);
  81. URHO3D_ATTRIBUTE("Max Speed", maxSpeed_, DEFAULT_AGENT_MAX_SPEED, AM_DEFAULT);
  82. URHO3D_ATTRIBUTE("Radius", radius_, 0.0f, AM_DEFAULT);
  83. URHO3D_ATTRIBUTE("Height", height_, 0.0f, AM_DEFAULT);
  84. URHO3D_ATTRIBUTE("Query Filter Type", queryFilterType_, DEFAULT_AGENT_QUERY_FILTER_TYPE, AM_DEFAULT);
  85. URHO3D_ATTRIBUTE("Obstacle Avoidance Type", obstacleAvoidanceType_, DEFAULT_AGENT_OBSTACLE_AVOIDANCE_TYPE, AM_DEFAULT);
  86. URHO3D_ENUM_ATTRIBUTE("Navigation Pushiness", navPushiness_, crowdAgentPushinessNames, DEFAULT_AGENT_NAVIGATION_PUSHINESS, AM_DEFAULT);
  87. URHO3D_ENUM_ATTRIBUTE("Navigation Quality", navQuality_, crowdAgentAvoidanceQualityNames, DEFAULT_AGENT_AVOIDANCE_QUALITY, AM_DEFAULT);
  88. }
  89. void CrowdAgent::ApplyAttributes()
  90. {
  91. // Values from Editor, saved-file, or network must be checked before applying
  92. maxAccel_ = Max(0.f, maxAccel_);
  93. maxSpeed_ = Max(0.f, maxSpeed_);
  94. radius_ = Max(0.f, radius_);
  95. height_ = Max(0.f, height_);
  96. queryFilterType_ = Min(queryFilterType_, (unsigned)DT_CROWD_MAX_QUERY_FILTER_TYPE - 1);
  97. obstacleAvoidanceType_ = Min(obstacleAvoidanceType_, (unsigned)DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS - 1);
  98. UpdateParameters();
  99. // Set or reset target after we have attributes applied to the agent's parameters.
  100. CrowdAgentRequestedTarget requestedTargetType = requestedTargetType_;
  101. if (CA_REQUESTEDTARGET_NONE != requestedTargetType_)
  102. {
  103. // Assign a dummy value such that the value check in the setter method passes
  104. requestedTargetType_ = CA_REQUESTEDTARGET_NONE;
  105. if (requestedTargetType == CA_REQUESTEDTARGET_POSITION)
  106. SetTargetPosition(targetPosition_);
  107. else
  108. SetTargetVelocity(targetVelocity_);
  109. }
  110. else
  111. {
  112. requestedTargetType_ = CA_REQUESTEDTARGET_POSITION;
  113. ResetTarget();
  114. }
  115. }
  116. void CrowdAgent::OnSetEnabled()
  117. {
  118. bool enabled = IsEnabledEffective();
  119. if (enabled && !IsInCrowd())
  120. AddAgentToCrowd();
  121. else if (!enabled && IsInCrowd())
  122. RemoveAgentFromCrowd();
  123. }
  124. void CrowdAgent::DrawDebugGeometry(bool depthTest)
  125. {
  126. Scene* scene = GetScene();
  127. if (scene)
  128. {
  129. auto* debug = scene->GetComponent<DebugRenderer>();
  130. if (debug)
  131. DrawDebugGeometry(debug, depthTest);
  132. }
  133. }
  134. void CrowdAgent::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  135. {
  136. if (node_)
  137. {
  138. const Vector3 pos = GetPosition();
  139. const Vector3 vel = GetActualVelocity();
  140. const Vector3 desiredVel = GetDesiredVelocity();
  141. const Vector3 agentHeightVec(0, height_, 0);
  142. debug->AddLine(pos + 0.5f * agentHeightVec, pos + vel + 0.5f * agentHeightVec, Color::GREEN, depthTest);
  143. debug->AddLine(pos + 0.25f * agentHeightVec, pos + desiredVel + 0.25f * agentHeightVec, Color::RED, depthTest);
  144. debug->AddCylinder(pos, radius_, height_, HasArrived() ? Color::GREEN : Color::WHITE, depthTest);
  145. }
  146. }
  147. void CrowdAgent::UpdateParameters(unsigned scope)
  148. {
  149. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  150. if (agent)
  151. {
  152. dtCrowdAgentParams params = agent->params;
  153. if (scope & SCOPE_NAVIGATION_QUALITY_PARAMS)
  154. {
  155. switch (navQuality_)
  156. {
  157. case NAVIGATIONQUALITY_LOW:
  158. params.updateFlags = 0u
  159. | DT_CROWD_OPTIMIZE_VIS
  160. | DT_CROWD_ANTICIPATE_TURNS;
  161. break;
  162. case NAVIGATIONQUALITY_MEDIUM:
  163. params.updateFlags = 0u
  164. | DT_CROWD_OPTIMIZE_TOPO
  165. | DT_CROWD_OPTIMIZE_VIS
  166. | DT_CROWD_ANTICIPATE_TURNS
  167. | DT_CROWD_SEPARATION;
  168. break;
  169. case NAVIGATIONQUALITY_HIGH:
  170. params.updateFlags = 0u
  171. // Path finding
  172. | DT_CROWD_OPTIMIZE_TOPO
  173. | DT_CROWD_OPTIMIZE_VIS
  174. // Steering
  175. | DT_CROWD_ANTICIPATE_TURNS
  176. | DT_CROWD_SEPARATION
  177. // Velocity planning
  178. | DT_CROWD_OBSTACLE_AVOIDANCE;
  179. break;
  180. }
  181. }
  182. if (scope & SCOPE_NAVIGATION_PUSHINESS_PARAMS)
  183. {
  184. switch (navPushiness_)
  185. {
  186. case NAVIGATIONPUSHINESS_LOW:
  187. params.separationWeight = 4.0f;
  188. params.collisionQueryRange = radius_ * 16.0f;
  189. break;
  190. case NAVIGATIONPUSHINESS_MEDIUM:
  191. params.separationWeight = 2.0f;
  192. params.collisionQueryRange = radius_ * 8.0f;
  193. break;
  194. case NAVIGATIONPUSHINESS_HIGH:
  195. params.separationWeight = 0.5f;
  196. params.collisionQueryRange = radius_ * 1.0f;
  197. break;
  198. case NAVIGATIONPUSHINESS_NONE:
  199. params.separationWeight = 0.0f;
  200. params.collisionQueryRange = radius_ * 1.0f;
  201. break;
  202. }
  203. }
  204. if (scope & SCOPE_BASE_PARAMS)
  205. {
  206. params.radius = radius_;
  207. params.height = height_;
  208. params.maxAcceleration = maxAccel_;
  209. params.maxSpeed = maxSpeed_;
  210. params.pathOptimizationRange = radius_ * 30.0f;
  211. params.queryFilterType = (unsigned char)queryFilterType_;
  212. params.obstacleAvoidanceType = (unsigned char)obstacleAvoidanceType_;
  213. }
  214. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  215. }
  216. }
  217. int CrowdAgent::AddAgentToCrowd(bool force)
  218. {
  219. if (!node_ || !crowdManager_ || !crowdManager_->crowd_)
  220. return -1;
  221. if (force || !IsInCrowd())
  222. {
  223. URHO3D_PROFILE(AddAgentToCrowd);
  224. agentCrowdId_ = crowdManager_->AddAgent(this, node_->GetWorldPosition());
  225. if (agentCrowdId_ == -1)
  226. return -1;
  227. ApplyAttributes();
  228. previousAgentState_ = GetAgentState();
  229. previousTargetState_ = GetTargetState();
  230. // Agent created, but initial state is invalid and needs to be addressed
  231. if (previousAgentState_ == CA_STATE_INVALID)
  232. {
  233. using namespace CrowdAgentFailure;
  234. VariantMap& map = GetEventDataMap();
  235. map[P_NODE] = GetNode();
  236. map[P_CROWD_AGENT] = this;
  237. map[P_CROWD_TARGET_STATE] = previousTargetState_;
  238. map[P_CROWD_AGENT_STATE] = previousAgentState_;
  239. map[P_POSITION] = GetPosition();
  240. map[P_VELOCITY] = GetActualVelocity();
  241. crowdManager_->SendEvent(E_CROWD_AGENT_FAILURE, map);
  242. Node* node = GetNode();
  243. if (node)
  244. node->SendEvent(E_CROWD_AGENT_NODE_FAILURE, map);
  245. // Reevaluate states as handling of event may have resulted in changes
  246. previousAgentState_ = GetAgentState();
  247. previousTargetState_ = GetTargetState();
  248. }
  249. // Save the initial position to prevent CrowdAgentReposition event being triggered unnecessarily
  250. previousPosition_ = GetPosition();
  251. }
  252. return agentCrowdId_;
  253. }
  254. void CrowdAgent::RemoveAgentFromCrowd()
  255. {
  256. if (IsInCrowd())
  257. {
  258. crowdManager_->RemoveAgent(this);
  259. agentCrowdId_ = -1;
  260. }
  261. }
  262. void CrowdAgent::SetTargetPosition(const Vector3& position)
  263. {
  264. if (position != targetPosition_ || CA_REQUESTEDTARGET_POSITION != requestedTargetType_)
  265. {
  266. targetPosition_ = position;
  267. requestedTargetType_ = CA_REQUESTEDTARGET_POSITION;
  268. MarkNetworkUpdate();
  269. if (!IsInCrowd())
  270. AddAgentToCrowd();
  271. if (IsInCrowd()) // Make sure the previous method call is successful
  272. {
  273. dtPolyRef nearestRef;
  274. Vector3 nearestPos = crowdManager_->FindNearestPoint(position, queryFilterType_, &nearestRef);
  275. crowdManager_->GetCrowd()->requestMoveTarget(agentCrowdId_, nearestRef, nearestPos.Data());
  276. }
  277. }
  278. }
  279. void CrowdAgent::SetTargetVelocity(const Vector3& velocity)
  280. {
  281. if (velocity != targetVelocity_ || CA_REQUESTEDTARGET_VELOCITY != requestedTargetType_)
  282. {
  283. targetVelocity_ = velocity;
  284. requestedTargetType_ = CA_REQUESTEDTARGET_VELOCITY;
  285. MarkNetworkUpdate();
  286. if (IsInCrowd())
  287. crowdManager_->GetCrowd()->requestMoveVelocity(agentCrowdId_, velocity.Data());
  288. }
  289. }
  290. void CrowdAgent::ResetTarget()
  291. {
  292. if (CA_REQUESTEDTARGET_NONE != requestedTargetType_)
  293. {
  294. requestedTargetType_ = CA_REQUESTEDTARGET_NONE;
  295. MarkNetworkUpdate();
  296. if (IsInCrowd())
  297. crowdManager_->GetCrowd()->resetMoveTarget(agentCrowdId_);
  298. }
  299. }
  300. void CrowdAgent::SetUpdateNodePosition(bool unodepos)
  301. {
  302. if (unodepos != updateNodePosition_)
  303. {
  304. updateNodePosition_ = unodepos;
  305. MarkNetworkUpdate();
  306. }
  307. }
  308. void CrowdAgent::SetMaxAccel(float maxAccel)
  309. {
  310. if (maxAccel != maxAccel_ && maxAccel >= 0.f)
  311. {
  312. maxAccel_ = maxAccel;
  313. UpdateParameters(SCOPE_BASE_PARAMS);
  314. MarkNetworkUpdate();
  315. }
  316. }
  317. void CrowdAgent::SetMaxSpeed(float maxSpeed)
  318. {
  319. if (maxSpeed != maxSpeed_ && maxSpeed >= 0.f)
  320. {
  321. maxSpeed_ = maxSpeed;
  322. UpdateParameters(SCOPE_BASE_PARAMS);
  323. MarkNetworkUpdate();
  324. }
  325. }
  326. void CrowdAgent::SetRadius(float radius)
  327. {
  328. if (radius != radius_ && radius > 0.f)
  329. {
  330. radius_ = radius;
  331. UpdateParameters(SCOPE_BASE_PARAMS | SCOPE_NAVIGATION_PUSHINESS_PARAMS);
  332. MarkNetworkUpdate();
  333. }
  334. }
  335. void CrowdAgent::SetHeight(float height)
  336. {
  337. if (height != height_ && height > 0.f)
  338. {
  339. height_ = height;
  340. UpdateParameters(SCOPE_BASE_PARAMS);
  341. MarkNetworkUpdate();
  342. }
  343. }
  344. void CrowdAgent::SetQueryFilterType(unsigned queryFilterType)
  345. {
  346. if (queryFilterType != queryFilterType_)
  347. {
  348. if (queryFilterType >= DT_CROWD_MAX_QUERY_FILTER_TYPE)
  349. {
  350. URHO3D_LOGERRORF("The specified filter type index (%d) exceeds the maximum allowed value (%d)", queryFilterType,
  351. DT_CROWD_MAX_QUERY_FILTER_TYPE);
  352. return;
  353. }
  354. queryFilterType_ = queryFilterType;
  355. UpdateParameters(SCOPE_BASE_PARAMS);
  356. MarkNetworkUpdate();
  357. }
  358. }
  359. void CrowdAgent::SetObstacleAvoidanceType(unsigned obstacleAvoidanceType)
  360. {
  361. if (obstacleAvoidanceType != obstacleAvoidanceType_)
  362. {
  363. if (obstacleAvoidanceType >= DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS)
  364. {
  365. URHO3D_LOGERRORF("The specified obstacle avoidance type index (%d) exceeds the maximum allowed value (%d)",
  366. obstacleAvoidanceType, DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS);
  367. return;
  368. }
  369. obstacleAvoidanceType_ = obstacleAvoidanceType;
  370. UpdateParameters(SCOPE_BASE_PARAMS);
  371. MarkNetworkUpdate();
  372. }
  373. }
  374. void CrowdAgent::SetNavigationQuality(NavigationQuality val)
  375. {
  376. if (val != navQuality_)
  377. {
  378. navQuality_ = val;
  379. UpdateParameters(SCOPE_NAVIGATION_QUALITY_PARAMS);
  380. MarkNetworkUpdate();
  381. }
  382. }
  383. void CrowdAgent::SetNavigationPushiness(NavigationPushiness val)
  384. {
  385. if (val != navPushiness_)
  386. {
  387. navPushiness_ = val;
  388. UpdateParameters(SCOPE_NAVIGATION_PUSHINESS_PARAMS);
  389. MarkNetworkUpdate();
  390. }
  391. }
  392. Vector3 CrowdAgent::GetPosition() const
  393. {
  394. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  395. return agent ? Vector3(agent->npos) : node_->GetWorldPosition();
  396. }
  397. Vector3 CrowdAgent::GetDesiredVelocity() const
  398. {
  399. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  400. return agent ? Vector3(agent->dvel) : Vector3::ZERO;
  401. }
  402. Vector3 CrowdAgent::GetActualVelocity() const
  403. {
  404. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  405. return agent ? Vector3(agent->vel) : Vector3::ZERO;
  406. }
  407. CrowdAgentState CrowdAgent::GetAgentState() const
  408. {
  409. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  410. return agent ? (CrowdAgentState)agent->state : CA_STATE_INVALID;
  411. }
  412. CrowdAgentTargetState CrowdAgent::GetTargetState() const
  413. {
  414. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  415. return agent ? (CrowdAgentTargetState)agent->targetState : CA_TARGET_NONE;
  416. }
  417. bool CrowdAgent::HasArrived() const
  418. {
  419. // Is the agent at or near the end of its path and within its own radius of the goal?
  420. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  421. return agent && (!agent->ncorners || (agent->cornerFlags[agent->ncorners - 1] & DT_STRAIGHTPATH_END &&
  422. dtVdist2D(agent->npos, &agent->cornerVerts[(agent->ncorners - 1) * 3]) <=
  423. agent->params.radius));
  424. }
  425. bool CrowdAgent::IsInCrowd() const
  426. {
  427. return crowdManager_ && agentCrowdId_ != -1;
  428. }
  429. void CrowdAgent::OnCrowdUpdate(dtCrowdAgent* ag, float dt)
  430. {
  431. assert (ag);
  432. if (node_)
  433. {
  434. // Use pointer to self to check for destruction after sending events
  435. WeakPtr<CrowdAgent> self(this);
  436. Vector3 newPos(ag->npos);
  437. Vector3 newVel(ag->vel);
  438. // Notify parent node of the reposition
  439. if (newPos != previousPosition_)
  440. {
  441. previousPosition_ = newPos;
  442. if (updateNodePosition_)
  443. {
  444. ignoreTransformChanges_ = true;
  445. node_->SetWorldPosition(newPos);
  446. ignoreTransformChanges_ = false;
  447. }
  448. using namespace CrowdAgentReposition;
  449. VariantMap& map = GetEventDataMap();
  450. map[P_NODE] = node_;
  451. map[P_CROWD_AGENT] = this;
  452. map[P_POSITION] = newPos;
  453. map[P_VELOCITY] = newVel;
  454. map[P_ARRIVED] = HasArrived();
  455. map[P_TIMESTEP] = dt;
  456. crowdManager_->SendEvent(E_CROWD_AGENT_REPOSITION, map);
  457. if (self.Expired())
  458. return;
  459. node_->SendEvent(E_CROWD_AGENT_NODE_REPOSITION, map);
  460. if (self.Expired())
  461. return;
  462. }
  463. // Send a notification event if we've reached the destination
  464. CrowdAgentTargetState newTargetState = GetTargetState();
  465. CrowdAgentState newAgentState = GetAgentState();
  466. if (newAgentState != previousAgentState_ || newTargetState != previousTargetState_)
  467. {
  468. using namespace CrowdAgentStateChanged;
  469. VariantMap& map = GetEventDataMap();
  470. map[P_NODE] = node_;
  471. map[P_CROWD_AGENT] = this;
  472. map[P_CROWD_TARGET_STATE] = newTargetState;
  473. map[P_CROWD_AGENT_STATE] = newAgentState;
  474. map[P_POSITION] = newPos;
  475. map[P_VELOCITY] = newVel;
  476. crowdManager_->SendEvent(E_CROWD_AGENT_STATE_CHANGED, map);
  477. if (self.Expired())
  478. return;
  479. node_->SendEvent(E_CROWD_AGENT_NODE_STATE_CHANGED, map);
  480. if (self.Expired())
  481. return;
  482. // Send a failure event if either state is a failed status
  483. if (newAgentState == CA_STATE_INVALID || newTargetState == CA_TARGET_FAILED)
  484. {
  485. VariantMap& map = GetEventDataMap();
  486. map[P_NODE] = node_;
  487. map[P_CROWD_AGENT] = this;
  488. map[P_CROWD_TARGET_STATE] = newTargetState;
  489. map[P_CROWD_AGENT_STATE] = newAgentState;
  490. map[P_POSITION] = newPos;
  491. map[P_VELOCITY] = newVel;
  492. crowdManager_->SendEvent(E_CROWD_AGENT_FAILURE, map);
  493. if (self.Expired())
  494. return;
  495. node_->SendEvent(E_CROWD_AGENT_NODE_FAILURE, map);
  496. if (self.Expired())
  497. return;
  498. }
  499. // State may have been altered during the handling of the event
  500. previousAgentState_ = GetAgentState();
  501. previousTargetState_ = GetTargetState();
  502. }
  503. }
  504. }
  505. void CrowdAgent::OnNodeSet(Node* node)
  506. {
  507. if (node)
  508. node->AddListener(this);
  509. }
  510. void CrowdAgent::OnSceneSet(Scene* scene)
  511. {
  512. if (scene)
  513. {
  514. if (scene == node_)
  515. URHO3D_LOGERROR(GetTypeName() + " should not be created to the root scene node");
  516. crowdManager_ = scene->GetOrCreateComponent<CrowdManager>();
  517. AddAgentToCrowd();
  518. }
  519. else
  520. RemoveAgentFromCrowd();
  521. }
  522. void CrowdAgent::OnMarkedDirty(Node* node)
  523. {
  524. if (!ignoreTransformChanges_ && IsEnabledEffective())
  525. {
  526. auto* agent = const_cast<dtCrowdAgent*>(GetDetourCrowdAgent());
  527. if (agent)
  528. {
  529. auto& agentPos = reinterpret_cast<Vector3&>(agent->npos);
  530. Vector3 nodePos = node->GetWorldPosition();
  531. // Only reset position / state if actually changed
  532. if (nodePos != agentPos)
  533. {
  534. agentPos = nodePos;
  535. // If the node has been externally altered, provide the opportunity for DetourCrowd to reevaluate the crowd agent
  536. if (agent->state == CA_STATE_INVALID)
  537. agent->state = CA_STATE_WALKING;
  538. }
  539. }
  540. }
  541. }
  542. const dtCrowdAgent* CrowdAgent::GetDetourCrowdAgent() const
  543. {
  544. return IsInCrowd() ? crowdManager_->GetDetourCrowdAgent(agentCrowdId_) : nullptr;
  545. }
  546. void CrowdAgent::HandleNavigationTileAdded(StringHash eventType, VariantMap& eventData)
  547. {
  548. if (!crowdManager_)
  549. return;
  550. auto* mesh = static_cast<NavigationMesh*>(eventData[NavigationTileAdded::P_MESH].GetPtr());
  551. if (crowdManager_->GetNavigationMesh() != mesh)
  552. return;
  553. const IntVector2 tile = eventData[NavigationTileRemoved::P_TILE].GetIntVector2();
  554. const IntVector2 agentTile = mesh->GetTileIndex(node_->GetWorldPosition());
  555. const BoundingBox boundingBox = mesh->GetTileBoundingBox(agentTile);
  556. if (tile == agentTile && IsInCrowd())
  557. {
  558. RemoveAgentFromCrowd();
  559. AddAgentToCrowd();
  560. }
  561. }
  562. }