AINavigation.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  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
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell 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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "AINavigation.h"
  23. #include "AIController.h"
  24. #include "T3D/shapeBase.h"
  25. static U32 sAILoSMask = TerrainObjectType | StaticShapeObjectType | StaticObjectType | AIObjectType;
  26. AINavigation::AINavigation(AIController* controller)
  27. {
  28. mControllerRef = controller;
  29. #ifdef TORQUE_NAVIGATION_ENABLED
  30. mJump = None;
  31. mNavSize = Regular;
  32. #endif
  33. }
  34. AINavigation::~AINavigation()
  35. {
  36. #ifdef TORQUE_NAVIGATION_ENABLED
  37. clearPath();
  38. clearFollow();
  39. #endif
  40. }
  41. void AINavigation::setMoveDestination(const Point3F& location, bool slowdown)
  42. {
  43. mMoveDestination = location;
  44. getCtrl()->mMovement.mMoveState = AIController::ModeMove;
  45. getCtrl()->mMovement.mMoveSlowdown = slowdown;
  46. getCtrl()->mMovement.mMoveStuckTestCountdown = getCtrl()->mControllerData->mMoveStuckTestDelay;
  47. }
  48. bool AINavigation::setPathDestination(const Point3F& pos, bool replace)
  49. {
  50. #ifdef TORQUE_NAVIGATION_ENABLED
  51. if (replace)
  52. getCtrl()->setGoal(pos, getCtrl()->mControllerData->mMoveTolerance);
  53. if (!mNavMesh)
  54. updateNavMesh();
  55. // If we can't find a mesh, just move regularly.
  56. if (!mNavMesh)
  57. {
  58. //setMoveDestination(pos);
  59. getCtrl()->throwCallback("onPathFailed");
  60. return false;
  61. }
  62. // Create a new path.
  63. NavPath* path = new NavPath();
  64. path->mMesh = mNavMesh;
  65. path->mFrom = getCtrl()->getAIInfo()->getPosition(true);
  66. path->mTo = getCtrl()->getGoal()->getPosition(true);
  67. path->mFromSet = path->mToSet = true;
  68. path->mAlwaysRender = true;
  69. path->mLinkTypes = getCtrl()->mControllerData->mLinkTypes;
  70. path->mXray = true;
  71. // Paths plan automatically upon being registered.
  72. if (!path->registerObject())
  73. {
  74. delete path;
  75. return false;
  76. }
  77. if (path->success())
  78. {
  79. // Clear any current path we might have.
  80. clearPath();
  81. getCtrl()->clearCover();
  82. // Store new path.
  83. mPathData.path = path;
  84. mPathData.owned = true;
  85. // Skip node 0, which we are currently standing on.
  86. moveToNode(1);
  87. getCtrl()->throwCallback("onPathSuccess");
  88. return true;
  89. }
  90. else
  91. {
  92. // Just move normally if we can't path.
  93. //setMoveDestination(pos, true);
  94. //return;
  95. getCtrl()->throwCallback("onPathFailed");
  96. path->deleteObject();
  97. return false;
  98. }
  99. #else
  100. setMoveDestination(pos, false);
  101. return true;
  102. #endif
  103. }
  104. Point3F AINavigation::getPathDestination() const
  105. {
  106. #ifdef TORQUE_NAVIGATION_ENABLED
  107. if (!mPathData.path.isNull())
  108. return mPathData.path->mTo;
  109. return Point3F(0, 0, 0);
  110. #else
  111. return getMoveDestination();
  112. #endif
  113. }
  114. void AINavigation::onReachDestination()
  115. {
  116. #ifdef TORQUE_NAVIGATION_ENABLED
  117. if (!getPath().isNull())
  118. {
  119. if (mPathData.index == getPath()->size() - 1)
  120. {
  121. // Handle looping paths.
  122. if (getPath()->mIsLooping)
  123. moveToNode(0);
  124. // Otherwise end path.
  125. else
  126. {
  127. clearPath();
  128. getCtrl()->throwCallback("onReachDestination");
  129. }
  130. }
  131. else
  132. {
  133. moveToNode(mPathData.index + 1);
  134. // Throw callback every time if we're on a looping path.
  135. //if(mPathData.path->mIsLooping)
  136. //throwCallback("onReachDestination");
  137. }
  138. }
  139. else
  140. #endif
  141. {
  142. getCtrl()->throwCallback("onReachDestination");
  143. getCtrl()->mMovement.mMoveState = AIController::ModeStop;
  144. }
  145. }
  146. void AINavigation::followObject()
  147. {
  148. if (getCtrl()->getGoal()->getDist() < getCtrl()->mControllerData->mMoveTolerance)
  149. return;
  150. if (setPathDestination(getCtrl()->getGoal()->getPosition(true)))
  151. {
  152. #ifdef TORQUE_NAVIGATION_ENABLED
  153. getCtrl()->clearCover();
  154. #endif
  155. }
  156. }
  157. void AINavigation::followObject(SceneObject* obj, F32 radius)
  158. {
  159. getCtrl()->setGoal(obj, radius);
  160. followObject();
  161. }
  162. void AINavigation::clearFollow()
  163. {
  164. getCtrl()->clearGoal();
  165. }
  166. DefineEngineMethod(AIController, setMoveDestination, void, (Point3F goal, bool slowDown), (true),
  167. "@brief Tells the AI to move to the location provided\n\n"
  168. "@param goal Coordinates in world space representing location to move to.\n"
  169. "@param slowDown A boolean value. If set to true, the bot will slow down "
  170. "when it gets within 5-meters of its move destination. If false, the bot "
  171. "will stop abruptly when it reaches the move destination. By default, this is true.\n\n"
  172. "@note Upon reaching a move destination, the bot will clear its move destination and "
  173. "calls to getMoveDestination will return \"0 0 0\"."
  174. "@see getMoveDestination()\n")
  175. {
  176. object->getNav()->setMoveDestination(goal, slowDown);
  177. }
  178. DefineEngineMethod(AIController, getMoveDestination, Point3F, (), ,
  179. "@brief Get the AIPlayer's current destination.\n\n"
  180. "@return Returns a point containing the \"x y z\" position "
  181. "of the AIPlayer's current move destination. If no move destination "
  182. "has yet been set, this returns \"0 0 0\"."
  183. "@see setMoveDestination()\n")
  184. {
  185. return object->getNav()->getMoveDestination();
  186. }
  187. DefineEngineMethod(AIController, setPathDestination, bool, (Point3F goal), ,
  188. "@brief Tells the AI to find a path to the location provided\n\n"
  189. "@param goal Coordinates in world space representing location to move to.\n"
  190. "@return True if a path was found.\n\n"
  191. "@see getPathDestination()\n"
  192. "@see setMoveDestination()\n")
  193. {
  194. return object->getNav()->setPathDestination(goal, true);
  195. }
  196. DefineEngineMethod(AIController, getPathDestination, Point3F, (), ,
  197. "@brief Get the AIPlayer's current pathfinding destination.\n\n"
  198. "@return Returns a point containing the \"x y z\" position "
  199. "of the AIPlayer's current path destination. If no path destination "
  200. "has yet been set, this returns \"0 0 0\"."
  201. "@see setPathDestination()\n")
  202. {
  203. return object->getNav()->getPathDestination();
  204. }
  205. DefineEngineMethod(AIController, followObject, void, (SimObjectId obj, F32 radius), ,
  206. "@brief Tell the AIPlayer to follow another object.\n\n"
  207. "@param obj ID of the object to follow.\n"
  208. "@param radius Maximum distance we let the target escape to.")
  209. {
  210. SceneObject* follow;
  211. #ifdef TORQUE_NAVIGATION_ENABLED
  212. object->getNav()->clearPath();
  213. object->clearCover();
  214. #endif
  215. object->getNav()->clearFollow();
  216. if (Sim::findObject(obj, follow))
  217. object->getNav()->followObject(follow, radius);
  218. }
  219. #ifdef TORQUE_NAVIGATION_ENABLED
  220. NavMesh* AINavigation::findNavMesh() const
  221. {
  222. GameBase* gbo = dynamic_cast<GameBase*>(mControllerRef->getAIInfo()->mObj.getPointer());
  223. // Search for NavMeshes that contain us entirely with the smallest possible
  224. // volume.
  225. NavMesh* mesh = NULL;
  226. SimSet* set = NavMesh::getServerSet();
  227. for (U32 i = 0; i < set->size(); i++)
  228. {
  229. NavMesh* m = static_cast<NavMesh*>(set->at(i));
  230. if (m->getWorldBox().isContained(gbo->getWorldBox()))
  231. {
  232. // Check that mesh size is appropriate.
  233. if (gbo->isMounted())
  234. {
  235. if (!m->mVehicles)
  236. continue;
  237. }
  238. else
  239. {
  240. if ((getNavSize() == Small && !m->mSmallCharacters) ||
  241. (getNavSize() == Regular && !m->mRegularCharacters) ||
  242. (getNavSize() == Large && !m->mLargeCharacters))
  243. continue;
  244. }
  245. if (!mesh || m->getWorldBox().getVolume() < mesh->getWorldBox().getVolume())
  246. mesh = m;
  247. }
  248. }
  249. return mesh;
  250. }
  251. void AINavigation::updateNavMesh()
  252. {
  253. GameBase* gbo = dynamic_cast<GameBase*>(mControllerRef->getAIInfo()->mObj.getPointer());
  254. NavMesh* old = mNavMesh;
  255. if (mNavMesh.isNull())
  256. mNavMesh = findNavMesh();
  257. else
  258. {
  259. if (!mNavMesh->getWorldBox().isContained(gbo->getWorldBox()))
  260. mNavMesh = findNavMesh();
  261. }
  262. // See if we need to update our path.
  263. if (mNavMesh != old && !mPathData.path.isNull())
  264. {
  265. setPathDestination(mPathData.path->mTo);
  266. }
  267. }
  268. void AINavigation::moveToNode(S32 node)
  269. {
  270. if (mPathData.path.isNull())
  271. return;
  272. // -1 is shorthand for 'last path node'.
  273. if (node == -1)
  274. node = mPathData.path->size() - 1;
  275. // Consider slowing down on the last path node.
  276. setMoveDestination(mPathData.path->getNode(node), false);
  277. // Check flags for this segment.
  278. if (mPathData.index)
  279. {
  280. U16 flags = mPathData.path->getFlags(node - 1);
  281. // Jump if we must.
  282. if (flags & LedgeFlag)
  283. mJump = Ledge;
  284. else if (flags & JumpFlag)
  285. mJump = Now;
  286. else
  287. // Catch pathing errors.
  288. mJump = None;
  289. }
  290. // Store current index.
  291. mPathData.index = node;
  292. }
  293. void AINavigation::repath()
  294. {
  295. // Ineffectual if we don't have a path, or are using someone else's.
  296. if (mPathData.path.isNull() || !mPathData.owned)
  297. return;
  298. if (mRandI(0, 100) < getCtrl()->mControllerData->mFlocking.mChance && flock())
  299. {
  300. mPathData.path->mTo = mMoveDestination;
  301. }
  302. else
  303. {
  304. // If we're following, get their position.
  305. mPathData.path->mTo = getCtrl()->getGoal()->getPosition(true);
  306. }
  307. // Update from position and replan.
  308. mPathData.path->mFrom = getCtrl()->getAIInfo()->getPosition(true);
  309. mPathData.path->plan();
  310. // Move to first node (skip start pos).
  311. moveToNode(1);
  312. }
  313. void AINavigation::followNavPath(NavPath* path)
  314. {
  315. // Get rid of our current path.
  316. clearPath();
  317. getCtrl()->clearCover();
  318. // Follow new path.
  319. mPathData.path = path;
  320. mPathData.owned = false;
  321. // Start from 0 since we might not already be there.
  322. moveToNode(0);
  323. }
  324. void AINavigation::clearPath()
  325. {
  326. // Only delete if we own the path.
  327. if (!mPathData.path.isNull() && mPathData.owned)
  328. mPathData.path->deleteObject();
  329. // Reset path data.
  330. mPathData = PathData();
  331. }
  332. bool AINavigation::flock()
  333. {
  334. AIControllerData::Flocking flockingData = getCtrl()->mControllerData->mFlocking;
  335. SimObjectPtr<SceneObject> obj = getCtrl()->getAIInfo()->mObj;
  336. obj->disableCollision();
  337. Point3F pos = obj->getBoxCenter();
  338. Point3F searchArea = Point3F(flockingData.mMin / 2, flockingData.mMax / 2, getCtrl()->getAIInfo()->mObj->getObjBox().maxExtents.z / 2);
  339. F32 maxFlocksq = flockingData.mMax * flockingData.mMax;
  340. bool flocking = false;
  341. U32 found = 0;
  342. if (getCtrl()->getGoal())
  343. {
  344. Point3F dest = mMoveDestination;
  345. if (getCtrl()->mMovement.mMoveState == AIController::ModeStuck)
  346. {
  347. Point3F shuffle = Point3F(mRandF() - 0.5, mRandF() - 0.5, 0);
  348. shuffle.normalize();
  349. dest += shuffle * flockingData.mMin;
  350. }
  351. dest.z = pos.z;
  352. if ((pos - dest).len() > flockingData.mSideStep)
  353. {
  354. //find closest object
  355. SimpleQueryList sql;
  356. Box3F queryBox = Box3F(pos - searchArea, pos + searchArea);
  357. obj->getContainer()->findObjects(queryBox, AIObjectType, SimpleQueryList::insertionCallback, &sql);
  358. sql.mList.remove(obj);
  359. Point3F avoidanceOffset = Point3F::Zero;
  360. //avoid objects in the way
  361. RayInfo info;
  362. if (obj->getContainer()->castRay(pos, dest + Point3F(0, 0, obj->getObjBox().len_z() / 2), sAILoSMask, &info))
  363. {
  364. Point3F blockerOffset = (info.point - dest);
  365. blockerOffset.z = 0;
  366. avoidanceOffset += blockerOffset;
  367. }
  368. //avoid bots that are too close
  369. for (U32 i = 0; i < sql.mList.size(); i++)
  370. {
  371. ShapeBase* other = dynamic_cast<ShapeBase*>(sql.mList[i]);
  372. Point3F objectCenter = other->getBoxCenter();
  373. F32 sumRad = flockingData.mMin + other->getAIController()->mControllerData->mFlocking.mMin;
  374. F32 separation = getCtrl()->getAIInfo()->mRadius + other->getAIController()->getAIInfo()->mRadius;
  375. sumRad += separation;
  376. Point3F offset = (pos - objectCenter);
  377. F32 offsetLensq = offset.lenSquared(); //square roots are expensive, so use squared val compares
  378. if ((flockingData.mMin > 0) && (offsetLensq < (sumRad * sumRad)))
  379. {
  380. other->disableCollision();
  381. if (!obj->getContainer()->castRay(pos, other->getBoxCenter(), sAILoSMask, &info))
  382. {
  383. found++;
  384. offset.normalizeSafe();
  385. offset *= sumRad + separation;
  386. avoidanceOffset += offset; //accumulate total group, move away from that
  387. }
  388. other->enableCollision();
  389. }
  390. }
  391. //if we don't have to worry about bumping into one another (nothing found lower than minFLock), see about grouping up
  392. if (found == 0)
  393. {
  394. for (U32 i = 0; i < sql.mList.size(); i++)
  395. {
  396. ShapeBase* other = static_cast<ShapeBase*>(sql.mList[i]);
  397. Point3F objectCenter = other->getBoxCenter();
  398. F32 sumRad = flockingData.mMin + other->getAIController()->mControllerData->mFlocking.mMin;
  399. F32 separation = getCtrl()->getAIInfo()->mRadius + other->getAIController()->getAIInfo()->mRadius;
  400. sumRad += separation;
  401. Point3F offset = (pos - objectCenter);
  402. if ((flockingData.mMin > 0) && ((sumRad * sumRad) < (maxFlocksq)))
  403. {
  404. other->disableCollision();
  405. if (!obj->getContainer()->castRay(pos, other->getBoxCenter(), sAILoSMask, &info))
  406. {
  407. found++;
  408. offset.normalizeSafe();
  409. offset *= sumRad + separation;
  410. avoidanceOffset -= offset; // subtract total group, move toward it
  411. }
  412. other->enableCollision();
  413. }
  414. }
  415. }
  416. if (found > 0)
  417. {
  418. avoidanceOffset.z = 0;
  419. avoidanceOffset.x = (mRandF() * avoidanceOffset.x) * 0.5 + avoidanceOffset.x * 0.75;
  420. avoidanceOffset.y = (mRandF() * avoidanceOffset.y) * 0.5 + avoidanceOffset.y * 0.75;
  421. if (avoidanceOffset.lenSquared() < (maxFlocksq))
  422. {
  423. dest += avoidanceOffset;
  424. }
  425. //if we're not jumping...
  426. if (mJump == None)
  427. {
  428. dest.z = obj->getPosition().z;
  429. //make sure we don't run off a cliff
  430. Point3F zlen(0, 0, getCtrl()->mControllerData->mHeightTolerance);
  431. if (obj->getContainer()->castRay(dest + zlen, dest - zlen, TerrainObjectType | StaticShapeObjectType | StaticObjectType, &info))
  432. {
  433. if ((mMoveDestination - dest).len() > getCtrl()->mControllerData->mMoveTolerance)
  434. {
  435. mMoveDestination = dest;
  436. flocking = true;
  437. }
  438. }
  439. }
  440. }
  441. }
  442. }
  443. obj->enableCollision();
  444. return flocking;
  445. }
  446. DefineEngineMethod(AIController, followNavPath, void, (SimObjectId obj), ,
  447. "@brief Tell the AIPlayer to follow a path.\n\n"
  448. "@param obj ID of a NavPath object for the character to follow.")
  449. {
  450. NavPath* path;
  451. if (Sim::findObject(obj, path))
  452. object->getNav()->followNavPath(path);
  453. }
  454. DefineEngineMethod(AIController, repath, void, (), ,
  455. "@brief Tells the AI to re-plan its path. Does nothing if the character "
  456. "has no path, or if it is following a mission path.\n\n")
  457. {
  458. object->getNav()->repath();
  459. }
  460. DefineEngineMethod(AIController, findNavMesh, S32, (), ,
  461. "@brief Get the NavMesh object this AIPlayer is currently using.\n\n"
  462. "@return The ID of the NavPath object this character is using for "
  463. "pathfinding. This is determined by the character's location, "
  464. "navigation type and other factors. Returns -1 if no NavMesh is "
  465. "found.")
  466. {
  467. NavMesh* mesh = object->getNav()->getNavMesh();
  468. return mesh ? mesh->getId() : -1;
  469. }
  470. DefineEngineMethod(AIController, getNavMesh, S32, (), ,
  471. "@brief Return the NavMesh this AIPlayer is using to navigate.\n\n")
  472. {
  473. NavMesh* m = object->getNav()->getNavMesh();
  474. return m ? m->getId() : 0;
  475. }
  476. DefineEngineMethod(AIController, setNavSize, void, (const char* size), ,
  477. "@brief Set the size of NavMesh this character uses. One of \"Small\", \"Regular\" or \"Large\".")
  478. {
  479. if (!String::compare(size, "Small"))
  480. object->getNav()->setNavSize(AINavigation::Small);
  481. else if (!String::compare(size, "Regular"))
  482. object->getNav()->setNavSize(AINavigation::Regular);
  483. else if (!String::compare(size, "Large"))
  484. object->getNav()->setNavSize(AINavigation::Large);
  485. else
  486. Con::errorf("AIPlayer::setNavSize: no such size '%s'.", size);
  487. }
  488. DefineEngineMethod(AIController, getNavSize, const char*, (), ,
  489. "@brief Return the size of NavMesh this character uses for pathfinding.")
  490. {
  491. switch (object->getNav()->getNavSize())
  492. {
  493. case AINavigation::Small:
  494. return "Small";
  495. case AINavigation::Regular:
  496. return "Regular";
  497. case AINavigation::Large:
  498. return "Large";
  499. }
  500. return "";
  501. }
  502. #endif