CrowdAgent.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. //
  2. // Copyright (c) 2008-2015 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 "../Scene/Component.h"
  24. #include "../Core/Context.h"
  25. #include "../Navigation/CrowdAgent.h"
  26. #include "../Graphics/DebugRenderer.h"
  27. #include "../Navigation/DetourCrowdManager.h"
  28. #include "../IO/Log.h"
  29. #include "../IO/MemoryBuffer.h"
  30. #include "../Navigation/NavigationEvents.h"
  31. #include "../Scene/Node.h"
  32. #include "../Core/Profiler.h"
  33. #include "../Scene/Scene.h"
  34. #include "../Scene/Serializable.h"
  35. #include "../Core/Variant.h"
  36. #include <Detour/include/DetourCommon.h>
  37. #include <DetourCrowd/include/DetourCrowd.h>
  38. #include "../DebugNew.h"
  39. namespace Atomic
  40. {
  41. extern const char* NAVIGATION_CATEGORY;
  42. static const unsigned DEFAULT_AGENT_NAVIGATION_FILTER_TYPE = 0;
  43. static const float DEFAULT_AGENT_MAX_SPEED = 0.f;
  44. static const float DEFAULT_AGENT_MAX_ACCEL = 0.f;
  45. static const NavigationQuality DEFAULT_AGENT_AVOIDANCE_QUALITY = NAVIGATIONQUALITY_HIGH;
  46. static const NavigationPushiness DEFAULT_AGENT_NAVIGATION_PUSHINESS = PUSHINESS_MEDIUM;
  47. const char* crowdAgentAvoidanceQualityNames[] = {
  48. "low",
  49. "medium",
  50. "high",
  51. 0
  52. };
  53. const char* crowdAgentPushinessNames[] = {
  54. "low",
  55. "medium",
  56. "high",
  57. 0
  58. };
  59. CrowdAgent::CrowdAgent(Context* context) :
  60. Component(context),
  61. inCrowd_(false),
  62. agentCrowdId_(-1),
  63. targetRef_(-1),
  64. updateNodePosition_(true),
  65. maxAccel_(DEFAULT_AGENT_MAX_ACCEL),
  66. maxSpeed_(DEFAULT_AGENT_MAX_SPEED),
  67. radius_(0.0f),
  68. height_(0.0f),
  69. filterType_(DEFAULT_AGENT_NAVIGATION_FILTER_TYPE),
  70. navQuality_(DEFAULT_AGENT_AVOIDANCE_QUALITY),
  71. navPushiness_(DEFAULT_AGENT_NAVIGATION_PUSHINESS),
  72. previousTargetState_(CROWD_AGENT_TARGET_NONE),
  73. previousAgentState_(CROWD_AGENT_READY),
  74. ignoreTransformChanges_(false)
  75. {
  76. }
  77. CrowdAgent::~CrowdAgent()
  78. {
  79. RemoveAgentFromCrowd();
  80. }
  81. void CrowdAgent::RegisterObject(Context* context)
  82. {
  83. context->RegisterFactory<CrowdAgent>(NAVIGATION_CATEGORY);
  84. ACCESSOR_ATTRIBUTE("Max Accel", GetMaxAccel, SetMaxAccel, float, DEFAULT_AGENT_MAX_ACCEL, AM_DEFAULT);
  85. ACCESSOR_ATTRIBUTE("Max Speed", GetMaxSpeed, SetMaxSpeed, float, DEFAULT_AGENT_MAX_SPEED, AM_DEFAULT);
  86. ACCESSOR_ATTRIBUTE("Radius", GetRadius, SetRadius, float, 0.0f, AM_DEFAULT);
  87. ACCESSOR_ATTRIBUTE("Height", GetHeight, SetHeight, float, 0.0f, AM_DEFAULT);
  88. ACCESSOR_ATTRIBUTE("Target Position", GetTargetPosition, SetMoveTarget, Vector3, Vector3::ZERO, AM_DEFAULT);
  89. ACCESSOR_ATTRIBUTE("Navigation Filter", GetNavigationFilterType, SetNavigationFilterType, unsigned, DEFAULT_AGENT_NAVIGATION_FILTER_TYPE, AM_DEFAULT);
  90. ENUM_ACCESSOR_ATTRIBUTE("Navigation Pushiness", GetNavigationPushiness, SetNavigationPushiness, NavigationPushiness, crowdAgentPushinessNames, PUSHINESS_LOW, AM_DEFAULT);
  91. ENUM_ACCESSOR_ATTRIBUTE("Navigation Quality", GetNavigationQuality, SetNavigationQuality, NavigationQuality, crowdAgentAvoidanceQualityNames, NAVIGATIONQUALITY_LOW, AM_DEFAULT);
  92. MIXED_ACCESSOR_ATTRIBUTE("Agent Data", GetAgentDataAttr, SetAgentDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  93. }
  94. void CrowdAgent::OnNodeSet(Node* node)
  95. {
  96. if (node)
  97. node->AddListener(this);
  98. }
  99. void CrowdAgent::OnSceneSet(Scene* scene)
  100. {
  101. if (scene)
  102. {
  103. if (scene == node_)
  104. LOGERROR(GetTypeName() + " should not be created to the root scene node");
  105. crowdManager_ = scene->GetOrCreateComponent<DetourCrowdManager>();
  106. AddAgentToCrowd();
  107. }
  108. else
  109. RemoveAgentFromCrowd();
  110. }
  111. void CrowdAgent::OnSetEnabled()
  112. {
  113. bool enabled = IsEnabledEffective();
  114. if (enabled && !inCrowd_)
  115. AddAgentToCrowd();
  116. else if (!enabled && inCrowd_)
  117. RemoveAgentFromCrowd();
  118. }
  119. void CrowdAgent::DrawDebugGeometry(bool depthTest)
  120. {
  121. Scene* scene = GetScene();
  122. if (scene)
  123. {
  124. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  125. if (debug)
  126. DrawDebugGeometry(debug, depthTest);
  127. }
  128. }
  129. void CrowdAgent::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  130. {
  131. if (node_)
  132. {
  133. const Vector3 pos = GetPosition();
  134. const Vector3 vel = GetActualVelocity();
  135. const Vector3 desiredVel = GetDesiredVelocity();
  136. const Vector3 agentHeightVec(0, height_, 0);
  137. debug->AddLine(pos + 0.5f * agentHeightVec, pos + vel + 0.5f * agentHeightVec, Color::GREEN, depthTest);
  138. debug->AddLine(pos + 0.25f * agentHeightVec, pos + desiredVel + 0.25f * agentHeightVec, Color::RED, depthTest);
  139. debug->AddCylinder(pos, radius_, height_, HasArrived() ? Color::GREEN : Color::WHITE, depthTest);
  140. }
  141. }
  142. const dtCrowdAgent* CrowdAgent::GetDetourCrowdAgent() const
  143. {
  144. return crowdManager_ && inCrowd_ ? crowdManager_->GetCrowdAgent(agentCrowdId_) : 0;
  145. }
  146. void CrowdAgent::AddAgentToCrowd()
  147. {
  148. if (!crowdManager_ || !crowdManager_->crowd_ || !node_)
  149. return;
  150. PROFILE(AddAgentToCrowd);
  151. if (!inCrowd_)
  152. {
  153. inCrowd_ = true;
  154. agentCrowdId_ = crowdManager_->AddAgent(this, node_->GetPosition());
  155. if (agentCrowdId_ == -1)
  156. {
  157. inCrowd_ = false;
  158. LOGERROR("AddAgentToCrowd: Could not add agent to crowd");
  159. return;
  160. }
  161. crowdManager_->UpdateAgentNavigationQuality(this, navQuality_);
  162. crowdManager_->UpdateAgentPushiness(this, navPushiness_);
  163. previousAgentState_ = GetAgentState();
  164. previousTargetState_ = GetTargetState();
  165. // Agent created, but initial state is invalid and needs to be addressed
  166. if (previousAgentState_ == CROWD_AGENT_INVALID)
  167. {
  168. VariantMap& map = GetContext()->GetEventDataMap();
  169. map[CrowdAgentFailure::P_NODE] = GetNode();
  170. map[CrowdAgentFailure::P_CROWD_AGENT] = this;
  171. map[CrowdAgentFailure::P_CROWD_TARGET_STATE] = previousTargetState_;
  172. map[CrowdAgentFailure::P_CROWD_AGENT_STATE] = previousAgentState_;
  173. map[CrowdAgentFailure::P_POSITION] = GetPosition();
  174. map[CrowdAgentFailure::P_VELOCITY] = GetActualVelocity();
  175. SendEvent(E_CROWD_AGENT_FAILURE, map);
  176. // Reevaluate states as handling of event may have resulted in changes
  177. previousAgentState_ = GetAgentState();
  178. previousTargetState_ = GetTargetState();
  179. }
  180. // Save the initial position to prevent CrowdAgentReposition event being triggered unnecessarily
  181. previousPosition_ = GetPosition();
  182. }
  183. }
  184. void CrowdAgent::RemoveAgentFromCrowd()
  185. {
  186. if (crowdManager_ && agentCrowdId_ != -1 && inCrowd_)
  187. {
  188. crowdManager_->RemoveAgent(this);
  189. inCrowd_ = false;
  190. agentCrowdId_ = -1;
  191. }
  192. }
  193. void CrowdAgent::SetNavigationFilterType(unsigned filterType)
  194. {
  195. filterType_ = filterType;
  196. if (crowdManager_ && inCrowd_)
  197. {
  198. // If in the crowd it's necessary to force the update of the query filter
  199. dtCrowdAgentParams params = crowdManager_->GetCrowdAgent(agentCrowdId_)->params;
  200. params.queryFilterType = (unsigned char)filterType;
  201. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  202. MarkNetworkUpdate();
  203. }
  204. }
  205. void CrowdAgent::SetMoveTarget(const Vector3& position)
  206. {
  207. if (crowdManager_) {
  208. if (!inCrowd_)
  209. AddAgentToCrowd();
  210. targetPosition_ = position;
  211. if (crowdManager_->SetAgentTarget(this, position, targetRef_))
  212. MarkNetworkUpdate();
  213. }
  214. }
  215. void CrowdAgent::ResetMoveTarget()
  216. {
  217. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  218. if (agent && agent->active)
  219. {
  220. targetPosition_ = Vector3::ZERO;
  221. crowdManager_->GetCrowd()->resetMoveTarget(agentCrowdId_);
  222. MarkNetworkUpdate();
  223. }
  224. }
  225. void CrowdAgent::SetMoveVelocity(const Vector3& velocity)
  226. {
  227. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  228. if (agent && agent->active)
  229. {
  230. crowdManager_->GetCrowd()->requestMoveVelocity(agentCrowdId_, velocity.Data());
  231. MarkNetworkUpdate();
  232. }
  233. }
  234. void CrowdAgent::SetMaxSpeed(float speed)
  235. {
  236. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  237. if (agent)
  238. {
  239. maxSpeed_ = speed;
  240. dtCrowdAgentParams params = agent->params;
  241. params.maxSpeed = speed;
  242. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  243. MarkNetworkUpdate();
  244. }
  245. }
  246. void CrowdAgent::SetMaxAccel(float accel)
  247. {
  248. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  249. if (agent)
  250. {
  251. maxAccel_ = accel;
  252. dtCrowdAgentParams params = agent->params;
  253. params.maxAcceleration = accel;
  254. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  255. MarkNetworkUpdate();
  256. }
  257. }
  258. void CrowdAgent::SetRadius(float radius)
  259. {
  260. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  261. if (agent)
  262. {
  263. radius_ = radius;
  264. dtCrowdAgentParams params = agent->params;
  265. params.radius = radius;
  266. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  267. MarkNetworkUpdate();
  268. }
  269. }
  270. void CrowdAgent::SetHeight(float height)
  271. {
  272. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  273. if (agent)
  274. {
  275. height_ = height;
  276. dtCrowdAgentParams params = agent->params;
  277. params.height = height;
  278. crowdManager_->GetCrowd()->updateAgentParameters(agentCrowdId_, &params);
  279. MarkNetworkUpdate();
  280. }
  281. }
  282. void CrowdAgent::SetNavigationQuality(NavigationQuality val)
  283. {
  284. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  285. if (agent)
  286. {
  287. navQuality_ = val;
  288. crowdManager_->UpdateAgentNavigationQuality(this, navQuality_);
  289. MarkNetworkUpdate();
  290. }
  291. }
  292. void CrowdAgent::SetNavigationPushiness(NavigationPushiness val)
  293. {
  294. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  295. if (agent)
  296. {
  297. navPushiness_ = val;
  298. crowdManager_->UpdateAgentPushiness(this, navPushiness_);
  299. MarkNetworkUpdate();
  300. }
  301. }
  302. Vector3 CrowdAgent::GetPosition() const
  303. {
  304. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  305. return agent && agent->active ? Vector3(agent->npos) : node_->GetPosition();
  306. }
  307. Vector3 CrowdAgent::GetDesiredVelocity() const
  308. {
  309. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  310. return agent && agent->active ? Vector3(agent->dvel) : Vector3::ZERO;
  311. }
  312. Vector3 CrowdAgent::GetActualVelocity() const
  313. {
  314. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  315. return agent && agent->active ? Vector3(agent->vel) : Vector3::ZERO;
  316. }
  317. Atomic::CrowdAgentState CrowdAgent::GetAgentState() const
  318. {
  319. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  320. return agent && agent->active ? (CrowdAgentState)agent->state : CROWD_AGENT_INVALID;
  321. }
  322. Atomic::CrowdTargetState CrowdAgent::GetTargetState() const
  323. {
  324. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  325. return agent && agent->active ? (CrowdTargetState)agent->targetState : CROWD_AGENT_TARGET_NONE;
  326. }
  327. bool CrowdAgent::HasArrived() const
  328. {
  329. // Is the agent at or near the end of its path?
  330. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  331. return agent && agent->active && (!agent->ncorners ||
  332. (agent->cornerFlags[agent->ncorners - 1] & DT_STRAIGHTPATH_END &&
  333. Equals(dtVdist2D(agent->npos, &agent->cornerVerts[(agent->ncorners - 1) * 3]), 0.f)));
  334. }
  335. void CrowdAgent::SetUpdateNodePosition(bool unodepos)
  336. {
  337. updateNodePosition_ = unodepos;
  338. MarkNetworkUpdate();
  339. }
  340. void CrowdAgent::OnCrowdAgentReposition(const Vector3& newPos, const Vector3& newVel)
  341. {
  342. if (node_)
  343. {
  344. // Notify parent node of the reposition
  345. if (newPos != previousPosition_)
  346. {
  347. previousPosition_ = newPos;
  348. VariantMap& map = GetContext()->GetEventDataMap();
  349. map[CrowdAgentReposition::P_NODE] = GetNode();
  350. map[CrowdAgentReposition::P_CROWD_AGENT] = this;
  351. map[CrowdAgentReposition::P_POSITION] = newPos;
  352. map[CrowdAgentReposition::P_VELOCITY] = newVel;
  353. map[CrowdAgentReposition::P_ARRIVED] = HasArrived();
  354. SendEvent(E_CROWD_AGENT_REPOSITION, map);
  355. if (updateNodePosition_)
  356. {
  357. ignoreTransformChanges_ = true;
  358. node_->SetPosition(newPos);
  359. ignoreTransformChanges_ = false;
  360. }
  361. }
  362. // Send a notification event if we've reached the destination
  363. CrowdTargetState newTargetState = GetTargetState();
  364. CrowdAgentState newAgentState = GetAgentState();
  365. if (newAgentState != previousAgentState_ || newTargetState != previousTargetState_)
  366. {
  367. VariantMap& map = GetContext()->GetEventDataMap();
  368. map[CrowdAgentStateChanged::P_NODE] = GetNode();
  369. map[CrowdAgentStateChanged::P_CROWD_AGENT] = this;
  370. map[CrowdAgentStateChanged::P_CROWD_TARGET_STATE] = newTargetState;
  371. map[CrowdAgentStateChanged::P_CROWD_AGENT_STATE] = newAgentState;
  372. map[CrowdAgentStateChanged::P_POSITION] = newPos;
  373. map[CrowdAgentStateChanged::P_VELOCITY] = newVel;
  374. SendEvent(E_CROWD_AGENT_STATE_CHANGED, map);
  375. // Send a failure event if either state is a failed status
  376. if (newAgentState == CROWD_AGENT_INVALID || newTargetState == CROWD_AGENT_TARGET_FAILED)
  377. {
  378. VariantMap& map = GetContext()->GetEventDataMap();
  379. map[CrowdAgentFailure::P_NODE] = GetNode();
  380. map[CrowdAgentFailure::P_CROWD_AGENT] = this;
  381. map[CrowdAgentFailure::P_CROWD_TARGET_STATE] = newTargetState;
  382. map[CrowdAgentFailure::P_CROWD_AGENT_STATE] = newAgentState;
  383. map[CrowdAgentFailure::P_POSITION] = newPos;
  384. map[CrowdAgentFailure::P_VELOCITY] = newVel;
  385. SendEvent(E_CROWD_AGENT_FAILURE, map);
  386. }
  387. // State may have been altered during the handling of the event
  388. previousAgentState_ = GetAgentState();
  389. previousTargetState_ = GetTargetState();
  390. }
  391. }
  392. }
  393. PODVector<unsigned char> CrowdAgent::GetAgentDataAttr() const
  394. {
  395. const dtCrowdAgent* agent = GetDetourCrowdAgent();
  396. if (!agent)
  397. return Variant::emptyBuffer;
  398. // Reading it back in isn't this simple, see SetAgentDataAttr
  399. VectorBuffer ret;
  400. ret.Write(agent, sizeof(dtCrowdAgent));
  401. return ret.GetBuffer();
  402. }
  403. void CrowdAgent::SetAgentDataAttr(const PODVector<unsigned char>& value)
  404. {
  405. if (value.Empty())
  406. return;
  407. dtCrowdAgent* agent = const_cast<dtCrowdAgent*>(GetDetourCrowdAgent());
  408. if (!agent)
  409. return;
  410. MemoryBuffer buffer(value);
  411. // Path corridor is tricky
  412. char corridorData[sizeof(dtPathCorridor)];
  413. // Duplicate the existing path corridor into a block
  414. memcpy(corridorData, &agent->corridor, sizeof(dtPathCorridor));
  415. // Read the entire block of the crowd agent
  416. buffer.Read(agent, sizeof(dtCrowdAgent));
  417. // Restore the values of the original path corridor
  418. memcpy(&agent->corridor, corridorData, sizeof(dtPathCorridor));
  419. // Tell the path corridor to rebuild the path, it will reevaluate the path, existing velocities maintained
  420. agent->corridor.reset(agent->targetRef, agent->targetPos);
  421. agent->params.userData = this;
  422. }
  423. void CrowdAgent::OnMarkedDirty(Node* node)
  424. {
  425. if (!ignoreTransformChanges_ && IsEnabledEffective())
  426. {
  427. dtCrowdAgent* agent = const_cast<dtCrowdAgent*>(GetDetourCrowdAgent());
  428. if (agent)
  429. {
  430. memcpy(agent->npos, node->GetWorldPosition().Data(), sizeof(float) * 3);
  431. // If the node has been externally altered, provide the opportunity for DetourCrowd to reevaluate the crowd agent
  432. if (agent->state == CROWD_AGENT_INVALID)
  433. agent->state = CROWD_AGENT_READY;
  434. }
  435. }
  436. }
  437. }