CrowdAgent.cpp 22 KB

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