AINavigation.cpp 17 KB

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