CCNavMeshAgent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /****************************************************************************
  2. Copyright (c) 2015-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "navmesh/CCNavMeshAgent.h"
  22. #if CC_USE_NAVMESH
  23. #include "navmesh/CCNavMesh.h"
  24. #include "recast/DetourCrowd/DetourCrowd.h"
  25. #include "2d/CCNode.h"
  26. #include "2d/CCScene.h"
  27. #include <algorithm>
  28. NS_CC_BEGIN
  29. NavMeshAgentParam::NavMeshAgentParam()
  30. : radius(0.6f)
  31. , height(2.0f)
  32. , maxAcceleration(8.0f)
  33. , maxSpeed(3.5f)
  34. , collisionQueryRange(radius * 12.0f)
  35. , pathOptimizationRange(radius * 30.0f)
  36. , separationWeight(2.0f)
  37. , updateFlags(DT_CROWD_ANTICIPATE_TURNS | DT_CROWD_OPTIMIZE_VIS | DT_CROWD_OPTIMIZE_TOPO | DT_CROWD_OBSTACLE_AVOIDANCE)
  38. , obstacleAvoidanceType(3)
  39. , queryFilterType(0)
  40. {
  41. }
  42. NavMeshAgent* NavMeshAgent::create(const NavMeshAgentParam &param)
  43. {
  44. auto ref = new (std::nothrow) NavMeshAgent();
  45. if (ref && ref->initWith(param))
  46. {
  47. ref->autorelease();
  48. return ref;
  49. }
  50. CC_SAFE_DELETE(ref);
  51. return nullptr;
  52. }
  53. const std::string& NavMeshAgent::getNavMeshAgentComponentName()
  54. {
  55. static std::string comName = "___NavMeshAgentComponent___";
  56. return comName;
  57. }
  58. cocos2d::NavMeshAgent::NavMeshAgent()
  59. : _syncFlag(NODE_AND_NODE)
  60. , _rotRefAxes(Vec3::UNIT_Z)
  61. , _state(DT_CROWDAGENT_STATE_WALKING)
  62. , _needAutoOrientation(true)
  63. , _agentID(-1)
  64. , _needUpdateAgent(true)
  65. , _needMove(false)
  66. , _totalTimeAfterMove(0.0f)
  67. , _userData(nullptr)
  68. , _crowd(nullptr)
  69. , _navMeshQuery(nullptr)
  70. {
  71. }
  72. cocos2d::NavMeshAgent::~NavMeshAgent()
  73. {
  74. }
  75. bool NavMeshAgent::initWith(const NavMeshAgentParam &param)
  76. {
  77. _param = param;
  78. setName(getNavMeshAgentComponentName());
  79. return true;
  80. }
  81. void cocos2d::NavMeshAgent::setNavMeshQuery(dtNavMeshQuery *query)
  82. {
  83. _navMeshQuery = query;
  84. }
  85. void cocos2d::NavMeshAgent::removeFrom(dtCrowd *crowed)
  86. {
  87. crowed->removeAgent(_agentID);
  88. _crowd = nullptr;
  89. _agentID = -1;
  90. }
  91. void cocos2d::NavMeshAgent::addTo(dtCrowd *crowed)
  92. {
  93. _crowd = crowed;
  94. dtCrowdAgentParams ap;
  95. convertTodtAgentParam(_param, ap);
  96. Mat4 mat = _owner->getNodeToWorldTransform();
  97. _agentID = _crowd->addAgent(&mat.m[12], &ap);
  98. }
  99. void cocos2d::NavMeshAgent::convertTodtAgentParam(const NavMeshAgentParam &inParam, dtCrowdAgentParams &outParam)
  100. {
  101. memset(&outParam, 0, sizeof(outParam));
  102. outParam.collisionQueryRange = inParam.collisionQueryRange;
  103. outParam.height = inParam.height;
  104. outParam.maxAcceleration = inParam.maxAcceleration;
  105. outParam.maxSpeed = inParam.maxSpeed;
  106. outParam.obstacleAvoidanceType = inParam.obstacleAvoidanceType;
  107. outParam.pathOptimizationRange = inParam.pathOptimizationRange;
  108. outParam.queryFilterType = inParam.queryFilterType;
  109. outParam.radius = inParam.radius;
  110. outParam.separationWeight = inParam.separationWeight;
  111. outParam.updateFlags = inParam.updateFlags;
  112. }
  113. void cocos2d::NavMeshAgent::onExit()
  114. {
  115. if (_agentID == -1) return;
  116. Component::onExit();
  117. auto scene = _owner->getScene();
  118. if (scene && scene->getNavMesh()){
  119. scene->getNavMesh()->removeNavMeshAgent(this);
  120. }
  121. }
  122. void cocos2d::NavMeshAgent::onEnter()
  123. {
  124. if (_agentID != -1) return;
  125. Component::onEnter();
  126. auto scene = _owner->getScene();
  127. if (scene && scene->getNavMesh()){
  128. scene->getNavMesh()->addNavMeshAgent(this);
  129. }
  130. }
  131. float NavMeshAgent::getMaxSpeed() const
  132. {
  133. return _param.maxSpeed;
  134. }
  135. void NavMeshAgent::setSeparationWeight(float weight)
  136. {
  137. _param.separationWeight = weight;
  138. _needUpdateAgent = true;
  139. }
  140. float NavMeshAgent::getSeparationWeight() const
  141. {
  142. return _param.separationWeight;
  143. }
  144. void cocos2d::NavMeshAgent::setObstacleAvoidanceType(unsigned char type)
  145. {
  146. _param.obstacleAvoidanceType = type;
  147. _needUpdateAgent = true;
  148. }
  149. unsigned char NavMeshAgent::getObstacleAvoidanceType() const
  150. {
  151. return _param.obstacleAvoidanceType;
  152. }
  153. Vec3 NavMeshAgent::getCurrentVelocity() const
  154. {
  155. if (_crowd){
  156. auto agent = _crowd->getAgent(_agentID);
  157. if (agent){
  158. return Vec3(agent->vel[0], agent->vel[1], agent->vel[2]);
  159. }
  160. }
  161. return Vec3::ZERO;
  162. }
  163. void NavMeshAgent::setMaxSpeed(float maxSpeed)
  164. {
  165. _param.maxSpeed = maxSpeed;
  166. _needUpdateAgent = true;
  167. }
  168. float NavMeshAgent::getMaxAcceleration() const
  169. {
  170. return _param.maxAcceleration;
  171. }
  172. void NavMeshAgent::setMaxAcceleration(float maxAcceleration)
  173. {
  174. _param.maxAcceleration = maxAcceleration;
  175. _needUpdateAgent = true;
  176. }
  177. float NavMeshAgent::getHeight() const
  178. {
  179. return _param.height;
  180. }
  181. void NavMeshAgent::setHeight(float height)
  182. {
  183. _param.height = height;
  184. _needUpdateAgent = true;
  185. }
  186. float NavMeshAgent::getRadius() const
  187. {
  188. return _param.radius;
  189. }
  190. void NavMeshAgent::setRadius(float radius)
  191. {
  192. _param.radius = radius;
  193. _needUpdateAgent = true;
  194. }
  195. void NavMeshAgent::move(const Vec3 &destination, const MoveCallback &callback)
  196. {
  197. _destination = destination;
  198. _moveCallback = callback;
  199. _needMove = true;
  200. _needUpdateAgent = true;
  201. }
  202. OffMeshLinkData NavMeshAgent::getCurrentOffMeshLinkData()
  203. {
  204. OffMeshLinkData data;
  205. if (_crowd && isOnOffMeshLink()){
  206. auto agentAnim = _crowd->getEditableAgentAnim(_agentID);
  207. if (agentAnim){
  208. Mat4 mat;
  209. if (_owner && _owner->getParent())
  210. mat = _owner->getParent()->getWorldToNodeTransform();
  211. mat.transformPoint(agentAnim->startPos, &data.startPosition);
  212. mat.transformPoint(agentAnim->endPos, &data.endPosition);
  213. }
  214. }
  215. return data;
  216. }
  217. bool NavMeshAgent::isOnOffMeshLink()
  218. {
  219. return _state == DT_CROWDAGENT_STATE_OFFMESH;
  220. }
  221. void cocos2d::NavMeshAgent::completeOffMeshLink()
  222. {
  223. if (_crowd && isOnOffMeshLink()){
  224. _state = DT_CROWDAGENT_STATE_WALKING;
  225. _needUpdateAgent = true;
  226. }
  227. }
  228. void NavMeshAgent::setAutoTraverseOffMeshLink(bool isAuto)
  229. {
  230. if (_crowd && isOnOffMeshLink()){
  231. auto agentAnim = _crowd->getEditableAgentAnim(_agentID);
  232. if (agentAnim){
  233. agentAnim->active = isAuto;
  234. }
  235. }
  236. }
  237. void NavMeshAgent::stop()
  238. {
  239. if (_state != DT_CROWDAGENT_STATE_INVALID) return;
  240. _state = DT_CROWDAGENT_STATE_INVALID;
  241. _needUpdateAgent = true;
  242. }
  243. void NavMeshAgent::setOrientationRefAxes(const Vec3 &rotRefAxes)
  244. {
  245. _rotRefAxes = rotRefAxes;
  246. }
  247. void cocos2d::NavMeshAgent::setAutoOrientation(bool isAuto)
  248. {
  249. _needAutoOrientation = isAuto;
  250. }
  251. void NavMeshAgent::resume()
  252. {
  253. if (_state != DT_CROWDAGENT_STATE_INVALID) return;
  254. _state = DT_CROWDAGENT_STATE_WALKING;
  255. _needUpdateAgent = true;
  256. }
  257. void NavMeshAgent::pause()
  258. {
  259. if (_state == DT_CROWDAGENT_STATE_INVALID) return;
  260. _state = DT_CROWDAGENT_STATE_INVALID;
  261. _needUpdateAgent = true;
  262. }
  263. void NavMeshAgent::preUpdate(float delta)
  264. {
  265. if (_state != DT_CROWDAGENT_STATE_INVALID)
  266. _totalTimeAfterMove += delta;
  267. if (_moveCallback && _state != DT_CROWDAGENT_STATE_INVALID)
  268. _moveCallback(this, _totalTimeAfterMove);
  269. if ((_syncFlag & NODE_TO_AGENT) != 0)
  270. syncToAgent();
  271. if (_needMove && _crowd && _navMeshQuery){
  272. if (_state == DT_CROWDAGENT_STATE_OFFMESH) return;
  273. _state = DT_CROWDAGENT_STATE_WALKING;
  274. _totalTimeAfterMove = 0.0f;
  275. dtPolyRef pRef = 0;
  276. float nearestPos[3];
  277. _navMeshQuery->findNearestPoly(&_destination.x, _crowd->getQueryExtents(), _crowd->getFilter(0), &pRef, nearestPos);
  278. _crowd->requestMoveTarget(_agentID, pRef, nearestPos);
  279. _needMove = false;
  280. }
  281. }
  282. void NavMeshAgent::postUpdate(float /*delta*/)
  283. {
  284. if ((_syncFlag & AGENT_TO_NODE) != 0)
  285. syncToNode();
  286. }
  287. void NavMeshAgent::syncToNode()
  288. {
  289. const dtCrowdAgent *agent = nullptr;
  290. if (_crowd){
  291. agent = _crowd->getAgent(_agentID);
  292. }
  293. if (agent){
  294. Mat4 wtop;
  295. Vec3 pos;
  296. if (_owner->getParent())
  297. wtop = _owner->getParent()->getWorldToNodeTransform();
  298. wtop.transformPoint(Vec3(agent->npos[0], agent->npos[1], agent->npos[2]), &pos);
  299. _owner->setPosition3D(pos);
  300. _state = agent->state;
  301. if (_needAutoOrientation){
  302. if (std::abs(agent->vel[0]) > 0.3f || std::abs(agent->vel[1]) > 0.3f || std::abs(agent->vel[2]) > 0.3f)
  303. {
  304. Vec3 axes(_rotRefAxes);
  305. axes.normalize();
  306. Vec3 dir;
  307. wtop.transformVector(Vec3(agent->vel[0], agent->vel[1], agent->vel[2]), &dir);
  308. dir.normalize();
  309. float cosTheta = Vec3::dot(axes, dir);
  310. Vec3 rotAxes;
  311. Vec3::cross(axes, dir, &rotAxes);
  312. Quaternion rot = Quaternion(rotAxes, acosf(cosTheta));
  313. _owner->setRotationQuat(rot);
  314. }
  315. }
  316. }
  317. }
  318. void NavMeshAgent::syncToAgent()
  319. {
  320. if (_crowd){
  321. auto agent = _crowd->getEditableAgent(_agentID);
  322. Mat4 mat = _owner->getNodeToWorldTransform();
  323. agent->npos[0] = mat.m[12];
  324. agent->npos[1] = mat.m[13];
  325. agent->npos[2] = mat.m[14];
  326. //if (_needAutoOrientation){
  327. // Vec3 vel = mat * _rotRefAxes;
  328. // agent->vel[0] = vel.x;
  329. // agent->vel[1] = vel.y;
  330. // agent->vel[2] = vel.z;
  331. //}
  332. if (_needUpdateAgent){
  333. dtCrowdAgentParams ap;
  334. convertTodtAgentParam(_param, ap);
  335. agent->params = ap;
  336. agent->state = _state;
  337. _needUpdateAgent = false;
  338. }
  339. }
  340. }
  341. Vec3 NavMeshAgent::getVelocity() const
  342. {
  343. const dtCrowdAgent *agent = nullptr;
  344. if (_crowd){
  345. agent = _crowd->getAgent(_agentID);
  346. }
  347. if (agent)
  348. {
  349. return Vec3(agent->vel[0], agent->vel[1], agent->vel[2]);
  350. }
  351. return Vec3::ZERO;
  352. }
  353. NS_CC_END
  354. #endif //CC_USE_NAVMESH