CrowdAgent.cpp 22 KB

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