CrowdAgent.cpp 17 KB

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