aiPlayer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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 "platform/platform.h"
  23. #include "T3D/aiPlayer.h"
  24. #include "console/consoleInternal.h"
  25. #include "math/mMatrix.h"
  26. #include "T3D/gameBase/moveManager.h"
  27. #include "console/engineAPI.h"
  28. IMPLEMENT_CO_NETOBJECT_V1(AIPlayer);
  29. ConsoleDocClass( AIPlayer,
  30. "@brief A Player object not controlled by conventional input, but by an AI engine.\n\n"
  31. "The AIPlayer provides a Player object that may be controlled from script. You control "
  32. "where the player moves and how fast. You may also set where the AIPlayer is aiming at "
  33. "-- either a location or another game object.\n\n"
  34. "The AIPlayer class does not have a datablock of its own. It makes use of the PlayerData "
  35. "datablock to define how it looks, etc. As the AIPlayer is an extension of the Player class "
  36. "it can mount objects and fire weapons, or mount vehicles and drive them.\n\n"
  37. "While the PlayerData datablock is used, there are a number of additional callbacks that are "
  38. "implemented by AIPlayer on the datablock. These are listed here:\n\n"
  39. "void onReachDestination(AIPlayer obj) \n"
  40. "Called when the player has reached its set destination using the setMoveDestination() method. "
  41. "The actual point at which this callback is called is when the AIPlayer is within the mMoveTolerance "
  42. "of the defined destination.\n\n"
  43. "void onMoveStuck(AIPlayer obj) \n"
  44. "While in motion, if an AIPlayer has moved less than moveStuckTolerance within a single tick, this "
  45. "callback is called. From here you could choose an alternate destination to get the AIPlayer moving "
  46. "again.\n\n"
  47. "void onTargetEnterLOS(AIPlayer obj) \n"
  48. "When an object is being aimed at (following a call to setAimObject()) and the targeted object enters "
  49. "the AIPlayer's line of sight, this callback is called. The LOS test is a ray from the AIPlayer's eye "
  50. "position to the center of the target's bounding box. The LOS ray test only checks against interiors, "
  51. "statis shapes, and terrain.\n\n"
  52. "void onTargetExitLOS(AIPlayer obj) \n"
  53. "When an object is being aimed at (following a call to setAimObject()) and the targeted object leaves "
  54. "the AIPlayer's line of sight, this callback is called. The LOS test is a ray from the AIPlayer's eye "
  55. "position to the center of the target's bounding box. The LOS ray test only checks against interiors, "
  56. "statis shapes, and terrain.\n\n"
  57. "@tsexample\n"
  58. "// Create the demo player object\n"
  59. "%player = new AiPlayer()\n"
  60. "{\n"
  61. " dataBlock = DemoPlayer;\n"
  62. " path = \"\";\n"
  63. "};\n"
  64. "@endtsexample\n\n"
  65. "@see Player for a list of all inherited functions, variables, and base description\n"
  66. "@ingroup AI\n"
  67. "@ingroup gameObjects\n");
  68. /**
  69. * Constructor
  70. */
  71. AIPlayer::AIPlayer()
  72. {
  73. mMoveDestination.set( 0.0f, 0.0f, 0.0f );
  74. mMoveSpeed = 1.0f;
  75. mMoveTolerance = 0.25f;
  76. mMoveStuckTolerance = 0.01f;
  77. mMoveStuckTestDelay = 30;
  78. mMoveStuckTestCountdown = 0;
  79. mMoveSlowdown = true;
  80. mMoveState = ModeStop;
  81. mAimObject = 0;
  82. mAimLocationSet = false;
  83. mTargetInLOS = false;
  84. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  85. mIsAiControlled = true;
  86. }
  87. /**
  88. * Destructor
  89. */
  90. AIPlayer::~AIPlayer()
  91. {
  92. }
  93. void AIPlayer::initPersistFields()
  94. {
  95. addGroup( "AI" );
  96. addField( "mMoveTolerance", TypeF32, Offset( mMoveTolerance, AIPlayer ),
  97. "@brief Distance from destination before stopping.\n\n"
  98. "When the AIPlayer is moving to a given destination it will move to within "
  99. "this distance of the destination and then stop. By providing this tolerance "
  100. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  101. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  102. addField( "moveStuckTolerance", TypeF32, Offset( mMoveStuckTolerance, AIPlayer ),
  103. "@brief Distance tolerance on stuck check.\n\n"
  104. "When the AIPlayer is moving to a given destination, if it ever moves less than "
  105. "this tolerance during a single tick, the AIPlayer is considered stuck. At this point "
  106. "the onMoveStuck() callback is called on the datablock.\n");
  107. addField( "moveStuckTestDelay", TypeS32, Offset( mMoveStuckTestDelay, AIPlayer ),
  108. "@brief The number of ticks to wait before testing if the AIPlayer is stuck.\n\n"
  109. "When the AIPlayer is asked to move, this property is the number of ticks to wait "
  110. "before the AIPlayer starts to check if it is stuck. This delay allows the AIPlayer "
  111. "to accelerate to full speed without its initial slow start being considered as stuck.\n"
  112. "@note Set to zero to have the stuck test start immediately.\n");
  113. endGroup( "AI" );
  114. Parent::initPersistFields();
  115. }
  116. bool AIPlayer::onAdd()
  117. {
  118. if (!Parent::onAdd())
  119. return false;
  120. // Use the eye as the current position (see getAIMove)
  121. MatrixF eye;
  122. getEyeTransform(&eye);
  123. mLastLocation = eye.getPosition();
  124. return true;
  125. }
  126. /**
  127. * Sets the speed at which this AI moves
  128. *
  129. * @param speed Speed to move, default player was 10
  130. */
  131. void AIPlayer::setMoveSpeed( F32 speed )
  132. {
  133. mMoveSpeed = getMax(0.0f, getMin( 1.0f, speed ));
  134. }
  135. /**
  136. * Stops movement for this AI
  137. */
  138. void AIPlayer::stopMove()
  139. {
  140. mMoveState = ModeStop;
  141. }
  142. /**
  143. * Sets how far away from the move location is considered
  144. * "on target"
  145. *
  146. * @param tolerance Movement tolerance for error
  147. */
  148. void AIPlayer::setMoveTolerance( const F32 tolerance )
  149. {
  150. mMoveTolerance = getMax( 0.1f, tolerance );
  151. }
  152. /**
  153. * Sets the location for the bot to run to
  154. *
  155. * @param location Point to run to
  156. */
  157. void AIPlayer::setMoveDestination( const Point3F &location, bool slowdown )
  158. {
  159. mMoveDestination = location;
  160. mMoveState = ModeMove;
  161. mMoveSlowdown = slowdown;
  162. mMoveStuckTestCountdown = mMoveStuckTestDelay;
  163. }
  164. /**
  165. * Sets the object the bot is targeting
  166. *
  167. * @param targetObject The object to target
  168. */
  169. void AIPlayer::setAimObject( GameBase *targetObject )
  170. {
  171. mAimObject = targetObject;
  172. mTargetInLOS = false;
  173. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  174. }
  175. /**
  176. * Sets the object the bot is targeting and an offset to add to target location
  177. *
  178. * @param targetObject The object to target
  179. * @param offset The offest from the target location to aim at
  180. */
  181. void AIPlayer::setAimObject( GameBase *targetObject, Point3F offset )
  182. {
  183. mAimObject = targetObject;
  184. mTargetInLOS = false;
  185. mAimOffset = offset;
  186. }
  187. /**
  188. * Sets the location for the bot to aim at
  189. *
  190. * @param location Point to aim at
  191. */
  192. void AIPlayer::setAimLocation( const Point3F &location )
  193. {
  194. mAimObject = 0;
  195. mAimLocationSet = true;
  196. mAimLocation = location;
  197. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  198. }
  199. /**
  200. * Clears the aim location and sets it to the bot's
  201. * current destination so he looks where he's going
  202. */
  203. void AIPlayer::clearAim()
  204. {
  205. mAimObject = 0;
  206. mAimLocationSet = false;
  207. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  208. }
  209. /**
  210. * This method calculates the moves for the AI player
  211. *
  212. * @param movePtr Pointer to move the move list into
  213. */
  214. bool AIPlayer::getAIMove(Move *movePtr)
  215. {
  216. *movePtr = NullMove;
  217. // Use the eye as the current position.
  218. MatrixF eye;
  219. getEyeTransform(&eye);
  220. Point3F location = eye.getPosition();
  221. Point3F rotation = getRotation();
  222. // Orient towards the aim point, aim object, or towards
  223. // our destination.
  224. if (mAimObject || mAimLocationSet || mMoveState != ModeStop)
  225. {
  226. // Update the aim position if we're aiming for an object
  227. if (mAimObject)
  228. mAimLocation = mAimObject->getPosition() + mAimOffset;
  229. else
  230. if (!mAimLocationSet)
  231. mAimLocation = mMoveDestination;
  232. F32 xDiff = mAimLocation.x - location.x;
  233. F32 yDiff = mAimLocation.y - location.y;
  234. if (!mIsZero(xDiff) || !mIsZero(yDiff))
  235. {
  236. // First do Yaw
  237. // use the cur yaw between -Pi and Pi
  238. F32 curYaw = rotation.z;
  239. while (curYaw > M_2PI_F)
  240. curYaw -= M_2PI_F;
  241. while (curYaw < -M_2PI_F)
  242. curYaw += M_2PI_F;
  243. // find the yaw offset
  244. F32 newYaw = mAtan2( xDiff, yDiff );
  245. F32 yawDiff = newYaw - curYaw;
  246. // make it between 0 and 2PI
  247. if( yawDiff < 0.0f )
  248. yawDiff += M_2PI_F;
  249. else if( yawDiff >= M_2PI_F )
  250. yawDiff -= M_2PI_F;
  251. // now make sure we take the short way around the circle
  252. if( yawDiff > M_PI_F )
  253. yawDiff -= M_2PI_F;
  254. else if( yawDiff < -M_PI_F )
  255. yawDiff += M_2PI_F;
  256. movePtr->yaw = yawDiff;
  257. // Next do pitch.
  258. if (!mAimObject && !mAimLocationSet)
  259. {
  260. // Level out if were just looking at our next way point.
  261. Point3F headRotation = getHeadRotation();
  262. movePtr->pitch = -headRotation.x;
  263. }
  264. else
  265. {
  266. // This should be adjusted to run from the
  267. // eye point to the object's center position. Though this
  268. // works well enough for now.
  269. F32 vertDist = mAimLocation.z - location.z;
  270. F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  271. F32 newPitch = mAtan2( horzDist, vertDist ) - ( M_PI_F / 2.0f );
  272. if (mFabs(newPitch) > 0.01f)
  273. {
  274. Point3F headRotation = getHeadRotation();
  275. movePtr->pitch = newPitch - headRotation.x;
  276. }
  277. }
  278. }
  279. }
  280. else
  281. {
  282. // Level out if we're not doing anything else
  283. Point3F headRotation = getHeadRotation();
  284. movePtr->pitch = -headRotation.x;
  285. }
  286. // Move towards the destination
  287. if (mMoveState != ModeStop)
  288. {
  289. F32 xDiff = mMoveDestination.x - location.x;
  290. F32 yDiff = mMoveDestination.y - location.y;
  291. // Check if we should mMove, or if we are 'close enough'
  292. if (mFabs(xDiff) < mMoveTolerance && mFabs(yDiff) < mMoveTolerance)
  293. {
  294. mMoveState = ModeStop;
  295. throwCallback("onReachDestination");
  296. }
  297. else
  298. {
  299. // Build move direction in world space
  300. if (mIsZero(xDiff))
  301. movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f;
  302. else
  303. if (mIsZero(yDiff))
  304. movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f;
  305. else
  306. if (mFabs(xDiff) > mFabs(yDiff))
  307. {
  308. F32 value = mFabs(yDiff / xDiff);
  309. movePtr->y = (location.y > mMoveDestination.y) ? -value : value;
  310. movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f;
  311. }
  312. else
  313. {
  314. F32 value = mFabs(xDiff / yDiff);
  315. movePtr->x = (location.x > mMoveDestination.x) ? -value : value;
  316. movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f;
  317. }
  318. // Rotate the move into object space (this really only needs
  319. // a 2D matrix)
  320. Point3F newMove;
  321. MatrixF moveMatrix;
  322. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  323. moveMatrix.mulV( Point3F( movePtr->x, movePtr->y, 0.0f ), &newMove );
  324. movePtr->x = newMove.x;
  325. movePtr->y = newMove.y;
  326. // Set movement speed. We'll slow down once we get close
  327. // to try and stop on the spot...
  328. if (mMoveSlowdown)
  329. {
  330. F32 speed = mMoveSpeed;
  331. F32 dist = mSqrt(xDiff*xDiff + yDiff*yDiff);
  332. F32 maxDist = 5.0f;
  333. if (dist < maxDist)
  334. speed *= dist / maxDist;
  335. movePtr->x *= speed;
  336. movePtr->y *= speed;
  337. mMoveState = ModeSlowing;
  338. }
  339. else
  340. {
  341. movePtr->x *= mMoveSpeed;
  342. movePtr->y *= mMoveSpeed;
  343. mMoveState = ModeMove;
  344. }
  345. if (mMoveStuckTestCountdown > 0)
  346. --mMoveStuckTestCountdown;
  347. else
  348. {
  349. // We should check to see if we are stuck...
  350. F32 locationDelta = (location - mLastLocation).len();
  351. if (locationDelta < mMoveStuckTolerance && mDamageState == Enabled)
  352. {
  353. // If we are slowing down, then it's likely that our location delta will be less than
  354. // our move stuck tolerance. Because we can be both slowing and stuck
  355. // we should TRY to check if we've moved. This could use better detection.
  356. if ( mMoveState != ModeSlowing || locationDelta == 0 )
  357. {
  358. mMoveState = ModeStuck;
  359. throwCallback("onMoveStuck");
  360. }
  361. }
  362. }
  363. }
  364. }
  365. // Test for target location in sight if it's an object. The LOS is
  366. // run from the eye position to the center of the object's bounding,
  367. // which is not very accurate.
  368. if (mAimObject) {
  369. MatrixF eyeMat;
  370. getEyeTransform(&eyeMat);
  371. eyeMat.getColumn(3,&location);
  372. Point3F targetLoc = mAimObject->getBoxCenter();
  373. // This ray ignores non-static shapes. Cast Ray returns true
  374. // if it hit something.
  375. RayInfo dummy;
  376. if (getContainer()->castRay( location, targetLoc,
  377. StaticShapeObjectType | StaticObjectType |
  378. TerrainObjectType, &dummy)) {
  379. if (mTargetInLOS) {
  380. throwCallback( "onTargetExitLOS" );
  381. mTargetInLOS = false;
  382. }
  383. }
  384. else
  385. if (!mTargetInLOS) {
  386. throwCallback( "onTargetEnterLOS" );
  387. mTargetInLOS = true;
  388. }
  389. }
  390. // Replicate the trigger state into the move so that
  391. // triggers can be controlled from scripts.
  392. for( int i = 0; i < MaxTriggerKeys; i++ )
  393. movePtr->trigger[i] = getImageTriggerState(i);
  394. mLastLocation = location;
  395. return true;
  396. }
  397. /**
  398. * Utility function to throw callbacks. Callbacks always occure
  399. * on the datablock class.
  400. *
  401. * @param name Name of script function to call
  402. */
  403. void AIPlayer::throwCallback( const char *name )
  404. {
  405. Con::executef(getDataBlock(), name, getIdString());
  406. }
  407. // --------------------------------------------------------------------------------------------
  408. // Console Functions
  409. // --------------------------------------------------------------------------------------------
  410. DefineEngineMethod( AIPlayer, stop, void, ( ),,
  411. "@brief Tells the AIPlayer to stop moving.\n\n")
  412. {
  413. object->stopMove();
  414. }
  415. DefineEngineMethod( AIPlayer, clearAim, void, ( ),,
  416. "@brief Use this to stop aiming at an object or a point.\n\n"
  417. "@see setAimLocation()\n"
  418. "@see setAimObject()\n")
  419. {
  420. object->clearAim();
  421. }
  422. DefineEngineMethod( AIPlayer, setMoveSpeed, void, ( F32 speed ),,
  423. "@brief Sets the move speed for an AI object.\n\n"
  424. "@param speed A speed multiplier between 0.0 and 1.0. "
  425. "This is multiplied by the AIPlayer's base movement rates (as defined in "
  426. "its PlayerData datablock)\n\n"
  427. "@see getMoveDestination()\n")
  428. {
  429. object->setMoveSpeed(speed);
  430. }
  431. DefineEngineMethod( AIPlayer, getMoveSpeed, F32, ( ),,
  432. "@brief Gets the move speed of an AI object.\n\n"
  433. "@return A speed multiplier between 0.0 and 1.0.\n\n"
  434. "@see setMoveSpeed()\n")
  435. {
  436. return object->getMoveSpeed();
  437. }
  438. DefineEngineMethod( AIPlayer, setMoveDestination, void, ( Point3F goal, bool slowDown ), ( true ),
  439. "@brief Tells the AI to move to the location provided\n\n"
  440. "@param goal Coordinates in world space representing location to move to.\n"
  441. "@param slowDown A boolean value. If set to true, the bot will slow down "
  442. "when it gets within 5-meters of its move destination. If false, the bot "
  443. "will stop abruptly when it reaches the move destination. By default, this is true.\n\n"
  444. "@note Upon reaching a move destination, the bot will clear its move destination and "
  445. "calls to getMoveDestination will return \"0 0 0\"."
  446. "@see getMoveDestination()\n")
  447. {
  448. object->setMoveDestination( goal, slowDown);
  449. }
  450. DefineEngineMethod( AIPlayer, getMoveDestination, Point3F, (),,
  451. "@brief Get the AIPlayer's current destination.\n\n"
  452. "@return Returns a point containing the \"x y z\" position "
  453. "of the AIPlayer's current move destination. If no move destination "
  454. "has yet been set, this returns \"0 0 0\"."
  455. "@see setMoveDestination()\n")
  456. {
  457. return object->getMoveDestination();
  458. }
  459. DefineEngineMethod( AIPlayer, setAimLocation, void, ( Point3F target ),,
  460. "@brief Tells the AIPlayer to aim at the location provided.\n\n"
  461. "@param target An \"x y z\" position in the game world to target.\n\n"
  462. "@see getAimLocation()\n")
  463. {
  464. object->setAimLocation(target);
  465. }
  466. DefineEngineMethod( AIPlayer, getAimLocation, Point3F, (),,
  467. "@brief Returns the point the AIPlayer is aiming at.\n\n"
  468. "This will reflect the position set by setAimLocation(), "
  469. "or the position of the object that the bot is now aiming at. "
  470. "If the bot is not aiming at anything, this value will "
  471. "change to whatever point the bot's current line-of-sight intercepts."
  472. "@return World space coordinates of the object AI is aiming at. Formatted as \"X Y Z\".\n\n"
  473. "@see setAimLocation()\n"
  474. "@see setAimObject()\n")
  475. {
  476. return object->getAimLocation();
  477. }
  478. ConsoleDocFragment _setAimObject(
  479. "@brief Sets the AIPlayer's target object. May optionally set an offset from target location\n\n"
  480. "@param targetObject The object to target\n"
  481. "@param offset Optional three-element offset vector which will be added to the position of the aim object.\n\n"
  482. "@tsexample\n"
  483. "// Without an offset\n"
  484. "%ai.setAimObject(%target);\n\n"
  485. "// With an offset\n"
  486. "// Cause our AI object to aim at the target\n"
  487. "// offset (0, 0, 1) so you don't aim at the target's feet\n"
  488. "%ai.setAimObject(%target, \"0 0 1\");\n"
  489. "@endtsexample\n\n"
  490. "@see getAimLocation()\n"
  491. "@see getAimObject()\n"
  492. "@see clearAim()\n",
  493. "AIPlayer",
  494. "void setAimObject(GameBase targetObject, Point3F offset);"
  495. );
  496. ConsoleMethod( AIPlayer, setAimObject, void, 3, 4, "( GameBase obj, [Point3F offset] )"
  497. "Sets the bot's target object. Optionally set an offset from target location."
  498. "@hide")
  499. {
  500. Point3F off( 0.0f, 0.0f, 0.0f );
  501. // Find the target
  502. GameBase *targetObject;
  503. if( Sim::findObject( argv[2], targetObject ) )
  504. {
  505. if (argc == 4)
  506. dSscanf( argv[3], "%g %g %g", &off.x, &off.y, &off.z );
  507. object->setAimObject( targetObject, off );
  508. }
  509. else
  510. object->setAimObject( 0, off );
  511. }
  512. DefineEngineMethod( AIPlayer, getAimObject, S32, (),,
  513. "@brief Gets the object the AIPlayer is targeting.\n\n"
  514. "@return Returns -1 if no object is being aimed at, "
  515. "or the SimObjectID of the object the AIPlayer is aiming at.\n\n"
  516. "@see setAimObject()\n")
  517. {
  518. GameBase* obj = object->getAimObject();
  519. return obj? obj->getId(): -1;
  520. }