aiPlayer.cpp 45 KB

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