AIController.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "AIController.h"
  23. #include "T3D/player.h"
  24. #include "T3D/rigidShape.h"
  25. #include "T3D/vehicles/wheeledVehicle.h"
  26. IMPLEMENT_CONOBJECT(AIController);
  27. //-----------------------------------------------------------------------------
  28. void AIController::throwCallback(const char* name)
  29. {
  30. Con::warnf("throwCallback: %s", name);
  31. Con::executef(mControllerData, name, getIdString()); //controller data callbacks
  32. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  33. if (!gbo) return;
  34. Con::executef(gbo->getDataBlock(), name, getAIInfo()->mObj->getIdString()); //legacy support for object db callbacks
  35. }
  36. void AIController::initPersistFields()
  37. {
  38. addProtectedField("ControllerData", TYPEID< AIControllerData >(), Offset(mControllerData, AIController),
  39. &setControllerDataProperty, &defaultProtectedGetFn,
  40. "Script datablock used for game objects.");
  41. addFieldV("MoveSpeed", TypeRangedF32, Offset(mMovement.mMoveSpeed, AIController), &CommonValidators::PositiveFloat,
  42. "@brief default move sepeed.");
  43. }
  44. bool AIController::setControllerDataProperty(void* obj, const char* index, const char* db)
  45. {
  46. if (db == NULL || !db[0])
  47. {
  48. Con::errorf("AIController::setControllerDataProperty - Can't unset ControllerData on AIController objects");
  49. return false;
  50. }
  51. AIController* object = static_cast<AIController*>(obj);
  52. AIControllerData* data;
  53. if (Sim::findObject(db, data))
  54. {
  55. object->mControllerData = data;
  56. return true;
  57. }
  58. Con::errorf("AIController::setControllerDataProperty - Could not find ControllerData \"%s\"", db);
  59. return false;
  60. }
  61. void AIController::setGoal(AIInfo* targ)
  62. {
  63. if (mGoal) { delete(mGoal); mGoal = NULL; }
  64. if (targ->mObj.isValid())
  65. {
  66. delete(mGoal);
  67. mGoal = new AIGoal(this, targ->mObj, targ->mRadius);
  68. }
  69. else if (targ->mPosSet)
  70. {
  71. delete(mGoal);
  72. mGoal = new AIGoal(this, targ->mPosition, targ->mRadius);
  73. }
  74. }
  75. void AIController::setGoal(Point3F loc, F32 rad)
  76. {
  77. if (mGoal) delete(mGoal);
  78. mGoal = new AIGoal(this, loc, rad);
  79. }
  80. void AIController::setGoal(SimObjectPtr<SceneObject> objIn, F32 rad)
  81. {
  82. if (mGoal) delete(mGoal);
  83. mGoal = new AIGoal(this, objIn, rad);
  84. }
  85. void AIController::setAim(Point3F loc, F32 rad, Point3F offset)
  86. {
  87. if (mAimTarget) delete(mAimTarget);
  88. mAimTarget = new AIAimTarget(this, loc, rad);
  89. mAimTarget->mAimOffset = offset;
  90. }
  91. void AIController::setAim(SimObjectPtr<SceneObject> objIn, F32 rad, Point3F offset)
  92. {
  93. if (mAimTarget) delete(mAimTarget);
  94. mAimTarget = new AIAimTarget(this, objIn, rad);
  95. mAimTarget->mAimOffset = offset;
  96. }
  97. #ifdef TORQUE_NAVIGATION_ENABLED
  98. bool AIController::getAIMove(Move* movePtr)
  99. {
  100. *movePtr = NullMove;
  101. ShapeBase* sbo = dynamic_cast<ShapeBase*>(getAIInfo()->mObj.getPointer());
  102. if (!sbo) return false;
  103. // Use the eye as the current position.
  104. MatrixF eye;
  105. sbo->getEyeTransform(&eye);
  106. Point3F location = eye.getPosition();
  107. Point3F rotation = sbo->getTransform().toEuler();
  108. #ifdef TORQUE_NAVIGATION_ENABLED
  109. if (sbo->getDamageState() == ShapeBase::Enabled && getGoal())
  110. {
  111. if (mMovement.mMoveState != ModeStop)
  112. getNav()->updateNavMesh();
  113. if (getNav()->mPathData.path.isNull())
  114. {
  115. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  116. {
  117. if (getGoal()->mObj.isValid())
  118. getNav()->followObject(getGoal()->mObj, mControllerData->mFollowTolerance);
  119. else if (getGoal()->mPosSet)
  120. getNav()->setPathDestination(getGoal()->getPosition());
  121. }
  122. }
  123. else
  124. {
  125. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  126. {
  127. F32 raylength = 2.0; //for vehicles
  128. SceneObject* obj = getAIInfo()->mObj->getObjectMount();
  129. if (!obj)
  130. {
  131. obj = getAIInfo()->mObj;
  132. raylength = 0.001f; //for jumping
  133. }
  134. RayInfo info;
  135. if (obj->getContainer()->castRay(obj->getPosition(), obj->getPosition() - Point3F(0, 0, raylength), StaticShapeObjectType, &info))
  136. {
  137. getNav()->repath();
  138. }
  139. getGoal()->mInRange = false;
  140. }
  141. if (getGoal()->getDist() < mControllerData->mFollowTolerance && !getGoal()->mInRange)
  142. {
  143. getNav()->clearPath();
  144. mMovement.mMoveState = ModeStop;
  145. getGoal()->mInRange = true;
  146. throwCallback("onTargetInRange");
  147. }
  148. else
  149. {
  150. if (getGoal()->getDist() < mControllerData->mAttackRadius )
  151. {
  152. if (!getGoal()->mInFiringRange)
  153. {
  154. getGoal()->mInFiringRange = true;
  155. throwCallback("onTargetInFiringRange");
  156. }
  157. }
  158. else
  159. getGoal()->mInFiringRange = false;
  160. }
  161. }
  162. }
  163. #endif // TORQUE_NAVIGATION_ENABLED
  164. // Orient towards the aim point, aim object, or towards
  165. // our destination.
  166. if (getAim() || mMovement.mMoveState != ModeStop)
  167. {
  168. // Update the aim position if we're aiming for an object or explicit position
  169. if (getAim())
  170. mMovement.mAimLocation = getAim()->getPosition();
  171. else
  172. mMovement.mAimLocation = getNav()->mMoveDestination;
  173. mControllerData->resolveYawPtr(this, location, movePtr);
  174. mControllerData->resolvePitchPtr(this, location, movePtr);
  175. mControllerData->resolveRollPtr(this, location, movePtr);
  176. if (mMovement.mMoveState != AIController::ModeStop)
  177. {
  178. F32 xDiff = getNav()->mMoveDestination.x - location.x;
  179. F32 yDiff = getNav()->mMoveDestination.y - location.y;
  180. if (mFabs(xDiff) < mControllerData->mMoveTolerance && mFabs(yDiff) < mControllerData->mMoveTolerance)
  181. {
  182. mMovement.mMoveState = AIController::ModeStop;
  183. getNav()->onReachDestination();
  184. }
  185. else
  186. {
  187. mControllerData->resolveSpeedPtr(this, location, movePtr);
  188. mControllerData->resolveStuckPtr(this);
  189. }
  190. }
  191. }
  192. mControllerData->resolveTriggerStatePtr(this, movePtr);
  193. // Test for target location in sight if it's an object. The LOS is
  194. // run from the eye position to the center of the object's bounding,
  195. // which is not very accurate.
  196. if (getAim() && getAim()->mObj)
  197. {
  198. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  199. if (getAim()->checkInLos(gbo))
  200. {
  201. if (!getAim()->mTargetInLOS)
  202. {
  203. throwCallback("onTargetEnterLOS");
  204. getAim()->mTargetInLOS = true;
  205. }
  206. }
  207. else if (getAim()->mTargetInLOS)
  208. {
  209. throwCallback("onTargetExitLOS");
  210. getAim()->mTargetInLOS = false;
  211. }
  212. }
  213. return true;
  214. }
  215. void AIController::clearCover()
  216. {
  217. // Notify cover that we are no longer on our way.
  218. if (getCover() && !getCover()->mCoverPoint.isNull())
  219. getCover()->mCoverPoint->setOccupied(false);
  220. SAFE_DELETE(mCover);
  221. }
  222. void AIController::Movement::stopMove()
  223. {
  224. mMoveState = ModeStop;
  225. #ifdef TORQUE_NAVIGATION_ENABLED
  226. mControllerRef->getNav()->clearPath();
  227. mControllerRef->clearCover();
  228. mControllerRef->getNav()->clearFollow();
  229. #endif
  230. }
  231. void AIController::Movement::onStuck()
  232. {
  233. mControllerRef->throwCallback("onMoveStuck");
  234. #ifdef TORQUE_NAVIGATION_ENABLED
  235. if (!mControllerRef->getNav()->getPath().isNull())
  236. mControllerRef->getNav()->repath();
  237. #endif
  238. }
  239. DefineEngineMethod(AIController, setMoveSpeed, void, (F32 speed), ,
  240. "@brief Sets the move speed for an AI object.\n\n"
  241. "@param speed A speed multiplier between 0.0 and 1.0. "
  242. "This is multiplied by the AIPlayer's base movement rates (as defined in "
  243. "its PlayerData datablock)\n\n"
  244. "@see getMoveDestination()\n")
  245. {
  246. object->mMovement.setMoveSpeed(speed);
  247. }
  248. DefineEngineMethod(AIController, getMoveSpeed, F32, (), ,
  249. "@brief Gets the move speed of an AI object.\n\n"
  250. "@return A speed multiplier between 0.0 and 1.0.\n\n"
  251. "@see setMoveSpeed()\n")
  252. {
  253. return object->mMovement.getMoveSpeed();
  254. }
  255. DefineEngineMethod(AIController, stop, void, (), ,
  256. "@brief Tells the AIPlayer to stop moving.\n\n")
  257. {
  258. object->mMovement.stopMove();
  259. }
  260. /**
  261. * Set the state of a movement trigger.
  262. *
  263. * @param slot The trigger slot to set
  264. * @param isSet set/unset the trigger
  265. */
  266. void AIController::TriggerState::setMoveTrigger(U32 slot, const bool isSet)
  267. {
  268. if (slot >= MaxTriggerKeys)
  269. {
  270. Con::errorf("Attempting to set an invalid trigger slot (%i)", slot);
  271. }
  272. else
  273. {
  274. mMoveTriggers[slot] = isSet; // set the trigger
  275. mControllerRef->getAIInfo()->mObj->setMaskBits(ShapeBase::NoWarpMask); // force the client to updateMove
  276. }
  277. }
  278. /**
  279. * Get the state of a movement trigger.
  280. *
  281. * @param slot The trigger slot to query
  282. * @return True if the trigger is set, false if it is not set
  283. */
  284. bool AIController::TriggerState::getMoveTrigger(U32 slot) const
  285. {
  286. if (slot >= MaxTriggerKeys)
  287. {
  288. Con::errorf("Attempting to get an invalid trigger slot (%i)", slot);
  289. return false;
  290. }
  291. else
  292. {
  293. return mMoveTriggers[slot];
  294. }
  295. }
  296. /**
  297. * Clear the trigger state for all movement triggers.
  298. */
  299. void AIController::TriggerState::clearMoveTriggers()
  300. {
  301. for (U32 i = 0; i < MaxTriggerKeys; i++)
  302. setMoveTrigger(i, false);
  303. }
  304. //-----------------------------------------------------------------------------
  305. IMPLEMENT_CO_DATABLOCK_V1(AIControllerData);
  306. void AIControllerData::resolveYaw(AIController* obj, Point3F location, Move* move)
  307. {
  308. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  309. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  310. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  311. if (!mIsZero(xDiff) || !mIsZero(yDiff))
  312. {
  313. // First do Yaw
  314. // use the cur yaw between -Pi and Pi
  315. F32 curYaw = rotation.z;
  316. while (curYaw > M_2PI_F)
  317. curYaw -= M_2PI_F;
  318. while (curYaw < -M_2PI_F)
  319. curYaw += M_2PI_F;
  320. // find the yaw offset
  321. F32 newYaw = mAtan2(xDiff, yDiff);
  322. F32 yawDiff = newYaw - curYaw;
  323. // make it between 0 and 2PI
  324. if (yawDiff < 0.0f)
  325. yawDiff += M_2PI_F;
  326. else if (yawDiff >= M_2PI_F)
  327. yawDiff -= M_2PI_F;
  328. // now make sure we take the short way around the circle
  329. if (yawDiff > M_PI_F)
  330. yawDiff -= M_2PI_F;
  331. else if (yawDiff < -M_PI_F)
  332. yawDiff += M_2PI_F;
  333. move->yaw = yawDiff;
  334. }
  335. }
  336. void AIControllerData::resolveRoll(AIController* obj, Point3F location, Move* movePtr)
  337. {
  338. }
  339. void AIControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  340. {
  341. F32 xDiff = obj->getNav()->mMoveDestination.x - location.x;
  342. F32 yDiff = obj->getNav()->mMoveDestination.y - location.y;
  343. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  344. // Build move direction in world space
  345. if (mIsZero(xDiff))
  346. movePtr->y = (location.y > obj->getNav()->mMoveDestination.y) ? -1.0f : 1.0f;
  347. else
  348. if (mIsZero(yDiff))
  349. movePtr->x = (location.x > obj->getNav()->mMoveDestination.x) ? -1.0f : 1.0f;
  350. else
  351. if (mFabs(xDiff) > mFabs(yDiff))
  352. {
  353. F32 value = mFabs(yDiff / xDiff);
  354. movePtr->y = (location.y > obj->getNav()->mMoveDestination.y) ? -value : value;
  355. movePtr->x = (location.x > obj->getNav()->mMoveDestination.x) ? -1.0f : 1.0f;
  356. }
  357. else
  358. {
  359. F32 value = mFabs(xDiff / yDiff);
  360. movePtr->x = (location.x > obj->getNav()->mMoveDestination.x) ? -value : value;
  361. movePtr->y = (location.y > obj->getNav()->mMoveDestination.y) ? -1.0f : 1.0f;
  362. }
  363. // Rotate the move into object space (this really only needs
  364. // a 2D matrix)
  365. Point3F newMove;
  366. MatrixF moveMatrix;
  367. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  368. moveMatrix.mulV(Point3F(movePtr->x, movePtr->y, 0.0f), &newMove);
  369. movePtr->x = newMove.x;
  370. movePtr->y = newMove.y;
  371. // Set movement speed. We'll slow down once we get close
  372. // to try and stop on the spot...
  373. if (obj->mMovement.mMoveSlowdown)
  374. {
  375. F32 speed = obj->mMovement.mMoveSpeed;
  376. F32 dist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  377. F32 maxDist = mMoveTolerance * 2;
  378. if (dist < maxDist)
  379. speed *= dist / maxDist;
  380. movePtr->x *= speed;
  381. movePtr->y *= speed;
  382. obj->mMovement.mMoveState = AIController::ModeSlowing;
  383. }
  384. else
  385. {
  386. movePtr->x *= obj->mMovement.mMoveSpeed;
  387. movePtr->y *= obj->mMovement.mMoveSpeed;
  388. obj->mMovement.mMoveState = AIController::ModeMove;
  389. }
  390. }
  391. void AIControllerData::resolveTriggerState(AIController* obj, Move* movePtr)
  392. {
  393. //check for scripted overides
  394. for (U32 slot = 0; slot < MaxTriggerKeys; slot++)
  395. {
  396. movePtr->trigger[slot] = obj->mTriggerState.mMoveTriggers[slot];
  397. }
  398. }
  399. void AIControllerData::resolveStuck(AIController* obj)
  400. {
  401. if (obj->mMovement.mMoveState == AIController::ModeStop) return;
  402. if (!obj->getGoal()) return;
  403. ShapeBase* sbo = dynamic_cast<ShapeBase*>(obj->getAIInfo()->mObj.getPointer());
  404. // Don't check for ai stuckness if animation during
  405. // an anim-clip effect override.
  406. if (sbo->getDamageState() == ShapeBase::Enabled && !(sbo->anim_clip_flags & ShapeBase::ANIM_OVERRIDDEN) && !sbo->isAnimationLocked())
  407. {
  408. if (obj->mMovement.mMoveStuckTestCountdown > 0)
  409. --obj->mMovement.mMoveStuckTestCountdown;
  410. else
  411. {
  412. // We should check to see if we are stuck...
  413. F32 locationDelta = (obj->getAIInfo()->getPosition() - obj->getAIInfo()->mLastPos).len();
  414. if (locationDelta < mMoveStuckTolerance)
  415. {
  416. // If we are slowing down, then it's likely that our location delta will be less than
  417. // our move stuck tolerance. Because we can be both slowing and stuck
  418. // we should TRY to check if we've moved. This could use better detection.
  419. if (obj->mMovement.mMoveState != AIController::ModeSlowing || locationDelta == 0)
  420. {
  421. obj->mMovement.mMoveState = AIController::ModeStuck;
  422. obj->mMovement.onStuck();
  423. obj->throwCallback("onStuck");
  424. }
  425. }
  426. }
  427. obj->getAIInfo()->mLastPos = obj->getAIInfo()->getPosition();
  428. }
  429. }
  430. void AIControllerData::initPersistFields()
  431. {
  432. docsURL;
  433. addGroup("AI");
  434. addFieldV("moveTolerance", TypeRangedF32, Offset(mMoveTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  435. "@brief Distance from destination before stopping.\n\n"
  436. "When the AIPlayer is moving to a given destination it will move to within "
  437. "this distance of the destination and then stop. By providing this tolerance "
  438. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  439. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  440. addFieldV("followTolerance", TypeRangedF32, Offset(mFollowTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  441. "@brief Distance from destination before stopping.\n\n"
  442. "When the AIPlayer is moving to a given destination it will move to within "
  443. "this distance of the destination and then stop. By providing this tolerance "
  444. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  445. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  446. addFieldV("moveStuckTolerance", TypeRangedF32, Offset(mMoveStuckTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  447. "@brief Distance tolerance on stuck check.\n\n"
  448. "When the AIPlayer is moving to a given destination, if it ever moves less than "
  449. "this tolerance during a single tick, the AIPlayer is considered stuck. At this point "
  450. "the onMoveStuck() callback is called on the datablock.\n");
  451. addFieldV("moveStuckTestDelay", TypeRangedS32, Offset(mMoveStuckTestDelay, AIControllerData), &CommonValidators::PositiveInt,
  452. "@brief The number of ticks to wait before testing if the AIPlayer is stuck.\n\n"
  453. "When the AIPlayer is asked to move, this property is the number of ticks to wait "
  454. "before the AIPlayer starts to check if it is stuck. This delay allows the AIPlayer "
  455. "to accelerate to full speed without its initial slow start being considered as stuck.\n"
  456. "@note Set to zero to have the stuck test start immediately.\n");
  457. addFieldV("AttackRadius", TypeRangedF32, Offset(mAttackRadius, AIControllerData), &CommonValidators::PositiveFloat,
  458. "@brief Distance considered in firing range for callback purposes.");
  459. endGroup("AI");
  460. #ifdef TORQUE_NAVIGATION_ENABLED
  461. addGroup("Pathfinding");
  462. addField("allowWalk", TypeBool, Offset(mLinkTypes.walk, AIControllerData),
  463. "Allow the character to walk on dry land.");
  464. addField("allowJump", TypeBool, Offset(mLinkTypes.jump, AIControllerData),
  465. "Allow the character to use jump links.");
  466. addField("allowDrop", TypeBool, Offset(mLinkTypes.drop, AIControllerData),
  467. "Allow the character to use drop links.");
  468. addField("allowSwim", TypeBool, Offset(mLinkTypes.swim, AIControllerData),
  469. "Allow the character to move in water.");
  470. addField("allowLedge", TypeBool, Offset(mLinkTypes.ledge, AIControllerData),
  471. "Allow the character to jump ledges.");
  472. addField("allowClimb", TypeBool, Offset(mLinkTypes.climb, AIControllerData),
  473. "Allow the character to use climb links.");
  474. addField("allowTeleport", TypeBool, Offset(mLinkTypes.teleport, AIControllerData),
  475. "Allow the character to use teleporters.");
  476. endGroup("Pathfinding");
  477. #endif // TORQUE_NAVIGATION_ENABLED
  478. Parent::initPersistFields();
  479. }
  480. //-----------------------------------------------------------------------------
  481. //-----------------------------------------------------------------------------
  482. IMPLEMENT_CO_DATABLOCK_V1(AIPlayerControllerData);
  483. void AIPlayerControllerData::resolvePitch(AIController* obj, Point3F location, Move* movePtr)
  484. {
  485. Player* po = dynamic_cast<Player*>(obj->getAIInfo()->mObj.getPointer());
  486. if (!po) return;//not a player
  487. if (obj->getAim() || obj->mMovement.mMoveState != AIController::ModeStop)
  488. {
  489. // Next do pitch.
  490. if (!obj->getAim())
  491. {
  492. // Level out if were just looking at our next way point.
  493. Point3F headRotation = po->getHeadRotation();
  494. movePtr->pitch = -headRotation.x;
  495. }
  496. else
  497. {
  498. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  499. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  500. // This should be adjusted to run from the
  501. // eye point to the object's center position. Though this
  502. // works well enough for now.
  503. F32 vertDist = obj->mMovement.mAimLocation.z - location.z;
  504. F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  505. F32 newPitch = mAtan2(horzDist, vertDist) - (M_PI_F / 2.0f);
  506. if (mFabs(newPitch) > 0.01f)
  507. {
  508. Point3F headRotation = po->getHeadRotation();
  509. movePtr->pitch = newPitch - headRotation.x;
  510. }
  511. }
  512. }
  513. else
  514. {
  515. // Level out if we're not doing anything else
  516. Point3F headRotation = po->getHeadRotation();
  517. movePtr->pitch = -headRotation.x;
  518. }
  519. }
  520. void AIPlayerControllerData::resolveTriggerState(AIController* obj, Move* movePtr)
  521. {
  522. Parent::resolveTriggerState(obj, movePtr);
  523. #ifdef TORQUE_NAVIGATION_ENABLED
  524. if (obj->getNav()->mJump == AINavigation::Now)
  525. {
  526. movePtr->trigger[2] = true;
  527. obj->getNav()->mJump = AINavigation::None;
  528. }
  529. else if (obj->getNav()->mJump == AINavigation::Ledge)
  530. {
  531. // If we're not touching the ground, jump!
  532. RayInfo info;
  533. if (!obj->getAIInfo()->mObj->getContainer()->castRay(obj->getAIInfo()->getPosition(), obj->getAIInfo()->getPosition() - Point3F(0, 0, 0.4f), StaticShapeObjectType, &info))
  534. {
  535. movePtr->trigger[2] = true;
  536. obj->getNav()->mJump = AINavigation::None;
  537. }
  538. }
  539. #endif // TORQUE_NAVIGATION_ENABLED
  540. }
  541. IMPLEMENT_CO_DATABLOCK_V1(AIWheeledVehicleControllerData);
  542. // Build a Triangle .. calculate angle of rotation required to meet target..
  543. // man there has to be a better way! >:)
  544. F32 AIWheeledVehicleControllerData::getSteeringAngle(AIController* obj, Point3F location)
  545. {
  546. WheeledVehicle* wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj.getPointer());
  547. if (!wvo)
  548. {
  549. //cover the case of a connection controling an object in turn controlling another
  550. if (obj->getAIInfo()->mObj->getObjectMount())
  551. wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  552. }
  553. if (!wvo) return 0;//not a WheeledVehicle
  554. DrivingState steerState = SteerNull;
  555. // What is our target
  556. Point3F desired;
  557. desired = obj->getNav()->mMoveDestination;
  558. MatrixF mat = wvo->getTransform();
  559. Point3F center, front;
  560. Point3F wFront;
  561. Box3F box = wvo->getObjBox();
  562. box.getCenter(&center);
  563. front = center;
  564. front.y = box.maxExtents.y; // should be true for all these objects
  565. obj->getAIInfo()->mObj->getWorldBox().getCenter(&center);
  566. front = center + front;
  567. Point3F objFront = front;
  568. Point3F offset = front - center;
  569. EulerF rot;
  570. rot = mat.toEuler();
  571. MatrixF transform(rot);
  572. transform.mulV(offset, &wFront);
  573. front = wFront + center;
  574. Point3F ftoc;
  575. ftoc.x = mFabs(front.x - center.x);
  576. ftoc.y = mFabs(front.y - center.y);
  577. ftoc.z = mFabs(front.z - center.z);
  578. F32 fToc = mSqrt((ftoc.x * ftoc.x) + (ftoc.y * ftoc.y));
  579. Point3F ltoc;
  580. ltoc.x = mFabs(desired.x - center.x);
  581. ltoc.y = mFabs(desired.y - center.y);
  582. ltoc.z = mFabs(desired.z - center.z);
  583. F32 lToc = mSqrt((ltoc.x * ltoc.x) + (ltoc.y * ltoc.y));
  584. Point3F ftol;
  585. ftol.x = mFabs(front.x - desired.x);
  586. ftol.y = mFabs(front.y - desired.y);
  587. ftol.z = mFabs(front.z - desired.z);
  588. F32 fTol = mSqrt((ftol.x * ftol.x) + (ftol.y * ftol.y));
  589. F32 myAngle = mAcos(((lToc * lToc) + (fToc * fToc) - (fTol * fTol)) / (2 * lToc * fToc));
  590. F32 finalYaw = mRadToDeg(myAngle);
  591. F32 maxSteeringAngle = 0;
  592. VehicleData* vd = (VehicleData*)(wvo->getDataBlock());
  593. maxSteeringAngle = vd->maxSteeringAngle;
  594. Point2F steering = wvo->getSteering();
  595. if (finalYaw < 5 && steering.x != 0.0f)
  596. steerState = Straight;
  597. else if (finalYaw < 5)
  598. steerState = SteerNull;
  599. else
  600. {// Quickly Hack out left or right turn info
  601. Point3F rotData = objFront - desired;
  602. MatrixF leftM(-rot);
  603. Point3F leftP;
  604. leftM.mulV(rotData, &leftP);
  605. leftP = leftP + desired;
  606. if (leftP.x < desired.x)
  607. steerState = Right;
  608. else
  609. steerState = Left;
  610. }
  611. F32 turnAdjust = myAngle - steering.x;
  612. F32 throttle = wvo->getThrottle();
  613. if (throttle < 0.0f)
  614. {
  615. F32 reverseReduction = 0.25f;
  616. if (steerState == Left)
  617. steerState = Right;
  618. else if (steerState == Right)
  619. steerState = Left;
  620. turnAdjust *= reverseReduction;
  621. myAngle *= reverseReduction;
  622. }
  623. F32 steer = 0;
  624. switch (steerState)
  625. {
  626. case Left:
  627. steer = myAngle < maxSteeringAngle ? -turnAdjust : -maxSteeringAngle - steering.x;
  628. break;
  629. case Right:
  630. steer = myAngle < maxSteeringAngle ? turnAdjust : maxSteeringAngle - steering.x;
  631. break;
  632. case Straight:
  633. steer = -steering.x;
  634. break;
  635. default:
  636. break;
  637. };
  638. // Con::printf("AI Steering : %f", steer);
  639. return steer;
  640. }
  641. void AIWheeledVehicleControllerData::resolveYaw(AIController* obj, Point3F location, Move* movePtr)
  642. {
  643. WheeledVehicle* wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj.getPointer());
  644. if (!wvo)
  645. {
  646. //cover the case of a connection controling an object in turn controlling another
  647. if (obj->getAIInfo()->mObj->getObjectMount())
  648. wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  649. }
  650. if (!wvo) return;//not a WheeledVehicle
  651. // Orient towards our destination.
  652. if (obj->mMovement.mMoveState == AIController::ModeMove || obj->mMovement.mMoveState == AIController::ModeReverse) {
  653. movePtr->yaw = getSteeringAngle(obj, location);
  654. }
  655. };
  656. void AIWheeledVehicleControllerData::resolveTriggerState(AIController* obj, Move* movePtr) {};
  657. #endif //_AICONTROLLER_H_