aiPlayer.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  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. #include <cfloat>
  29. static U32 sAIPlayerLoSMask = TerrainObjectType | StaticShapeObjectType | StaticObjectType;
  30. IMPLEMENT_CO_NETOBJECT_V1(AIPlayer);
  31. ConsoleDocClass( AIPlayer,
  32. "@brief A Player object not controlled by conventional input, but by an AI engine.\n\n"
  33. "The AIPlayer provides a Player object that may be controlled from script. You control "
  34. "where the player moves and how fast. You may also set where the AIPlayer is aiming at "
  35. "-- either a location or another game object.\n\n"
  36. "The AIPlayer class does not have a datablock of its own. It makes use of the PlayerData "
  37. "datablock to define how it looks, etc. As the AIPlayer is an extension of the Player class "
  38. "it can mount objects and fire weapons, or mount vehicles and drive them.\n\n"
  39. "While the PlayerData datablock is used, there are a number of additional callbacks that are "
  40. "implemented by AIPlayer on the datablock. These are listed here:\n\n"
  41. "void onReachDestination(AIPlayer obj) \n"
  42. "Called when the player has reached its set destination using the setMoveDestination() method. "
  43. "The actual point at which this callback is called is when the AIPlayer is within the mMoveTolerance "
  44. "of the defined destination.\n\n"
  45. "void onMoveStuck(AIPlayer obj) \n"
  46. "While in motion, if an AIPlayer has moved less than moveStuckTolerance within a single tick, this "
  47. "callback is called. From here you could choose an alternate destination to get the AIPlayer moving "
  48. "again.\n\n"
  49. "void onTargetEnterLOS(AIPlayer obj) \n"
  50. "When an object is being aimed at (following a call to setAimObject()) and the targeted object enters "
  51. "the AIPlayer's line of sight, this callback is called. The LOS test is a ray from the AIPlayer's eye "
  52. "position to the center of the target's bounding box. The LOS ray test only checks against interiors, "
  53. "statis shapes, and terrain.\n\n"
  54. "void onTargetExitLOS(AIPlayer obj) \n"
  55. "When an object is being aimed at (following a call to setAimObject()) and the targeted object leaves "
  56. "the AIPlayer's line of sight, this callback is called. The LOS test is a ray from the AIPlayer's eye "
  57. "position to the center of the target's bounding box. The LOS ray test only checks against interiors, "
  58. "statis shapes, and terrain.\n\n"
  59. "@tsexample\n"
  60. "// Create the demo player object\n"
  61. "%player = new AiPlayer()\n"
  62. "{\n"
  63. " dataBlock = DemoPlayer;\n"
  64. " path = \"\";\n"
  65. "};\n"
  66. "@endtsexample\n\n"
  67. "@see Player for a list of all inherited functions, variables, and base description\n"
  68. "@ingroup AI\n"
  69. "@ingroup gameObjects\n");
  70. /**
  71. * Constructor
  72. */
  73. AIPlayer::AIPlayer()
  74. {
  75. mMoveDestination.set( 0.0f, 0.0f, 0.0f );
  76. mMoveSpeed = 1.0f;
  77. mMoveTolerance = 0.25f;
  78. mMoveStuckTolerance = 0.01f;
  79. mMoveStuckTestDelay = 30;
  80. mMoveStuckTestCountdown = 0;
  81. mMoveSlowdown = true;
  82. mMoveState = ModeStop;
  83. mAimObject = 0;
  84. mAimLocationSet = false;
  85. mTargetInLOS = false;
  86. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  87. #ifdef TORQUE_NAVIGATION_ENABLED
  88. mJump = None;
  89. mNavSize = Regular;
  90. mLinkTypes = LinkData(AllFlags);
  91. #endif
  92. mIsAiControlled = true;
  93. for( S32 i = 0; i < MaxTriggerKeys; i ++ )
  94. mMoveTriggers[ i ] = false;
  95. }
  96. /**
  97. * Destructor
  98. */
  99. AIPlayer::~AIPlayer()
  100. {
  101. }
  102. void AIPlayer::initPersistFields()
  103. {
  104. addGroup( "AI" );
  105. addField( "mMoveTolerance", TypeF32, Offset( mMoveTolerance, AIPlayer ),
  106. "@brief Distance from destination before stopping.\n\n"
  107. "When the AIPlayer is moving to a given destination it will move to within "
  108. "this distance of the destination and then stop. By providing this tolerance "
  109. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  110. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  111. addField( "moveStuckTolerance", TypeF32, Offset( mMoveStuckTolerance, AIPlayer ),
  112. "@brief Distance tolerance on stuck check.\n\n"
  113. "When the AIPlayer is moving to a given destination, if it ever moves less than "
  114. "this tolerance during a single tick, the AIPlayer is considered stuck. At this point "
  115. "the onMoveStuck() callback is called on the datablock.\n");
  116. addField( "moveStuckTestDelay", TypeS32, Offset( mMoveStuckTestDelay, AIPlayer ),
  117. "@brief The number of ticks to wait before testing if the AIPlayer is stuck.\n\n"
  118. "When the AIPlayer is asked to move, this property is the number of ticks to wait "
  119. "before the AIPlayer starts to check if it is stuck. This delay allows the AIPlayer "
  120. "to accelerate to full speed without its initial slow start being considered as stuck.\n"
  121. "@note Set to zero to have the stuck test start immediately.\n");
  122. addField( "AttackRadius", TypeF32, Offset( mAttackRadius, AIPlayer ),
  123. "@brief Distance considered in firing range for callback purposes.");
  124. endGroup( "AI" );
  125. #ifdef TORQUE_NAVIGATION_ENABLED
  126. addGroup("Pathfinding");
  127. addField("allowWalk", TypeBool, Offset(mLinkTypes.walk, AIPlayer),
  128. "Allow the character to walk on dry land.");
  129. addField("allowJump", TypeBool, Offset(mLinkTypes.jump, AIPlayer),
  130. "Allow the character to use jump links.");
  131. addField("allowDrop", TypeBool, Offset(mLinkTypes.drop, AIPlayer),
  132. "Allow the character to use drop links.");
  133. addField("allowSwim", TypeBool, Offset(mLinkTypes.swim, AIPlayer),
  134. "Allow the character to move in water.");
  135. addField("allowLedge", TypeBool, Offset(mLinkTypes.ledge, AIPlayer),
  136. "Allow the character to jump ledges.");
  137. addField("allowClimb", TypeBool, Offset(mLinkTypes.climb, AIPlayer),
  138. "Allow the character to use climb links.");
  139. addField("allowTeleport", TypeBool, Offset(mLinkTypes.teleport, AIPlayer),
  140. "Allow the character to use teleporters.");
  141. endGroup("Pathfinding");
  142. #endif // TORQUE_NAVIGATION_ENABLED
  143. Parent::initPersistFields();
  144. }
  145. bool AIPlayer::onAdd()
  146. {
  147. if (!Parent::onAdd())
  148. return false;
  149. // Use the eye as the current position (see getAIMove)
  150. MatrixF eye;
  151. getEyeTransform(&eye);
  152. mLastLocation = eye.getPosition();
  153. return true;
  154. }
  155. void AIPlayer::onRemove()
  156. {
  157. #ifdef TORQUE_NAVIGATION_ENABLED
  158. clearPath();
  159. clearCover();
  160. clearFollow();
  161. #endif
  162. Parent::onRemove();
  163. }
  164. /**
  165. * Sets the speed at which this AI moves
  166. *
  167. * @param speed Speed to move, default player was 10
  168. */
  169. void AIPlayer::setMoveSpeed( F32 speed )
  170. {
  171. mMoveSpeed = getMax(0.0f, getMin( 1.0f, speed ));
  172. }
  173. /**
  174. * Stops movement for this AI
  175. */
  176. void AIPlayer::stopMove()
  177. {
  178. mMoveState = ModeStop;
  179. #ifdef TORQUE_NAVIGATION_ENABLED
  180. clearPath();
  181. clearCover();
  182. clearFollow();
  183. #endif
  184. }
  185. /**
  186. * Sets how far away from the move location is considered
  187. * "on target"
  188. *
  189. * @param tolerance Movement tolerance for error
  190. */
  191. void AIPlayer::setMoveTolerance( const F32 tolerance )
  192. {
  193. mMoveTolerance = getMax( 0.1f, tolerance );
  194. }
  195. /**
  196. * Sets the location for the bot to run to
  197. *
  198. * @param location Point to run to
  199. */
  200. void AIPlayer::setMoveDestination( const Point3F &location, bool slowdown )
  201. {
  202. mMoveDestination = location;
  203. mMoveState = ModeMove;
  204. mMoveSlowdown = slowdown;
  205. mMoveStuckTestCountdown = mMoveStuckTestDelay;
  206. }
  207. /**
  208. * Sets the object the bot is targeting
  209. *
  210. * @param targetObject The object to target
  211. */
  212. void AIPlayer::setAimObject( GameBase *targetObject )
  213. {
  214. mAimObject = targetObject;
  215. mTargetInLOS = false;
  216. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  217. }
  218. /**
  219. * Sets the object the bot is targeting and an offset to add to target location
  220. *
  221. * @param targetObject The object to target
  222. * @param offset The offest from the target location to aim at
  223. */
  224. void AIPlayer::setAimObject(GameBase *targetObject, const Point3F& offset)
  225. {
  226. mAimObject = targetObject;
  227. mTargetInLOS = false;
  228. mAimOffset = offset;
  229. }
  230. /**
  231. * Sets the location for the bot to aim at
  232. *
  233. * @param location Point to aim at
  234. */
  235. void AIPlayer::setAimLocation( const Point3F &location )
  236. {
  237. mAimObject = 0;
  238. mAimLocationSet = true;
  239. mAimLocation = location;
  240. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  241. }
  242. /**
  243. * Clears the aim location and sets it to the bot's
  244. * current destination so he looks where he's going
  245. */
  246. void AIPlayer::clearAim()
  247. {
  248. mAimObject = 0;
  249. mAimLocationSet = false;
  250. mAimOffset = Point3F(0.0f, 0.0f, 0.0f);
  251. }
  252. /**
  253. * Set the state of a movement trigger.
  254. *
  255. * @param slot The trigger slot to set
  256. * @param isSet set/unset the trigger
  257. */
  258. void AIPlayer::setMoveTrigger( U32 slot, const bool isSet )
  259. {
  260. if(slot >= MaxTriggerKeys)
  261. {
  262. Con::errorf("Attempting to set an invalid trigger slot (%i)", slot);
  263. }
  264. else
  265. {
  266. mMoveTriggers[ slot ] = isSet; // set the trigger
  267. setMaskBits(NoWarpMask); // force the client to updateMove
  268. }
  269. }
  270. /**
  271. * Get the state of a movement trigger.
  272. *
  273. * @param slot The trigger slot to query
  274. * @return True if the trigger is set, false if it is not set
  275. */
  276. bool AIPlayer::getMoveTrigger( U32 slot ) const
  277. {
  278. if(slot >= MaxTriggerKeys)
  279. {
  280. Con::errorf("Attempting to get an invalid trigger slot (%i)", slot);
  281. return false;
  282. }
  283. else
  284. {
  285. return mMoveTriggers[ slot ];
  286. }
  287. }
  288. /**
  289. * Clear the trigger state for all movement triggers.
  290. */
  291. void AIPlayer::clearMoveTriggers()
  292. {
  293. for( U32 i = 0; i < MaxTriggerKeys; i ++ )
  294. setMoveTrigger( i, false );
  295. }
  296. /**
  297. * This method calculates the moves for the AI player
  298. *
  299. * @param movePtr Pointer to move the move list into
  300. */
  301. bool AIPlayer::getAIMove(Move *movePtr)
  302. {
  303. *movePtr = NullMove;
  304. // Use the eye as the current position.
  305. MatrixF eye;
  306. getEyeTransform(&eye);
  307. Point3F location = eye.getPosition();
  308. Point3F rotation = getRotation();
  309. #ifdef TORQUE_NAVIGATION_ENABLED
  310. if(mDamageState == Enabled)
  311. {
  312. if(mMoveState != ModeStop)
  313. updateNavMesh();
  314. if(!mFollowData.object.isNull())
  315. {
  316. if(mPathData.path.isNull())
  317. {
  318. if((getPosition() - mFollowData.object->getPosition()).len() > mFollowData.radius)
  319. followObject(mFollowData.object, mFollowData.radius);
  320. }
  321. else
  322. {
  323. if((mPathData.path->mTo - mFollowData.object->getPosition()).len() > mFollowData.radius)
  324. repath();
  325. else if((getPosition() - mFollowData.object->getPosition()).len() < mFollowData.radius)
  326. {
  327. clearPath();
  328. mMoveState = ModeStop;
  329. throwCallback("onTargetInRange");
  330. }
  331. else if((getPosition() - mFollowData.object->getPosition()).len() < mAttackRadius)
  332. {
  333. throwCallback("onTargetInFiringRange");
  334. }
  335. }
  336. }
  337. }
  338. #endif // TORQUE_NAVIGATION_ENABLED
  339. // Orient towards the aim point, aim object, or towards
  340. // our destination.
  341. if (mAimObject || mAimLocationSet || mMoveState != ModeStop)
  342. {
  343. // Update the aim position if we're aiming for an object
  344. if (mAimObject)
  345. mAimLocation = mAimObject->getPosition() + mAimOffset;
  346. else
  347. if (!mAimLocationSet)
  348. mAimLocation = mMoveDestination;
  349. F32 xDiff = mAimLocation.x - location.x;
  350. F32 yDiff = mAimLocation.y - location.y;
  351. if (!mIsZero(xDiff) || !mIsZero(yDiff))
  352. {
  353. // First do Yaw
  354. // use the cur yaw between -Pi and Pi
  355. F32 curYaw = rotation.z;
  356. while (curYaw > M_2PI_F)
  357. curYaw -= M_2PI_F;
  358. while (curYaw < -M_2PI_F)
  359. curYaw += M_2PI_F;
  360. // find the yaw offset
  361. F32 newYaw = mAtan2( xDiff, yDiff );
  362. F32 yawDiff = newYaw - curYaw;
  363. // make it between 0 and 2PI
  364. if( yawDiff < 0.0f )
  365. yawDiff += M_2PI_F;
  366. else if( yawDiff >= M_2PI_F )
  367. yawDiff -= M_2PI_F;
  368. // now make sure we take the short way around the circle
  369. if( yawDiff > M_PI_F )
  370. yawDiff -= M_2PI_F;
  371. else if( yawDiff < -M_PI_F )
  372. yawDiff += M_2PI_F;
  373. movePtr->yaw = yawDiff;
  374. // Next do pitch.
  375. if (!mAimObject && !mAimLocationSet)
  376. {
  377. // Level out if were just looking at our next way point.
  378. Point3F headRotation = getHeadRotation();
  379. movePtr->pitch = -headRotation.x;
  380. }
  381. else
  382. {
  383. // This should be adjusted to run from the
  384. // eye point to the object's center position. Though this
  385. // works well enough for now.
  386. F32 vertDist = mAimLocation.z - location.z;
  387. F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  388. F32 newPitch = mAtan2( horzDist, vertDist ) - ( M_PI_F / 2.0f );
  389. if (mFabs(newPitch) > 0.01f)
  390. {
  391. Point3F headRotation = getHeadRotation();
  392. movePtr->pitch = newPitch - headRotation.x;
  393. }
  394. }
  395. }
  396. }
  397. else
  398. {
  399. // Level out if we're not doing anything else
  400. Point3F headRotation = getHeadRotation();
  401. movePtr->pitch = -headRotation.x;
  402. }
  403. // Move towards the destination
  404. if (mMoveState != ModeStop)
  405. {
  406. F32 xDiff = mMoveDestination.x - location.x;
  407. F32 yDiff = mMoveDestination.y - location.y;
  408. // Check if we should mMove, or if we are 'close enough'
  409. if (mFabs(xDiff) < mMoveTolerance && mFabs(yDiff) < mMoveTolerance)
  410. {
  411. mMoveState = ModeStop;
  412. onReachDestination();
  413. }
  414. else
  415. {
  416. // Build move direction in world space
  417. if (mIsZero(xDiff))
  418. movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f;
  419. else
  420. if (mIsZero(yDiff))
  421. movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f;
  422. else
  423. if (mFabs(xDiff) > mFabs(yDiff))
  424. {
  425. F32 value = mFabs(yDiff / xDiff);
  426. movePtr->y = (location.y > mMoveDestination.y) ? -value : value;
  427. movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f;
  428. }
  429. else
  430. {
  431. F32 value = mFabs(xDiff / yDiff);
  432. movePtr->x = (location.x > mMoveDestination.x) ? -value : value;
  433. movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f;
  434. }
  435. // Rotate the move into object space (this really only needs
  436. // a 2D matrix)
  437. Point3F newMove;
  438. MatrixF moveMatrix;
  439. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  440. moveMatrix.mulV( Point3F( movePtr->x, movePtr->y, 0.0f ), &newMove );
  441. movePtr->x = newMove.x;
  442. movePtr->y = newMove.y;
  443. // Set movement speed. We'll slow down once we get close
  444. // to try and stop on the spot...
  445. if (mMoveSlowdown)
  446. {
  447. F32 speed = mMoveSpeed;
  448. F32 dist = mSqrt(xDiff*xDiff + yDiff*yDiff);
  449. F32 maxDist = mMoveTolerance*2;
  450. if (dist < maxDist)
  451. speed *= dist / maxDist;
  452. movePtr->x *= speed;
  453. movePtr->y *= speed;
  454. mMoveState = ModeSlowing;
  455. }
  456. else
  457. {
  458. movePtr->x *= mMoveSpeed;
  459. movePtr->y *= mMoveSpeed;
  460. mMoveState = ModeMove;
  461. }
  462. if (mMoveStuckTestCountdown > 0)
  463. --mMoveStuckTestCountdown;
  464. else
  465. {
  466. // We should check to see if we are stuck...
  467. F32 locationDelta = (location - mLastLocation).len();
  468. if (locationDelta < mMoveStuckTolerance && mDamageState == Enabled)
  469. {
  470. // If we are slowing down, then it's likely that our location delta will be less than
  471. // our move stuck tolerance. Because we can be both slowing and stuck
  472. // we should TRY to check if we've moved. This could use better detection.
  473. if ( mMoveState != ModeSlowing || locationDelta == 0 )
  474. {
  475. mMoveState = ModeStuck;
  476. onStuck();
  477. }
  478. }
  479. }
  480. }
  481. }
  482. // Test for target location in sight if it's an object. The LOS is
  483. // run from the eye position to the center of the object's bounding,
  484. // which is not very accurate.
  485. if (mAimObject)
  486. {
  487. if (checkInLos(mAimObject.getPointer()))
  488. {
  489. if (!mTargetInLOS)
  490. {
  491. throwCallback( "onTargetEnterLOS" );
  492. mTargetInLOS = true;
  493. }
  494. }
  495. else if (mTargetInLOS)
  496. {
  497. throwCallback( "onTargetExitLOS" );
  498. mTargetInLOS = false;
  499. }
  500. }
  501. Pose desiredPose = mPose;
  502. if ( mSwimming )
  503. desiredPose = SwimPose;
  504. else if ( mAiPose == 1 && canCrouch() )
  505. desiredPose = CrouchPose;
  506. else if ( mAiPose == 2 && canProne() )
  507. desiredPose = PronePose;
  508. else if ( mAiPose == 3 && canSprint() )
  509. desiredPose = SprintPose;
  510. else if ( canStand() )
  511. desiredPose = StandPose;
  512. setPose( desiredPose );
  513. // Replicate the trigger state into the move so that
  514. // triggers can be controlled from scripts.
  515. for( U32 i = 0; i < MaxTriggerKeys; i++ )
  516. movePtr->trigger[ i ] = mMoveTriggers[ i ];
  517. #ifdef TORQUE_NAVIGATION_ENABLED
  518. if(mJump == Now)
  519. {
  520. movePtr->trigger[2] = true;
  521. mJump = None;
  522. }
  523. else if(mJump == Ledge)
  524. {
  525. // If we're not touching the ground, jump!
  526. RayInfo info;
  527. if(!getContainer()->castRay(getPosition(), getPosition() - Point3F(0, 0, 0.4f), StaticShapeObjectType, &info))
  528. {
  529. movePtr->trigger[2] = true;
  530. mJump = None;
  531. }
  532. }
  533. #endif // TORQUE_NAVIGATION_ENABLED
  534. mLastLocation = location;
  535. return true;
  536. }
  537. void AIPlayer::updateMove(const Move* move)
  538. {
  539. if (!getControllingClient() && isGhost())
  540. return;
  541. Parent::updateMove(move);
  542. }
  543. void AIPlayer::setAiPose( S32 pose )
  544. {
  545. if (!getControllingClient() && isGhost())
  546. return;
  547. mAiPose = pose;
  548. }
  549. S32 AIPlayer::getAiPose()
  550. {
  551. return mAiPose;
  552. }
  553. /**
  554. * Utility function to throw callbacks. Callbacks always occure
  555. * on the datablock class.
  556. *
  557. * @param name Name of script function to call
  558. */
  559. void AIPlayer::throwCallback( const char *name )
  560. {
  561. Con::executef(getDataBlock(), name, getIdString());
  562. }
  563. /**
  564. * Called when we get within mMoveTolerance of our destination set using
  565. * setMoveDestination(). Only fires the script callback if we are at the end
  566. * of a pathfinding path, or have no pathfinding path.
  567. */
  568. void AIPlayer::onReachDestination()
  569. {
  570. #ifdef TORQUE_NAVIGATION_ENABLED
  571. if(!mPathData.path.isNull())
  572. {
  573. if(mPathData.index == mPathData.path->size() - 1)
  574. {
  575. // Handle looping paths.
  576. if(mPathData.path->mIsLooping)
  577. moveToNode(0);
  578. // Otherwise end path.
  579. else
  580. {
  581. clearPath();
  582. throwCallback("onReachDestination");
  583. }
  584. }
  585. else
  586. {
  587. moveToNode(mPathData.index + 1);
  588. // Throw callback every time if we're on a looping path.
  589. //if(mPathData.path->mIsLooping)
  590. //throwCallback("onReachDestination");
  591. }
  592. }
  593. else
  594. #endif
  595. throwCallback("onReachDestination");
  596. }
  597. /**
  598. * Called when we move less than mMoveStuckTolerance in a tick, signalling
  599. * that some obstacle is preventing us from getting where we need to go.
  600. */
  601. void AIPlayer::onStuck()
  602. {
  603. #ifdef TORQUE_NAVIGATION_ENABLED
  604. if(!mPathData.path.isNull())
  605. repath();
  606. else
  607. #endif
  608. throwCallback("onMoveStuck");
  609. }
  610. #ifdef TORQUE_NAVIGATION_ENABLED
  611. // --------------------------------------------------------------------------------------------
  612. // Pathfinding
  613. // --------------------------------------------------------------------------------------------
  614. void AIPlayer::clearPath()
  615. {
  616. // Only delete if we own the path.
  617. if(!mPathData.path.isNull() && mPathData.owned)
  618. mPathData.path->deleteObject();
  619. // Reset path data.
  620. mPathData = PathData();
  621. }
  622. void AIPlayer::clearCover()
  623. {
  624. // Notify cover that we are no longer on our way.
  625. if(!mCoverData.cover.isNull())
  626. mCoverData.cover->setOccupied(false);
  627. mCoverData = CoverData();
  628. }
  629. void AIPlayer::clearFollow()
  630. {
  631. mFollowData = FollowData();
  632. }
  633. void AIPlayer::moveToNode(S32 node)
  634. {
  635. if(mPathData.path.isNull())
  636. return;
  637. // -1 is shorthand for 'last path node'.
  638. if(node == -1)
  639. node = mPathData.path->size() - 1;
  640. // Consider slowing down on the last path node.
  641. setMoveDestination(mPathData.path->getNode(node), false);
  642. // Check flags for this segment.
  643. if(mPathData.index)
  644. {
  645. U16 flags = mPathData.path->getFlags(node - 1);
  646. // Jump if we must.
  647. if(flags & LedgeFlag)
  648. mJump = Ledge;
  649. else if(flags & JumpFlag)
  650. mJump = Now;
  651. else
  652. // Catch pathing errors.
  653. mJump = None;
  654. }
  655. // Store current index.
  656. mPathData.index = node;
  657. }
  658. bool AIPlayer::setPathDestination(const Point3F &pos)
  659. {
  660. // Pathfinding only happens on the server.
  661. if(!isServerObject())
  662. return false;
  663. if(!getNavMesh())
  664. updateNavMesh();
  665. // If we can't find a mesh, just move regularly.
  666. if(!getNavMesh())
  667. {
  668. //setMoveDestination(pos);
  669. throwCallback("onPathFailed");
  670. return false;
  671. }
  672. // Create a new path.
  673. NavPath *path = new NavPath();
  674. path->mMesh = getNavMesh();
  675. path->mFrom = getPosition();
  676. path->mTo = pos;
  677. path->mFromSet = path->mToSet = true;
  678. path->mAlwaysRender = true;
  679. path->mLinkTypes = mLinkTypes;
  680. path->mXray = true;
  681. // Paths plan automatically upon being registered.
  682. if(!path->registerObject())
  683. {
  684. delete path;
  685. return false;
  686. }
  687. if(path->success())
  688. {
  689. // Clear any current path we might have.
  690. clearPath();
  691. clearCover();
  692. clearFollow();
  693. // Store new path.
  694. mPathData.path = path;
  695. mPathData.owned = true;
  696. // Skip node 0, which we are currently standing on.
  697. moveToNode(1);
  698. throwCallback("onPathSuccess");
  699. return true;
  700. }
  701. else
  702. {
  703. // Just move normally if we can't path.
  704. //setMoveDestination(pos, true);
  705. //return;
  706. throwCallback("onPathFailed");
  707. path->deleteObject();
  708. return false;
  709. }
  710. }
  711. DefineEngineMethod(AIPlayer, setPathDestination, bool, (Point3F goal),,
  712. "@brief Tells the AI to find a path to the location provided\n\n"
  713. "@param goal Coordinates in world space representing location to move to.\n"
  714. "@return True if a path was found.\n\n"
  715. "@see getPathDestination()\n"
  716. "@see setMoveDestination()\n")
  717. {
  718. return object->setPathDestination(goal);
  719. }
  720. Point3F AIPlayer::getPathDestination() const
  721. {
  722. if(!mPathData.path.isNull())
  723. return mPathData.path->mTo;
  724. return Point3F(0, 0, 0);
  725. }
  726. DefineEngineMethod(AIPlayer, getPathDestination, Point3F, (),,
  727. "@brief Get the AIPlayer's current pathfinding destination.\n\n"
  728. "@return Returns a point containing the \"x y z\" position "
  729. "of the AIPlayer's current path destination. If no path destination "
  730. "has yet been set, this returns \"0 0 0\"."
  731. "@see setPathDestination()\n")
  732. {
  733. return object->getPathDestination();
  734. }
  735. void AIPlayer::followNavPath(NavPath *path)
  736. {
  737. if(!isServerObject())
  738. return;
  739. // Get rid of our current path.
  740. clearPath();
  741. clearCover();
  742. clearFollow();
  743. // Follow new path.
  744. mPathData.path = path;
  745. mPathData.owned = false;
  746. // Start from 0 since we might not already be there.
  747. moveToNode(0);
  748. }
  749. DefineEngineMethod(AIPlayer, followNavPath, void, (SimObjectId obj),,
  750. "@brief Tell the AIPlayer to follow a path.\n\n"
  751. "@param obj ID of a NavPath object for the character to follow.")
  752. {
  753. NavPath *path;
  754. if(Sim::findObject(obj, path))
  755. object->followNavPath(path);
  756. }
  757. void AIPlayer::followObject(SceneObject *obj, F32 radius)
  758. {
  759. if(!isServerObject())
  760. return;
  761. if ((mFollowData.lastPos - obj->getPosition()).len()<mMoveTolerance)
  762. return;
  763. if(setPathDestination(obj->getPosition()))
  764. {
  765. clearCover();
  766. mFollowData.object = obj;
  767. mFollowData.radius = radius;
  768. mFollowData.lastPos = obj->getPosition();
  769. }
  770. }
  771. DefineEngineMethod(AIPlayer, followObject, void, (SimObjectId obj, F32 radius),,
  772. "@brief Tell the AIPlayer to follow another object.\n\n"
  773. "@param obj ID of the object to follow.\n"
  774. "@param radius Maximum distance we let the target escape to.")
  775. {
  776. SceneObject *follow;
  777. object->clearPath();
  778. object->clearCover();
  779. object->clearFollow();
  780. if(Sim::findObject(obj, follow))
  781. object->followObject(follow, radius);
  782. }
  783. void AIPlayer::repath()
  784. {
  785. // Ineffectual if we don't have a path, or are using someone else's.
  786. if(mPathData.path.isNull() || !mPathData.owned)
  787. return;
  788. // If we're following, get their position.
  789. if(!mFollowData.object.isNull())
  790. mPathData.path->mTo = mFollowData.object->getPosition();
  791. // Update from position and replan.
  792. mPathData.path->mFrom = getPosition();
  793. mPathData.path->plan();
  794. // Move to first node (skip start pos).
  795. moveToNode(1);
  796. }
  797. DefineEngineMethod(AIPlayer, repath, void, (),,
  798. "@brief Tells the AI to re-plan its path. Does nothing if the character "
  799. "has no path, or if it is following a mission path.\n\n")
  800. {
  801. object->repath();
  802. }
  803. struct CoverSearch
  804. {
  805. Point3F loc;
  806. Point3F from;
  807. F32 dist;
  808. F32 best;
  809. CoverPoint *point;
  810. CoverSearch() : loc(0, 0, 0), from(0, 0, 0)
  811. {
  812. best = -FLT_MAX;
  813. point = NULL;
  814. dist = FLT_MAX;
  815. }
  816. };
  817. static void findCoverCallback(SceneObject *obj, void *key)
  818. {
  819. CoverPoint *p = dynamic_cast<CoverPoint*>(obj);
  820. if(!p || p->isOccupied())
  821. return;
  822. CoverSearch *s = static_cast<CoverSearch*>(key);
  823. Point3F dir = s->from - p->getPosition();
  824. dir.normalizeSafe();
  825. // Score first based on angle of cover point to enemy.
  826. F32 score = mDot(p->getNormal(), dir);
  827. // Score also based on distance from seeker.
  828. score -= (p->getPosition() - s->loc).len() / s->dist;
  829. // Finally, consider cover size.
  830. score += (p->getSize() + 1) / CoverPoint::NumSizes;
  831. score *= p->getQuality();
  832. if(score > s->best)
  833. {
  834. s->best = score;
  835. s->point = p;
  836. }
  837. }
  838. bool AIPlayer::findCover(const Point3F &from, F32 radius)
  839. {
  840. if(radius <= 0)
  841. return false;
  842. // Create a search state.
  843. CoverSearch s;
  844. s.loc = getPosition();
  845. s.dist = radius;
  846. // Direction we seek cover FROM.
  847. s.from = from;
  848. // Find cover points.
  849. Box3F box(radius * 2.0f);
  850. box.setCenter(getPosition());
  851. getContainer()->findObjects(box, MarkerObjectType, findCoverCallback, &s);
  852. // Go to cover!
  853. if(s.point)
  854. {
  855. // Calling setPathDestination clears cover...
  856. bool foundPath = setPathDestination(s.point->getPosition());
  857. // Now store the cover info.
  858. mCoverData.cover = s.point;
  859. s.point->setOccupied(true);
  860. return foundPath;
  861. }
  862. return false;
  863. }
  864. DefineEngineMethod(AIPlayer, findCover, S32, (Point3F from, F32 radius),,
  865. "@brief Tells the AI to find cover nearby.\n\n"
  866. "@param from Location to find cover from (i.e., enemy position).\n"
  867. "@param radius Distance to search for cover.\n"
  868. "@return Cover point ID if cover was found, -1 otherwise.\n\n")
  869. {
  870. if(object->findCover(from, radius))
  871. {
  872. CoverPoint* cover = object->getCover();
  873. return cover ? cover->getId() : -1;
  874. }
  875. else
  876. {
  877. return -1;
  878. }
  879. }
  880. NavMesh *AIPlayer::findNavMesh() const
  881. {
  882. // Search for NavMeshes that contain us entirely with the smallest possible
  883. // volume.
  884. NavMesh *mesh = NULL;
  885. SimSet *set = NavMesh::getServerSet();
  886. for(U32 i = 0; i < set->size(); i++)
  887. {
  888. NavMesh *m = static_cast<NavMesh*>(set->at(i));
  889. if(m->getWorldBox().isContained(getWorldBox()))
  890. {
  891. // Check that mesh size is appropriate.
  892. if(mMount.object) // Should use isMounted() but it's not const. Grr.
  893. {
  894. if(!m->mVehicles)
  895. continue;
  896. }
  897. else
  898. {
  899. if(getNavSize() == Small && !m->mSmallCharacters ||
  900. getNavSize() == Regular && !m->mRegularCharacters ||
  901. getNavSize() == Large && !m->mLargeCharacters)
  902. continue;
  903. }
  904. if(!mesh || m->getWorldBox().getVolume() < mesh->getWorldBox().getVolume())
  905. mesh = m;
  906. }
  907. }
  908. return mesh;
  909. }
  910. DefineEngineMethod(AIPlayer, findNavMesh, S32, (),,
  911. "@brief Get the NavMesh object this AIPlayer is currently using.\n\n"
  912. "@return The ID of the NavPath object this character is using for "
  913. "pathfinding. This is determined by the character's location, "
  914. "navigation type and other factors. Returns -1 if no NavMesh is "
  915. "found.")
  916. {
  917. NavMesh *mesh = object->getNavMesh();
  918. return mesh ? mesh->getId() : -1;
  919. }
  920. void AIPlayer::updateNavMesh()
  921. {
  922. NavMesh *old = mNavMesh;
  923. if(mNavMesh.isNull())
  924. mNavMesh = findNavMesh();
  925. else
  926. {
  927. if(!mNavMesh->getWorldBox().isContained(getWorldBox()))
  928. mNavMesh = findNavMesh();
  929. }
  930. // See if we need to update our path.
  931. if(mNavMesh != old && !mPathData.path.isNull())
  932. {
  933. setPathDestination(mPathData.path->mTo);
  934. }
  935. }
  936. DefineEngineMethod(AIPlayer, getNavMesh, S32, (),,
  937. "@brief Return the NavMesh this AIPlayer is using to navigate.\n\n")
  938. {
  939. NavMesh *m = object->getNavMesh();
  940. return m ? m->getId() : 0;
  941. }
  942. DefineEngineMethod(AIPlayer, setNavSize, void, (const char *size),,
  943. "@brief Set the size of NavMesh this character uses. One of \"Small\", \"Regular\" or \"Large\".")
  944. {
  945. if(!dStrcmp(size, "Small"))
  946. object->setNavSize(AIPlayer::Small);
  947. else if(!dStrcmp(size, "Regular"))
  948. object->setNavSize(AIPlayer::Regular);
  949. else if(!dStrcmp(size, "Large"))
  950. object->setNavSize(AIPlayer::Large);
  951. else
  952. Con::errorf("AIPlayer::setNavSize: no such size '%s'.", size);
  953. }
  954. DefineEngineMethod(AIPlayer, getNavSize, const char*, (),,
  955. "@brief Return the size of NavMesh this character uses for pathfinding.")
  956. {
  957. switch(object->getNavSize())
  958. {
  959. case AIPlayer::Small:
  960. return "Small";
  961. case AIPlayer::Regular:
  962. return "Regular";
  963. case AIPlayer::Large:
  964. return "Large";
  965. }
  966. return "";
  967. }
  968. #endif // TORQUE_NAVIGATION_ENABLED
  969. // --------------------------------------------------------------------------------------------
  970. // Console Functions
  971. // --------------------------------------------------------------------------------------------
  972. DefineEngineMethod( AIPlayer, stop, void, ( ),,
  973. "@brief Tells the AIPlayer to stop moving.\n\n")
  974. {
  975. object->stopMove();
  976. }
  977. DefineEngineMethod( AIPlayer, clearAim, void, ( ),,
  978. "@brief Use this to stop aiming at an object or a point.\n\n"
  979. "@see setAimLocation()\n"
  980. "@see setAimObject()\n")
  981. {
  982. object->clearAim();
  983. }
  984. DefineEngineMethod( AIPlayer, setMoveSpeed, void, ( F32 speed ),,
  985. "@brief Sets the move speed for an AI object.\n\n"
  986. "@param speed A speed multiplier between 0.0 and 1.0. "
  987. "This is multiplied by the AIPlayer's base movement rates (as defined in "
  988. "its PlayerData datablock)\n\n"
  989. "@see getMoveDestination()\n")
  990. {
  991. object->setMoveSpeed(speed);
  992. }
  993. DefineEngineMethod( AIPlayer, getMoveSpeed, F32, ( ),,
  994. "@brief Gets the move speed of an AI object.\n\n"
  995. "@return A speed multiplier between 0.0 and 1.0.\n\n"
  996. "@see setMoveSpeed()\n")
  997. {
  998. return object->getMoveSpeed();
  999. }
  1000. DefineEngineMethod( AIPlayer, setMoveDestination, void, ( Point3F goal, bool slowDown ), ( true ),
  1001. "@brief Tells the AI to move to the location provided\n\n"
  1002. "@param goal Coordinates in world space representing location to move to.\n"
  1003. "@param slowDown A boolean value. If set to true, the bot will slow down "
  1004. "when it gets within 5-meters of its move destination. If false, the bot "
  1005. "will stop abruptly when it reaches the move destination. By default, this is true.\n\n"
  1006. "@note Upon reaching a move destination, the bot will clear its move destination and "
  1007. "calls to getMoveDestination will return \"0 0 0\"."
  1008. "@see getMoveDestination()\n")
  1009. {
  1010. object->setMoveDestination( goal, slowDown);
  1011. }
  1012. DefineEngineMethod( AIPlayer, getMoveDestination, Point3F, (),,
  1013. "@brief Get the AIPlayer's current destination.\n\n"
  1014. "@return Returns a point containing the \"x y z\" position "
  1015. "of the AIPlayer's current move destination. If no move destination "
  1016. "has yet been set, this returns \"0 0 0\"."
  1017. "@see setMoveDestination()\n")
  1018. {
  1019. return object->getMoveDestination();
  1020. }
  1021. DefineEngineMethod( AIPlayer, setAimLocation, void, ( Point3F target ),,
  1022. "@brief Tells the AIPlayer to aim at the location provided.\n\n"
  1023. "@param target An \"x y z\" position in the game world to target.\n\n"
  1024. "@see getAimLocation()\n")
  1025. {
  1026. object->setAimLocation(target);
  1027. }
  1028. DefineEngineMethod( AIPlayer, getAimLocation, Point3F, (),,
  1029. "@brief Returns the point the AIPlayer is aiming at.\n\n"
  1030. "This will reflect the position set by setAimLocation(), "
  1031. "or the position of the object that the bot is now aiming at. "
  1032. "If the bot is not aiming at anything, this value will "
  1033. "change to whatever point the bot's current line-of-sight intercepts."
  1034. "@return World space coordinates of the object AI is aiming at. Formatted as \"X Y Z\".\n\n"
  1035. "@see setAimLocation()\n"
  1036. "@see setAimObject()\n")
  1037. {
  1038. return object->getAimLocation();
  1039. }
  1040. ConsoleDocFragment _setAimObject(
  1041. "@brief Sets the AIPlayer's target object. May optionally set an offset from target location\n\n"
  1042. "@param targetObject The object to target\n"
  1043. "@param offset Optional three-element offset vector which will be added to the position of the aim object.\n\n"
  1044. "@tsexample\n"
  1045. "// Without an offset\n"
  1046. "%ai.setAimObject(%target);\n\n"
  1047. "// With an offset\n"
  1048. "// Cause our AI object to aim at the target\n"
  1049. "// offset (0, 0, 1) so you don't aim at the target's feet\n"
  1050. "%ai.setAimObject(%target, \"0 0 1\");\n"
  1051. "@endtsexample\n\n"
  1052. "@see getAimLocation()\n"
  1053. "@see getAimObject()\n"
  1054. "@see clearAim()\n",
  1055. "AIPlayer",
  1056. "void setAimObject(GameBase targetObject, Point3F offset);"
  1057. );
  1058. DefineConsoleMethod( AIPlayer, setAimObject, void, ( const char * objName, Point3F offset ), (Point3F::Zero), "( GameBase obj, [Point3F offset] )"
  1059. "Sets the bot's target object. Optionally set an offset from target location."
  1060. "@hide")
  1061. {
  1062. // Find the target
  1063. GameBase *targetObject;
  1064. if( Sim::findObject( objName, targetObject ) )
  1065. {
  1066. object->setAimObject( targetObject, offset );
  1067. }
  1068. else
  1069. object->setAimObject( 0, offset );
  1070. }
  1071. DefineEngineMethod( AIPlayer, getAimObject, S32, (),,
  1072. "@brief Gets the object the AIPlayer is targeting.\n\n"
  1073. "@return Returns -1 if no object is being aimed at, "
  1074. "or the SimObjectID of the object the AIPlayer is aiming at.\n\n"
  1075. "@see setAimObject()\n")
  1076. {
  1077. GameBase* obj = object->getAimObject();
  1078. return obj? obj->getId(): -1;
  1079. }
  1080. bool AIPlayer::checkInLos(GameBase* target, bool _useMuzzle, bool _checkEnabled)
  1081. {
  1082. if (!isServerObject()) return false;
  1083. if (!target)
  1084. {
  1085. target = mAimObject.getPointer();
  1086. if (!target)
  1087. return false;
  1088. }
  1089. if (_checkEnabled)
  1090. {
  1091. if (target->getTypeMask() & ShapeBaseObjectType)
  1092. {
  1093. ShapeBase *shapeBaseCheck = static_cast<ShapeBase *>(target);
  1094. if (shapeBaseCheck)
  1095. if (shapeBaseCheck->getDamageState() != Enabled) return false;
  1096. }
  1097. else
  1098. return false;
  1099. }
  1100. RayInfo ri;
  1101. disableCollision();
  1102. S32 mountCount = target->getMountedObjectCount();
  1103. for (S32 i = 0; i < mountCount; i++)
  1104. {
  1105. target->getMountedObject(i)->disableCollision();
  1106. }
  1107. Point3F checkPoint ;
  1108. if (_useMuzzle)
  1109. getMuzzlePointAI(0, &checkPoint );
  1110. else
  1111. {
  1112. MatrixF eyeMat;
  1113. getEyeTransform(&eyeMat);
  1114. eyeMat.getColumn(3, &checkPoint );
  1115. }
  1116. bool hit = !gServerContainer.castRay(checkPoint, target->getBoxCenter(), sAIPlayerLoSMask, &ri);
  1117. enableCollision();
  1118. for (S32 i = 0; i < mountCount; i++)
  1119. {
  1120. target->getMountedObject(i)->enableCollision();
  1121. }
  1122. return hit;
  1123. }
  1124. DefineEngineMethod(AIPlayer, checkInLos, bool, (ShapeBase* obj, bool useMuzzle, bool checkEnabled),(NULL, false, false),
  1125. "@brief Check whether an object is in line of sight.\n"
  1126. "@obj Object to check. (If blank, it will check the current target).\n"
  1127. "@useMuzzle Use muzzle position. Otherwise use eye position. (defaults to false).\n"
  1128. "@checkEnabled check whether the object can take damage and if so is still alive.(Defaults to false)\n")
  1129. {
  1130. return object->checkInLos(obj, useMuzzle, checkEnabled);
  1131. }
  1132. bool AIPlayer::checkInFoV(GameBase* target, F32 camFov, bool _checkEnabled)
  1133. {
  1134. if (!isServerObject()) return false;
  1135. if (!target)
  1136. {
  1137. target = mAimObject.getPointer();
  1138. if (!target)
  1139. return false;
  1140. }
  1141. if (_checkEnabled)
  1142. {
  1143. if (target->getTypeMask() & ShapeBaseObjectType)
  1144. {
  1145. ShapeBase *shapeBaseCheck = static_cast<ShapeBase *>(target);
  1146. if (shapeBaseCheck)
  1147. if (shapeBaseCheck->getDamageState() != Enabled) return false;
  1148. }
  1149. else
  1150. return false;
  1151. }
  1152. MatrixF cam = getTransform();
  1153. Point3F camPos;
  1154. VectorF camDir;
  1155. cam.getColumn(3, &camPos);
  1156. cam.getColumn(1, &camDir);
  1157. camFov = mDegToRad(camFov) / 2;
  1158. Point3F shapePos = target->getBoxCenter();
  1159. VectorF shapeDir = shapePos - camPos;
  1160. // Test to see if it's within our viewcone, this test doesn't
  1161. // actually match the viewport very well, should consider
  1162. // projection and box test.
  1163. shapeDir.normalize();
  1164. F32 dot = mDot(shapeDir, camDir);
  1165. return (dot > mCos(camFov));
  1166. }
  1167. DefineEngineMethod(AIPlayer, checkInFoV, bool, (ShapeBase* obj, F32 fov, bool checkEnabled), (NULL, 45.0f, false),
  1168. "@brief Check whether an object is within a specified veiw cone.\n"
  1169. "@obj Object to check. (If blank, it will check the current target).\n"
  1170. "@fov view angle in degrees.(Defaults to 45)\n"
  1171. "@checkEnabled check whether the object can take damage and if so is still alive.(Defaults to false)\n")
  1172. {
  1173. return object->checkInFoV(obj, fov, checkEnabled);
  1174. }
  1175. DefineEngineMethod( AIPlayer, setMoveTrigger, void, ( U32 slot ),,
  1176. "@brief Sets a movement trigger on an AI object.\n\n"
  1177. "@param slot The trigger slot to set.\n"
  1178. "@see getMoveTrigger()\n"
  1179. "@see clearMoveTrigger()\n"
  1180. "@see clearMoveTriggers()\n")
  1181. {
  1182. object->setMoveTrigger( slot, true );
  1183. }
  1184. DefineEngineMethod( AIPlayer, clearMoveTrigger, void, ( U32 slot ),,
  1185. "@brief Clears a movement trigger on an AI object.\n\n"
  1186. "@param slot The trigger slot to set.\n"
  1187. "@see setMoveTrigger()\n"
  1188. "@see getMoveTrigger()\n"
  1189. "@see clearMoveTriggers()\n")
  1190. {
  1191. object->setMoveTrigger( slot, false );
  1192. }
  1193. DefineEngineMethod( AIPlayer, getMoveTrigger, bool, ( U32 slot ),,
  1194. "@brief Tests if a movement trigger on an AI object is set.\n\n"
  1195. "@param slot The trigger slot to check.\n"
  1196. "@return a boolean indicating if the trigger is set/unset.\n"
  1197. "@see setMoveTrigger()\n"
  1198. "@see clearMoveTrigger()\n"
  1199. "@see clearMoveTriggers()\n")
  1200. {
  1201. return object->getMoveTrigger( slot );
  1202. }
  1203. DefineEngineMethod( AIPlayer, clearMoveTriggers, void, ( ),,
  1204. "@brief Clear ALL movement triggers on an AI object.\n"
  1205. "@see setMoveTrigger()\n"
  1206. "@see getMoveTrigger()\n"
  1207. "@see clearMoveTrigger()\n")
  1208. {
  1209. object->clearMoveTriggers();
  1210. }
  1211. F32 AIPlayer::getTargetDistance(GameBase* target, bool _checkEnabled)
  1212. {
  1213. if (!isServerObject()) return false;
  1214. if (!target)
  1215. {
  1216. target = mAimObject.getPointer();
  1217. if (!target)
  1218. return F32_MAX;
  1219. }
  1220. if (_checkEnabled)
  1221. {
  1222. if (target->getTypeMask() & ShapeBaseObjectType)
  1223. {
  1224. ShapeBase *shapeBaseCheck = static_cast<ShapeBase *>(target);
  1225. if (shapeBaseCheck)
  1226. if (shapeBaseCheck->getDamageState() != Enabled) return false;
  1227. }
  1228. else
  1229. return F32_MAX;
  1230. }
  1231. return (getPosition() - target->getPosition()).len();
  1232. }
  1233. DefineEngineMethod(AIPlayer, getTargetDistance, bool, (ShapeBase* obj, bool checkEnabled), (NULL, false),
  1234. "@brief Check whether an object is within a specified veiw cone.\n"
  1235. "@obj Object to check. (If blank, it will check the current target).\n"
  1236. "@fov view angle in degrees.(Defaults to 45)\n"
  1237. "@checkEnabled check whether the object can take damage and if so is still alive.(Defaults to false)\n")
  1238. {
  1239. return object->getTargetDistance(obj, checkEnabled);
  1240. }
  1241. DefineEngineMethod( AIPlayer, setAiPose, void, ( S32 pose ),,
  1242. "@brief Sets the AiPose for an AI object.\n"
  1243. "@param pose StandPose=0, CrouchPose=1, PronePose=2, SprintPose=3.\n"
  1244. "Uses the new AiPose variable from shapebase (as defined in its PlayerData datablock).\n")
  1245. {
  1246. object->setAiPose(pose);
  1247. }
  1248. DefineEngineMethod( AIPlayer, getAiPose, S32, (),,
  1249. "@brief Get the object's current AiPose.\n"
  1250. "@return StandPose=0, CrouchPose=1, PronePose=2, SprintPose=3.\n")
  1251. {
  1252. return object->getAiPose();
  1253. }