AIController.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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. #include "T3D/vehicles/flyingVehicle.h"
  27. IMPLEMENT_CONOBJECT(AIController);
  28. //-----------------------------------------------------------------------------
  29. void AIController::throwCallback(const char* name)
  30. {
  31. //Con::warnf("throwCallback: %s", name);
  32. Con::executef(mControllerData, name, getIdString()); //controller data callbacks
  33. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  34. if (!gbo) return;
  35. Con::executef(gbo->getDataBlock(), name, getAIInfo()->mObj->getIdString()); //legacy support for object db callbacks
  36. }
  37. void AIController::initPersistFields()
  38. {
  39. addProtectedField("ControllerData", TYPEID< AIControllerData >(), Offset(mControllerData, AIController),
  40. &setControllerDataProperty, &defaultProtectedGetFn,
  41. "Script datablock used for game objects.");
  42. addFieldV("MoveSpeed", TypeRangedF32, Offset(mMovement.mMoveSpeed, AIController), &CommonValidators::PositiveFloat,
  43. "@brief default move sepeed.");
  44. }
  45. bool AIController::setControllerDataProperty(void* obj, const char* index, const char* db)
  46. {
  47. if (db == NULL || !db[0])
  48. {
  49. Con::errorf("AIController::setControllerDataProperty - Can't unset ControllerData on AIController objects");
  50. return false;
  51. }
  52. AIController* object = static_cast<AIController*>(obj);
  53. AIControllerData* data;
  54. if (Sim::findObject(db, data))
  55. {
  56. object->mControllerData = data;
  57. return true;
  58. }
  59. Con::errorf("AIController::setControllerDataProperty - Could not find ControllerData \"%s\"", db);
  60. return false;
  61. }
  62. void AIController::setGoal(AIInfo* targ)
  63. {
  64. if (mGoal) { delete(mGoal); mGoal = NULL; }
  65. if (targ->mObj.isValid())
  66. {
  67. delete(mGoal);
  68. mGoal = new AIGoal(this, targ->mObj, targ->mRadius);
  69. }
  70. else if (targ->mPosSet)
  71. {
  72. delete(mGoal);
  73. mGoal = new AIGoal(this, targ->mPosition, targ->mRadius);
  74. }
  75. }
  76. void AIController::setGoal(Point3F loc, F32 rad)
  77. {
  78. if (mGoal) delete(mGoal);
  79. mGoal = new AIGoal(this, loc, rad);
  80. }
  81. void AIController::setGoal(SimObjectPtr<SceneObject> objIn, F32 rad)
  82. {
  83. if (mGoal) delete(mGoal);
  84. mGoal = new AIGoal(this, objIn, rad);
  85. }
  86. void AIController::setAim(Point3F loc, F32 rad, Point3F offset)
  87. {
  88. if (mAimTarget) delete(mAimTarget);
  89. mAimTarget = new AIAimTarget(this, loc, rad);
  90. mAimTarget->mAimOffset = offset;
  91. }
  92. void AIController::setAim(SimObjectPtr<SceneObject> objIn, F32 rad, Point3F offset)
  93. {
  94. if (mAimTarget) delete(mAimTarget);
  95. mAimTarget = new AIAimTarget(this, objIn, rad);
  96. mAimTarget->mAimOffset = offset;
  97. }
  98. #ifdef TORQUE_NAVIGATION_ENABLED
  99. bool AIController::getAIMove(Move* movePtr)
  100. {
  101. *movePtr = NullMove;
  102. ShapeBase* sbo = dynamic_cast<ShapeBase*>(getAIInfo()->mObj.getPointer());
  103. if (!sbo) return false;
  104. // Use the eye as the current position.
  105. MatrixF eye;
  106. sbo->getEyeTransform(&eye);
  107. Point3F location = eye.getPosition();
  108. Point3F rotation = sbo->getTransform().toEuler();
  109. // Test for target location in sight if it's an object. The LOS is
  110. // run from the eye position to the center of the object's bounding,
  111. // which is not very accurate.
  112. if (getAim() && getAim()->mObj)
  113. {
  114. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  115. if (getAim()->checkInLos(gbo))
  116. {
  117. if (!getAim()->mTargetInLOS)
  118. {
  119. throwCallback("onTargetEnterLOS");
  120. getAim()->mTargetInLOS = true;
  121. }
  122. }
  123. else if (getAim()->mTargetInLOS)
  124. {
  125. throwCallback("onTargetExitLOS");
  126. getAim()->mTargetInLOS = false;
  127. }
  128. }
  129. #ifdef TORQUE_NAVIGATION_ENABLED
  130. if (sbo->getDamageState() == ShapeBase::Enabled && getGoal())
  131. {
  132. if (mMovement.mMoveState != ModeStop)
  133. getNav()->updateNavMesh();
  134. if (getNav()->mPathData.path.isNull())
  135. {
  136. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  137. {
  138. if (getGoal()->mObj.isValid())
  139. getNav()->followObject(getGoal()->mObj, mControllerData->mFollowTolerance);
  140. else if (getGoal()->mPosSet)
  141. getNav()->setPathDestination(getGoal()->getPosition(true));
  142. }
  143. }
  144. else
  145. {
  146. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  147. {
  148. SceneObject* obj = getAIInfo()->mObj->getObjectMount();
  149. if (!obj)
  150. {
  151. obj = getAIInfo()->mObj;
  152. }
  153. RayInfo info;
  154. if (obj->getContainer()->castRay(obj->getPosition(), obj->getPosition() - Point3F(0, 0, mControllerData->mHeightTolerance), StaticShapeObjectType, &info))
  155. {
  156. getNav()->repath();
  157. }
  158. getGoal()->mInRange = false;
  159. }
  160. if (getGoal()->getDist() < mControllerData->mFollowTolerance )
  161. {
  162. getNav()->clearPath();
  163. mMovement.mMoveState = ModeStop;
  164. if (!getGoal()->mInRange)
  165. {
  166. getGoal()->mInRange = true;
  167. throwCallback("onTargetInRange");
  168. }
  169. else getGoal()->mInRange = false;
  170. }
  171. else
  172. {
  173. if (getGoal()->getDist() < mControllerData->mAttackRadius )
  174. {
  175. if (!getGoal()->mInFiringRange)
  176. {
  177. getGoal()->mInFiringRange = true;
  178. throwCallback("onTargetInFiringRange");
  179. }
  180. }
  181. else getGoal()->mInFiringRange = false;
  182. }
  183. }
  184. }
  185. #endif // TORQUE_NAVIGATION_ENABLED
  186. // Orient towards the aim point, aim object, or towards
  187. // our destination.
  188. if (getAim() || mMovement.mMoveState != ModeStop)
  189. {
  190. // Update the aim position if we're aiming for an object or explicit position
  191. if (getAim())
  192. mMovement.mAimLocation = getAim()->getPosition();
  193. else
  194. mMovement.mAimLocation = getNav()->getMoveDestination();
  195. mControllerData->resolveYawPtr(this, location, movePtr);
  196. mControllerData->resolvePitchPtr(this, location, movePtr);
  197. mControllerData->resolveRollPtr(this, location, movePtr);
  198. if (mMovement.mMoveState != AIController::ModeStop)
  199. {
  200. F32 xDiff = getNav()->getMoveDestination().x - location.x;
  201. F32 yDiff = getNav()->getMoveDestination().y - location.y;
  202. if (mFabs(xDiff) < mControllerData->mMoveTolerance && mFabs(yDiff) < mControllerData->mMoveTolerance)
  203. {
  204. getNav()->onReachDestination();
  205. }
  206. else
  207. {
  208. mControllerData->resolveSpeedPtr(this, location, movePtr);
  209. mControllerData->resolveStuckPtr(this);
  210. }
  211. }
  212. }
  213. mControllerData->resolveTriggerStatePtr(this, movePtr);
  214. getAIInfo()->mLastPos = getAIInfo()->getPosition();
  215. return true;
  216. }
  217. void AIController::clearCover()
  218. {
  219. // Notify cover that we are no longer on our way.
  220. if (getCover() && !getCover()->mCoverPoint.isNull())
  221. getCover()->mCoverPoint->setOccupied(false);
  222. SAFE_DELETE(mCover);
  223. }
  224. void AIController::Movement::stopMove()
  225. {
  226. mMoveState = ModeStop;
  227. #ifdef TORQUE_NAVIGATION_ENABLED
  228. getCtrl()->getNav()->clearPath();
  229. getCtrl()->clearCover();
  230. getCtrl()->getNav()->clearFollow();
  231. #endif
  232. }
  233. void AIController::Movement::onStuck()
  234. {
  235. mMoveState = AIController::ModeStuck;
  236. getCtrl()->throwCallback("onMoveStuck");
  237. #ifdef TORQUE_NAVIGATION_ENABLED
  238. if (!getCtrl()->getNav()->getPath().isNull())
  239. getCtrl()->getNav()->repath();
  240. #endif
  241. }
  242. DefineEngineMethod(AIController, setMoveSpeed, void, (F32 speed), ,
  243. "@brief Sets the move speed for an AI object.\n\n"
  244. "@param speed A speed multiplier between 0.0 and 1.0. "
  245. "This is multiplied by the AIController controlled object's base movement rates (as defined in "
  246. "its PlayerData datablock)\n\n"
  247. "@see getMoveDestination()\n")
  248. {
  249. object->mMovement.setMoveSpeed(speed);
  250. }
  251. DefineEngineMethod(AIController, getMoveSpeed, F32, (), ,
  252. "@brief Gets the move speed of an AI object.\n\n"
  253. "@return A speed multiplier between 0.0 and 1.0.\n\n"
  254. "@see setMoveSpeed()\n")
  255. {
  256. return object->mMovement.getMoveSpeed();
  257. }
  258. DefineEngineMethod(AIController, stop, void, (), ,
  259. "@brief Tells the AIController controlled object to stop moving.\n\n")
  260. {
  261. object->mMovement.stopMove();
  262. }
  263. /**
  264. * Set the state of a movement trigger.
  265. *
  266. * @param slot The trigger slot to set
  267. * @param isSet set/unset the trigger
  268. */
  269. void AIController::TriggerState::setMoveTrigger(U32 slot, const bool isSet)
  270. {
  271. if (slot >= MaxTriggerKeys)
  272. {
  273. Con::errorf("Attempting to set an invalid trigger slot (%i)", slot);
  274. }
  275. else
  276. {
  277. mMoveTriggers[slot] = isSet; // set the trigger
  278. mControllerRef->getAIInfo()->mObj->setMaskBits(ShapeBase::NoWarpMask); // force the client to updateMove
  279. }
  280. }
  281. /**
  282. * Get the state of a movement trigger.
  283. *
  284. * @param slot The trigger slot to query
  285. * @return True if the trigger is set, false if it is not set
  286. */
  287. bool AIController::TriggerState::getMoveTrigger(U32 slot) const
  288. {
  289. if (slot >= MaxTriggerKeys)
  290. {
  291. Con::errorf("Attempting to get an invalid trigger slot (%i)", slot);
  292. return false;
  293. }
  294. else
  295. {
  296. return mMoveTriggers[slot];
  297. }
  298. }
  299. /**
  300. * Clear the trigger state for all movement triggers.
  301. */
  302. void AIController::TriggerState::clearMoveTriggers()
  303. {
  304. for (U32 i = 0; i < MaxTriggerKeys; i++)
  305. setMoveTrigger(i, false);
  306. }
  307. //-----------------------------------------------------------------------------
  308. IMPLEMENT_CO_DATABLOCK_V1(AIControllerData);
  309. void AIControllerData::resolveYaw(AIController* obj, Point3F location, Move* move)
  310. {
  311. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  312. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  313. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  314. if (!mIsZero(xDiff) || !mIsZero(yDiff))
  315. {
  316. // First do Yaw
  317. // use the cur yaw between -Pi and Pi
  318. F32 curYaw = rotation.z;
  319. while (curYaw > M_2PI_F)
  320. curYaw -= M_2PI_F;
  321. while (curYaw < -M_2PI_F)
  322. curYaw += M_2PI_F;
  323. // find the yaw offset
  324. F32 newYaw = mAtan2(xDiff, yDiff);
  325. F32 yawDiff = newYaw - curYaw;
  326. // make it between 0 and 2PI
  327. if (yawDiff < 0.0f)
  328. yawDiff += M_2PI_F;
  329. else if (yawDiff >= M_2PI_F)
  330. yawDiff -= M_2PI_F;
  331. // now make sure we take the short way around the circle
  332. if (yawDiff > M_PI_F)
  333. yawDiff -= M_2PI_F;
  334. else if (yawDiff < -M_PI_F)
  335. yawDiff += M_2PI_F;
  336. move->yaw = yawDiff;
  337. }
  338. }
  339. void AIControllerData::resolveRoll(AIController* obj, Point3F location, Move* movePtr)
  340. {
  341. }
  342. void AIControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  343. {
  344. F32 xDiff = obj->getNav()->getMoveDestination().x - location.x;
  345. F32 yDiff = obj->getNav()->getMoveDestination().y - location.y;
  346. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  347. // Build move direction in world space
  348. if (mIsZero(xDiff))
  349. movePtr->y = (location.y > obj->getNav()->getMoveDestination().y) ? -1.0f : 1.0f;
  350. else
  351. {
  352. if (mIsZero(yDiff))
  353. movePtr->x = (location.x > obj->getNav()->getMoveDestination().x) ? -1.0f : 1.0f;
  354. else
  355. {
  356. if (mFabs(xDiff) > mFabs(yDiff))
  357. {
  358. F32 value = mFabs(yDiff / xDiff);
  359. movePtr->y = (location.y > obj->getNav()->getMoveDestination().y) ? -value : value;
  360. movePtr->x = (location.x > obj->getNav()->getMoveDestination().x) ? -1.0f : 1.0f;
  361. }
  362. else
  363. {
  364. F32 value = mFabs(xDiff / yDiff);
  365. movePtr->x = (location.x > obj->getNav()->getMoveDestination().x) ? -value : value;
  366. movePtr->y = (location.y > obj->getNav()->getMoveDestination().y) ? -1.0f : 1.0f;
  367. }
  368. }
  369. }
  370. // Rotate the move into object space (this really only needs
  371. // a 2D matrix)
  372. Point3F newMove;
  373. MatrixF moveMatrix;
  374. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  375. moveMatrix.mulV(Point3F(movePtr->x, movePtr->y, 0.0f), &newMove);
  376. movePtr->x = newMove.x;
  377. movePtr->y = newMove.y;
  378. // Set movement speed. We'll slow down once we get close
  379. // to try and stop on the spot...
  380. if (obj->mMovement.mMoveSlowdown)
  381. {
  382. F32 speed = obj->mMovement.mMoveSpeed;
  383. F32 dist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  384. F32 maxDist = mMoveTolerance * 2;
  385. if (dist < maxDist)
  386. speed *= dist / maxDist;
  387. movePtr->x *= speed;
  388. movePtr->y *= speed;
  389. }
  390. else
  391. {
  392. movePtr->x *= obj->mMovement.mMoveSpeed;
  393. movePtr->y *= obj->mMovement.mMoveSpeed;
  394. }
  395. }
  396. void AIControllerData::resolveTriggerState(AIController* obj, Move* movePtr)
  397. {
  398. //check for scripted overides
  399. for (U32 slot = 0; slot < MaxTriggerKeys; slot++)
  400. {
  401. movePtr->trigger[slot] = obj->mTriggerState.mMoveTriggers[slot];
  402. }
  403. }
  404. void AIControllerData::resolveStuck(AIController* obj)
  405. {
  406. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  407. if (!obj->getGoal()) return;
  408. ShapeBase* sbo = dynamic_cast<ShapeBase*>(obj->getAIInfo()->mObj.getPointer());
  409. // Don't check for ai stuckness if animation during
  410. // an anim-clip effect override.
  411. if (sbo->getDamageState() == ShapeBase::Enabled && !(sbo->anim_clip_flags & ShapeBase::ANIM_OVERRIDDEN) && !sbo->isAnimationLocked())
  412. {
  413. // We should check to see if we are stuck...
  414. F32 locationDelta = (obj->getAIInfo()->getPosition() - obj->getAIInfo()->mLastPos).len();
  415. if (locationDelta < mMoveStuckTolerance)
  416. {
  417. if (obj->mMovement.mMoveStuckTestCountdown > 0)
  418. --obj->mMovement.mMoveStuckTestCountdown;
  419. else
  420. {
  421. // If we are slowing down, then it's likely that our location delta will be less than
  422. // our move stuck tolerance. Because we can be both slowing and stuck
  423. // we should TRY to check if we've moved. This could use better detection.
  424. if (obj->mMovement.mMoveState != AIController::ModeSlowing || locationDelta == 0)
  425. {
  426. obj->mMovement.onStuck();
  427. obj->mMovement.mMoveStuckTestCountdown = obj->mControllerData->mMoveStuckTestDelay;
  428. }
  429. }
  430. }
  431. }
  432. }
  433. AIControllerData::AIControllerData()
  434. {
  435. mMoveTolerance = 0.25f;
  436. mFollowTolerance = 1.0f;
  437. mAttackRadius = 2.0f;
  438. mMoveStuckTolerance = 0.01f;
  439. mMoveStuckTestDelay = 30;
  440. mLinkTypes = LinkData(AllFlags);
  441. mNavSize = AINavigation::Regular;
  442. mHeightTolerance = 0.001f;
  443. mFlocking.mChance = 90;
  444. mFlocking.mMin = 1.0f;
  445. mFlocking.mMax = 3.0f;
  446. mFlocking.mSideStep = 0.01f;
  447. resolveYawPtr.bind(this, &AIControllerData::resolveYaw);
  448. resolvePitchPtr.bind(this, &AIControllerData::resolvePitch);
  449. resolveRollPtr.bind(this, &AIControllerData::resolveRoll);
  450. resolveSpeedPtr.bind(this, &AIControllerData::resolveSpeed);
  451. resolveTriggerStatePtr.bind(this, &AIControllerData::resolveTriggerState);
  452. resolveStuckPtr.bind(this, &AIControllerData::resolveStuck);
  453. }
  454. void AIControllerData::initPersistFields()
  455. {
  456. docsURL;
  457. addGroup("AI");
  458. addFieldV("moveTolerance", TypeRangedF32, Offset(mMoveTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  459. "@brief Distance from destination before stopping.\n\n"
  460. "When the AIController controlled object is moving to a given destination it will move to within "
  461. "this distance of the destination and then stop. By providing this tolerance "
  462. "it helps the AIController controlled object from never reaching its destination due to minor obstacles, "
  463. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  464. addFieldV("followTolerance", TypeRangedF32, Offset(mFollowTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  465. "@brief Distance from destination before stopping.\n\n"
  466. "When the AIController controlled object is moving to a given destination it will move to within "
  467. "this distance of the destination and then stop. By providing this tolerance "
  468. "it helps the AIController controlled object from never reaching its destination due to minor obstacles, "
  469. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  470. addFieldV("moveStuckTolerance", TypeRangedF32, Offset(mMoveStuckTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  471. "@brief Distance tolerance on stuck check.\n\n"
  472. "When the AIController controlled object controlled object is moving to a given destination, if it ever moves less than "
  473. "this tolerance during a single tick, the AIController controlled object is considered stuck. At this point "
  474. "the onMoveStuck() callback is called on the datablock.\n");
  475. addFieldV("HeightTolerance", TypeRangedF32, Offset(mHeightTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  476. "@brief Distance from destination before stopping.\n\n"
  477. "When the AIController controlled object is moving to a given destination it will move to within "
  478. "this distance of the destination and then stop. By providing this tolerance "
  479. "it helps the AIController controlled object from never reaching its destination due to minor obstacles, "
  480. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  481. addFieldV("moveStuckTestDelay", TypeRangedS32, Offset(mMoveStuckTestDelay, AIControllerData), &CommonValidators::PositiveInt,
  482. "@brief The number of ticks to wait before testing if the AIController controlled object is stuck.\n\n"
  483. "When the AIController controlled object is asked to move, this property is the number of ticks to wait "
  484. "before the AIController controlled object starts to check if it is stuck. This delay allows the AIController controlled object "
  485. "to accelerate to full speed without its initial slow start being considered as stuck.\n"
  486. "@note Set to zero to have the stuck test start immediately.\n");
  487. addFieldV("AttackRadius", TypeRangedF32, Offset(mAttackRadius, AIControllerData), &CommonValidators::PositiveFloat,
  488. "@brief Distance considered in firing range for callback purposes.");
  489. addFieldV("FlockChance", TypeRangedS32, Offset(mFlocking.mChance, AIControllerData), &CommonValidators::S32Percent,
  490. "@brief chance of flocking.");
  491. addFieldV("FlockMin", TypeRangedF32, Offset(mFlocking.mMin, AIControllerData), &CommonValidators::PositiveFloat,
  492. "@brief min flocking separation distance.");
  493. addFieldV("FlockMax", TypeRangedF32, Offset(mFlocking.mMax, AIControllerData), &CommonValidators::PositiveFloat,
  494. "@brief max flocking clustering distance.");
  495. addFieldV("FlockSideStep", TypeRangedF32, Offset(mFlocking.mSideStep, AIControllerData), &CommonValidators::PositiveFloat,
  496. "@brief Distance from destination before we stop moving out of the way.");
  497. endGroup("AI");
  498. #ifdef TORQUE_NAVIGATION_ENABLED
  499. addGroup("Pathfinding");
  500. addField("allowWalk", TypeBool, Offset(mLinkTypes.walk, AIControllerData),
  501. "Allow the character to walk on dry land.");
  502. addField("allowJump", TypeBool, Offset(mLinkTypes.jump, AIControllerData),
  503. "Allow the character to use jump links.");
  504. addField("allowDrop", TypeBool, Offset(mLinkTypes.drop, AIControllerData),
  505. "Allow the character to use drop links.");
  506. addField("allowSwim", TypeBool, Offset(mLinkTypes.swim, AIControllerData),
  507. "Allow the character to move in water.");
  508. addField("allowLedge", TypeBool, Offset(mLinkTypes.ledge, AIControllerData),
  509. "Allow the character to jump ledges.");
  510. addField("allowClimb", TypeBool, Offset(mLinkTypes.climb, AIControllerData),
  511. "Allow the character to use climb links.");
  512. addField("allowTeleport", TypeBool, Offset(mLinkTypes.teleport, AIControllerData),
  513. "Allow the character to use teleporters.");
  514. endGroup("Pathfinding");
  515. #endif // TORQUE_NAVIGATION_ENABLED
  516. Parent::initPersistFields();
  517. }
  518. //-----------------------------------------------------------------------------
  519. //-----------------------------------------------------------------------------
  520. IMPLEMENT_CO_DATABLOCK_V1(AIPlayerControllerData);
  521. void AIPlayerControllerData::resolvePitch(AIController* obj, Point3F location, Move* movePtr)
  522. {
  523. Player* po = dynamic_cast<Player*>(obj->getAIInfo()->mObj.getPointer());
  524. if (!po) return;//not a player
  525. if (obj->getAim() || obj->mMovement.mMoveState != AIController::ModeStop)
  526. {
  527. // Next do pitch.
  528. if (!obj->getAim())
  529. {
  530. // Level out if were just looking at our next way point.
  531. Point3F headRotation = po->getHeadRotation();
  532. movePtr->pitch = -headRotation.x;
  533. }
  534. else
  535. {
  536. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  537. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  538. // This should be adjusted to run from the
  539. // eye point to the object's center position. Though this
  540. // works well enough for now.
  541. F32 vertDist = obj->mMovement.mAimLocation.z - location.z;
  542. F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  543. F32 newPitch = mAtan2(horzDist, vertDist) - (M_PI_F / 2.0f);
  544. if (mFabs(newPitch) > 0.01f)
  545. {
  546. Point3F headRotation = po->getHeadRotation();
  547. movePtr->pitch = newPitch - headRotation.x;
  548. }
  549. }
  550. }
  551. else
  552. {
  553. // Level out if we're not doing anything else
  554. Point3F headRotation = po->getHeadRotation();
  555. movePtr->pitch = -headRotation.x;
  556. }
  557. }
  558. void AIPlayerControllerData::resolveTriggerState(AIController* obj, Move* movePtr)
  559. {
  560. Parent::resolveTriggerState(obj, movePtr);
  561. #ifdef TORQUE_NAVIGATION_ENABLED
  562. if (obj->getNav()->mJump == AINavigation::Now)
  563. {
  564. movePtr->trigger[2] = true;
  565. obj->getNav()->mJump = AINavigation::None;
  566. }
  567. else if (obj->getNav()->mJump == AINavigation::Ledge)
  568. {
  569. // If we're not touching the ground, jump!
  570. RayInfo info;
  571. if (!obj->getAIInfo()->mObj->getContainer()->castRay(obj->getAIInfo()->getPosition(), obj->getAIInfo()->getPosition() - Point3F(0, 0, 0.4f), StaticShapeObjectType, &info))
  572. {
  573. movePtr->trigger[2] = true;
  574. obj->getNav()->mJump = AINavigation::None;
  575. }
  576. }
  577. #endif // TORQUE_NAVIGATION_ENABLED
  578. }
  579. //-----------------------------------------------------------------------------
  580. //-----------------------------------------------------------------------------
  581. IMPLEMENT_CO_DATABLOCK_V1(AIWheeledVehicleControllerData);
  582. // Build a Triangle .. calculate angle of rotation required to meet target..
  583. // man there has to be a better way! >:)
  584. F32 AIWheeledVehicleControllerData::getSteeringAngle(AIController* obj, Point3F location)
  585. {
  586. WheeledVehicle* wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj.getPointer());
  587. if (!wvo)
  588. {
  589. //cover the case of a connection controling an object in turn controlling another
  590. if (obj->getAIInfo()->mObj->getObjectMount())
  591. wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  592. }
  593. if (!wvo) return 0;//not a WheeledVehicle
  594. DrivingState steerState = SteerNull;
  595. // What is our target
  596. Point3F desired;
  597. desired = obj->getNav()->getMoveDestination();
  598. MatrixF mat = wvo->getTransform();
  599. Point3F center, front;
  600. Point3F wFront;
  601. Box3F box = wvo->getObjBox();
  602. box.getCenter(&center);
  603. front = center;
  604. front.y = box.maxExtents.y; // should be true for all these objects
  605. obj->getAIInfo()->mObj->getWorldBox().getCenter(&center);
  606. front = center + front;
  607. Point3F objFront = front;
  608. Point3F offset = front - center;
  609. EulerF rot;
  610. rot = mat.toEuler();
  611. MatrixF transform(rot);
  612. transform.mulV(offset, &wFront);
  613. front = wFront + center;
  614. Point3F ftoc;
  615. ftoc.x = mFabs(front.x - center.x);
  616. ftoc.y = mFabs(front.y - center.y);
  617. ftoc.z = mFabs(front.z - center.z);
  618. F32 fToc = mSqrt((ftoc.x * ftoc.x) + (ftoc.y * ftoc.y));
  619. Point3F ltoc;
  620. ltoc.x = mFabs(desired.x - center.x);
  621. ltoc.y = mFabs(desired.y - center.y);
  622. ltoc.z = mFabs(desired.z - center.z);
  623. F32 lToc = mSqrt((ltoc.x * ltoc.x) + (ltoc.y * ltoc.y));
  624. Point3F ftol;
  625. ftol.x = mFabs(front.x - desired.x);
  626. ftol.y = mFabs(front.y - desired.y);
  627. ftol.z = mFabs(front.z - desired.z);
  628. F32 fTol = mSqrt((ftol.x * ftol.x) + (ftol.y * ftol.y));
  629. F32 myAngle = mAcos(((lToc * lToc) + (fToc * fToc) - (fTol * fTol)) / (2 * lToc * fToc));
  630. F32 finalYaw = mRadToDeg(myAngle);
  631. F32 maxSteeringAngle = 0;
  632. VehicleData* vd = (VehicleData*)(wvo->getDataBlock());
  633. maxSteeringAngle = vd->maxSteeringAngle;
  634. Point2F steering = wvo->getSteering();
  635. if (finalYaw < 5 && steering.x != 0.0f)
  636. steerState = Straight;
  637. else if (finalYaw < 5)
  638. steerState = SteerNull;
  639. else
  640. {// Quickly Hack out left or right turn info
  641. Point3F rotData = objFront - desired;
  642. MatrixF leftM(-rot);
  643. Point3F leftP;
  644. leftM.mulV(rotData, &leftP);
  645. leftP = leftP + desired;
  646. if (leftP.x < desired.x)
  647. steerState = Right;
  648. else
  649. steerState = Left;
  650. }
  651. F32 throttle = wvo->getThrottle();
  652. if (throttle < 0.0f && steerState != Straight)
  653. {
  654. F32 reverseReduction = 0.25;
  655. steering.x = steering.x * reverseReduction * throttle;
  656. }
  657. F32 turnAdjust = myAngle - steering.x;
  658. F32 steer = 0;
  659. switch (steerState)
  660. {
  661. case Left:
  662. steer = myAngle < maxSteeringAngle ? -turnAdjust : -maxSteeringAngle - steering.x;
  663. break;
  664. case Right:
  665. steer = myAngle < maxSteeringAngle ? turnAdjust : maxSteeringAngle - steering.x;
  666. break;
  667. case Straight:
  668. steer = -steering.x;
  669. break;
  670. default:
  671. break;
  672. };
  673. // Con::printf("AI Steering : %f", steer);
  674. return steer;
  675. }
  676. void AIWheeledVehicleControllerData::resolveYaw(AIController* obj, Point3F location, Move* movePtr)
  677. {
  678. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  679. WheeledVehicle* wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj.getPointer());
  680. if (!wvo)
  681. {
  682. //cover the case of a connection controling an object in turn controlling another
  683. if (obj->getAIInfo()->mObj->getObjectMount())
  684. wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  685. }
  686. if (!wvo) return;//not a WheeledVehicle
  687. // Orient towards our destination.
  688. if (obj->mMovement.mMoveState == AIController::ModeMove || obj->mMovement.mMoveState == AIController::ModeReverse) {
  689. movePtr->yaw = getSteeringAngle(obj, location);
  690. }
  691. };
  692. void AIWheeledVehicleControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  693. {
  694. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  695. WheeledVehicle* wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj.getPointer());
  696. if (!wvo)
  697. {
  698. //cover the case of a connection controling an object in turn controlling another
  699. if (obj->getAIInfo()->mObj->getObjectMount())
  700. wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  701. }
  702. if (!wvo) return;//not a WheeledVehicle
  703. Parent::resolveSpeed(obj, location, movePtr);
  704. VehicleData* db = static_cast<VehicleData *>(wvo->getDataBlock());
  705. movePtr->x = 0;
  706. movePtr->y *= 1.1 - wvo->getSteering().y / db->maxSteeringAngle;
  707. }
  708. //-----------------------------------------------------------------------------
  709. //-----------------------------------------------------------------------------
  710. IMPLEMENT_CO_DATABLOCK_V1(AIFlyingVehicleControllerData);
  711. void AIFlyingVehicleControllerData::initPersistFields()
  712. {
  713. docsURL;
  714. addGroup("AI");
  715. addFieldV("FlightFloor", TypeRangedF32, Offset(mFlightFloor, AIFlyingVehicleControllerData), &CommonValidators::PositiveFloat,
  716. "@brief Max height we can target.");
  717. addFieldV("FlightCeiling", TypeRangedF32, Offset(mFlightCeiling, AIFlyingVehicleControllerData), &CommonValidators::PositiveFloat,
  718. "@brief Max height we can target.");
  719. endGroup("AI");
  720. Parent::initPersistFields();
  721. }
  722. // Build a Triangle .. calculate angle of rotation required to meet target..
  723. // man there has to be a better way! >:)
  724. F32 AIFlyingVehicleControllerData::getSteeringAngle(AIController* obj, Point3F location)
  725. {
  726. FlyingVehicle* fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj.getPointer());
  727. if (!fvo)
  728. {
  729. //cover the case of a connection controling an object in turn controlling another
  730. if (obj->getAIInfo()->mObj->getObjectMount())
  731. fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  732. }
  733. if (!fvo) return 0;//not a FlyingVehicle
  734. DrivingState steerState = SteerNull;
  735. // What is our target
  736. Point3F desired;
  737. desired = obj->getNav()->getMoveDestination();
  738. MatrixF mat = fvo->getTransform();
  739. Point3F center, front;
  740. Point3F wFront;
  741. Box3F box = fvo->getObjBox();
  742. box.getCenter(&center);
  743. front = center;
  744. front.y = box.maxExtents.y; // should be true for all these objects
  745. obj->getAIInfo()->mObj->getWorldBox().getCenter(&center);
  746. front = center + front;
  747. Point3F objFront = front;
  748. Point3F offset = front - center;
  749. EulerF rot;
  750. rot = mat.toEuler();
  751. MatrixF transform(rot);
  752. transform.mulV(offset, &wFront);
  753. front = wFront + center;
  754. Point3F ftoc;
  755. ftoc.x = mFabs(front.x - center.x);
  756. ftoc.y = mFabs(front.y - center.y);
  757. ftoc.z = mFabs(front.z - center.z);
  758. F32 fToc = mSqrt((ftoc.x * ftoc.x) + (ftoc.y * ftoc.y));
  759. Point3F ltoc;
  760. ltoc.x = mFabs(desired.x - center.x);
  761. ltoc.y = mFabs(desired.y - center.y);
  762. ltoc.z = mFabs(desired.z - center.z);
  763. F32 lToc = mSqrt((ltoc.x * ltoc.x) + (ltoc.y * ltoc.y));
  764. Point3F ftol;
  765. ftol.x = mFabs(front.x - desired.x);
  766. ftol.y = mFabs(front.y - desired.y);
  767. ftol.z = mFabs(front.z - desired.z);
  768. F32 fTol = mSqrt((ftol.x * ftol.x) + (ftol.y * ftol.y));
  769. F32 myAngle = mAcos(((lToc * lToc) + (fToc * fToc) - (fTol * fTol)) / (2 * lToc * fToc));
  770. F32 finalYaw = mRadToDeg(myAngle);
  771. F32 maxSteeringAngle = 0;
  772. VehicleData* vd = (VehicleData*)(fvo->getDataBlock());
  773. maxSteeringAngle = vd->maxSteeringAngle;
  774. Point2F steering = fvo->getSteering();
  775. if (finalYaw < 5 && steering.x != 0.0f)
  776. steerState = Straight;
  777. else if (finalYaw < 5)
  778. steerState = SteerNull;
  779. else
  780. {// Quickly Hack out left or right turn info
  781. Point3F rotData = objFront - desired;
  782. MatrixF leftM(-rot);
  783. Point3F leftP;
  784. leftM.mulV(rotData, &leftP);
  785. leftP = leftP + desired;
  786. if (leftP.x < desired.x)
  787. steerState = Right;
  788. else
  789. steerState = Left;
  790. }
  791. F32 throttle = fvo->getThrottle();
  792. if (throttle < 0.0f && steerState != Straight)
  793. {
  794. F32 reverseReduction = 0.25;
  795. steering.x = steering.x * reverseReduction * throttle;
  796. }
  797. F32 turnAdjust = myAngle - steering.x;
  798. F32 steer = 0;
  799. switch (steerState)
  800. {
  801. case Left:
  802. steer = myAngle < maxSteeringAngle ? -turnAdjust : -maxSteeringAngle - steering.x;
  803. break;
  804. case Right:
  805. steer = myAngle < maxSteeringAngle ? turnAdjust : maxSteeringAngle - steering.x;
  806. break;
  807. case Straight:
  808. steer = -steering.x;
  809. break;
  810. default:
  811. break;
  812. };
  813. // Con::printf("AI Steering : %f", steer);
  814. return steer;
  815. }
  816. void AIFlyingVehicleControllerData::resolveYaw(AIController* obj, Point3F location, Move* movePtr)
  817. {
  818. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  819. FlyingVehicle* fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj.getPointer());
  820. if (!fvo)
  821. {
  822. //cover the case of a connection controling an object in turn controlling another
  823. if (obj->getAIInfo()->mObj->getObjectMount())
  824. fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  825. }
  826. if (!fvo) return;//not a FlyingVehicle
  827. // Orient towards our destination.
  828. movePtr->yaw = getSteeringAngle(obj, location);
  829. };
  830. void AIFlyingVehicleControllerData::resolvePitch(AIController* obj, Point3F location, Move* movePtr)
  831. {
  832. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  833. FlyingVehicle* fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj.getPointer());
  834. if (!fvo)
  835. {
  836. //cover the case of a connection controling an object in turn controlling another
  837. if (obj->getAIInfo()->mObj->getObjectMount())
  838. fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  839. }
  840. if (!fvo) return;//not a FlyingVehicle
  841. F32 lastPitch = fvo->getSteering().y* (1.0f - fvo->getThrottle());
  842. Point3F up = fvo->getTransform().getUpVector();
  843. up.normalize();
  844. Point3F aimLoc = obj->mMovement.mAimLocation;
  845. aimLoc.z = mClampF(aimLoc.z, mFlightFloor, mFlightCeiling);
  846. // Get the AI to Target vector and normalize it.
  847. Point3F toTarg = location-aimLoc;
  848. toTarg.normalize();
  849. F32 dotPitch = mDot(up, toTarg);
  850. if (mFabs(dotPitch) > 0.05f)
  851. movePtr->pitch = dotPitch - lastPitch;
  852. else
  853. movePtr->pitch = -lastPitch;
  854. }
  855. void AIFlyingVehicleControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  856. {
  857. if (obj->mMovement.mMoveState < AIController::ModeSlowing) return;
  858. FlyingVehicle* fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj.getPointer());
  859. if (!fvo)
  860. {
  861. //cover the case of a connection controling an object in turn controlling another
  862. if (obj->getAIInfo()->mObj->getObjectMount())
  863. fvo = dynamic_cast<FlyingVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  864. }
  865. if (!fvo) return;//not a FlyingVehicle
  866. Parent::resolveSpeed(obj, location, movePtr);
  867. movePtr->x = 0;
  868. movePtr->y = mMax(movePtr->y, 0.0f);
  869. }
  870. #endif //_AICONTROLLER_H_