CrowdAgent.cpp 21 KB

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