aiPlayer.cpp 44 KB

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