AIController.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. // Test for target location in sight if it's an object. The LOS is
  109. // run from the eye position to the center of the object's bounding,
  110. // which is not very accurate.
  111. if (getAim() && getAim()->mObj)
  112. {
  113. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  114. if (getAim()->checkInLos(gbo))
  115. {
  116. if (!getAim()->mTargetInLOS)
  117. {
  118. throwCallback("onTargetEnterLOS");
  119. getAim()->mTargetInLOS = true;
  120. }
  121. }
  122. else if (getAim()->mTargetInLOS)
  123. {
  124. throwCallback("onTargetExitLOS");
  125. getAim()->mTargetInLOS = false;
  126. }
  127. }
  128. #ifdef TORQUE_NAVIGATION_ENABLED
  129. if (sbo->getDamageState() == ShapeBase::Enabled && getGoal())
  130. {
  131. if (mMovement.mMoveState != ModeStop)
  132. getNav()->updateNavMesh();
  133. if (getNav()->mPathData.path.isNull())
  134. {
  135. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  136. {
  137. if (getGoal()->mObj.isValid())
  138. getNav()->followObject(getGoal()->mObj, mControllerData->mFollowTolerance);
  139. else if (getGoal()->mPosSet)
  140. getNav()->setPathDestination(getGoal()->getPosition());
  141. }
  142. }
  143. else
  144. {
  145. if (getGoal()->getDist() > mControllerData->mFollowTolerance)
  146. {
  147. F32 raylength = 2.0; //for vehicles
  148. SceneObject* obj = getAIInfo()->mObj->getObjectMount();
  149. if (!obj)
  150. {
  151. obj = getAIInfo()->mObj;
  152. raylength = 0.001f; //for jumping
  153. }
  154. RayInfo info;
  155. if (obj->getContainer()->castRay(obj->getPosition(), obj->getPosition() - Point3F(0, 0, raylength), StaticShapeObjectType, &info))
  156. {
  157. getNav()->repath();
  158. }
  159. getGoal()->mInRange = false;
  160. }
  161. if (getGoal()->getDist() < mControllerData->mFollowTolerance )
  162. {
  163. getNav()->clearPath();
  164. mMovement.mMoveState = ModeStop;
  165. if (!getGoal()->mInRange)
  166. {
  167. getGoal()->mInRange = true;
  168. throwCallback("onTargetInRange");
  169. }
  170. else getGoal()->mInRange = false;
  171. }
  172. else
  173. {
  174. if (getGoal()->getDist() < mControllerData->mAttackRadius )
  175. {
  176. if (!getGoal()->mInFiringRange)
  177. {
  178. getGoal()->mInFiringRange = true;
  179. throwCallback("onTargetInFiringRange");
  180. }
  181. }
  182. else getGoal()->mInFiringRange = false;
  183. }
  184. }
  185. }
  186. #endif // TORQUE_NAVIGATION_ENABLED
  187. // Orient towards the aim point, aim object, or towards
  188. // our destination.
  189. if (getAim() || mMovement.mMoveState != ModeStop)
  190. {
  191. // Update the aim position if we're aiming for an object or explicit position
  192. if (getAim())
  193. mMovement.mAimLocation = getAim()->getPosition();
  194. else
  195. mMovement.mAimLocation = getNav()->getMoveDestination();
  196. mControllerData->resolveYawPtr(this, location, movePtr);
  197. mControllerData->resolvePitchPtr(this, location, movePtr);
  198. mControllerData->resolveRollPtr(this, location, movePtr);
  199. if (mMovement.mMoveState != AIController::ModeStop)
  200. {
  201. F32 xDiff = getNav()->getMoveDestination().x - location.x;
  202. F32 yDiff = getNav()->getMoveDestination().y - location.y;
  203. if (mFabs(xDiff) < mControllerData->mMoveTolerance && mFabs(yDiff) < mControllerData->mMoveTolerance)
  204. {
  205. getNav()->onReachDestination();
  206. }
  207. else
  208. {
  209. mControllerData->resolveSpeedPtr(this, location, movePtr);
  210. mControllerData->resolveStuckPtr(this);
  211. }
  212. }
  213. }
  214. mControllerData->resolveTriggerStatePtr(this, movePtr);
  215. getAIInfo()->mLastPos = getAIInfo()->getPosition();
  216. return true;
  217. }
  218. void AIController::clearCover()
  219. {
  220. // Notify cover that we are no longer on our way.
  221. if (getCover() && !getCover()->mCoverPoint.isNull())
  222. getCover()->mCoverPoint->setOccupied(false);
  223. SAFE_DELETE(mCover);
  224. }
  225. void AIController::Movement::stopMove()
  226. {
  227. mMoveState = ModeStop;
  228. #ifdef TORQUE_NAVIGATION_ENABLED
  229. getCtrl()->getNav()->clearPath();
  230. getCtrl()->clearCover();
  231. getCtrl()->getNav()->clearFollow();
  232. #endif
  233. }
  234. void AIController::Movement::onStuck()
  235. {
  236. mMoveState = AIController::ModeStuck;
  237. getCtrl()->throwCallback("onMoveStuck");
  238. #ifdef TORQUE_NAVIGATION_ENABLED
  239. if (!getCtrl()->getNav()->getPath().isNull())
  240. getCtrl()->getNav()->repath();
  241. #endif
  242. }
  243. DefineEngineMethod(AIController, setMoveSpeed, void, (F32 speed), ,
  244. "@brief Sets the move speed for an AI object.\n\n"
  245. "@param speed A speed multiplier between 0.0 and 1.0. "
  246. "This is multiplied by the AIPlayer's base movement rates (as defined in "
  247. "its PlayerData datablock)\n\n"
  248. "@see getMoveDestination()\n")
  249. {
  250. object->mMovement.setMoveSpeed(speed);
  251. }
  252. DefineEngineMethod(AIController, getMoveSpeed, F32, (), ,
  253. "@brief Gets the move speed of an AI object.\n\n"
  254. "@return A speed multiplier between 0.0 and 1.0.\n\n"
  255. "@see setMoveSpeed()\n")
  256. {
  257. return object->mMovement.getMoveSpeed();
  258. }
  259. DefineEngineMethod(AIController, stop, void, (), ,
  260. "@brief Tells the AIPlayer to stop moving.\n\n")
  261. {
  262. object->mMovement.stopMove();
  263. }
  264. /**
  265. * Set the state of a movement trigger.
  266. *
  267. * @param slot The trigger slot to set
  268. * @param isSet set/unset the trigger
  269. */
  270. void AIController::TriggerState::setMoveTrigger(U32 slot, const bool isSet)
  271. {
  272. if (slot >= MaxTriggerKeys)
  273. {
  274. Con::errorf("Attempting to set an invalid trigger slot (%i)", slot);
  275. }
  276. else
  277. {
  278. mMoveTriggers[slot] = isSet; // set the trigger
  279. mControllerRef->getAIInfo()->mObj->setMaskBits(ShapeBase::NoWarpMask); // force the client to updateMove
  280. }
  281. }
  282. /**
  283. * Get the state of a movement trigger.
  284. *
  285. * @param slot The trigger slot to query
  286. * @return True if the trigger is set, false if it is not set
  287. */
  288. bool AIController::TriggerState::getMoveTrigger(U32 slot) const
  289. {
  290. if (slot >= MaxTriggerKeys)
  291. {
  292. Con::errorf("Attempting to get an invalid trigger slot (%i)", slot);
  293. return false;
  294. }
  295. else
  296. {
  297. return mMoveTriggers[slot];
  298. }
  299. }
  300. /**
  301. * Clear the trigger state for all movement triggers.
  302. */
  303. void AIController::TriggerState::clearMoveTriggers()
  304. {
  305. for (U32 i = 0; i < MaxTriggerKeys; i++)
  306. setMoveTrigger(i, false);
  307. }
  308. //-----------------------------------------------------------------------------
  309. IMPLEMENT_CO_DATABLOCK_V1(AIControllerData);
  310. void AIControllerData::resolveYaw(AIController* obj, Point3F location, Move* move)
  311. {
  312. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  313. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  314. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  315. if (!mIsZero(xDiff) || !mIsZero(yDiff))
  316. {
  317. // First do Yaw
  318. // use the cur yaw between -Pi and Pi
  319. F32 curYaw = rotation.z;
  320. while (curYaw > M_2PI_F)
  321. curYaw -= M_2PI_F;
  322. while (curYaw < -M_2PI_F)
  323. curYaw += M_2PI_F;
  324. // find the yaw offset
  325. F32 newYaw = mAtan2(xDiff, yDiff);
  326. F32 yawDiff = newYaw - curYaw;
  327. // make it between 0 and 2PI
  328. if (yawDiff < 0.0f)
  329. yawDiff += M_2PI_F;
  330. else if (yawDiff >= M_2PI_F)
  331. yawDiff -= M_2PI_F;
  332. // now make sure we take the short way around the circle
  333. if (yawDiff > M_PI_F)
  334. yawDiff -= M_2PI_F;
  335. else if (yawDiff < -M_PI_F)
  336. yawDiff += M_2PI_F;
  337. move->yaw = yawDiff;
  338. }
  339. }
  340. void AIControllerData::resolveRoll(AIController* obj, Point3F location, Move* movePtr)
  341. {
  342. }
  343. void AIControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  344. {
  345. F32 xDiff = obj->getNav()->getMoveDestination().x - location.x;
  346. F32 yDiff = obj->getNav()->getMoveDestination().y - location.y;
  347. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  348. // Build move direction in world space
  349. if (mIsZero(xDiff))
  350. movePtr->y = (location.y > obj->getNav()->getMoveDestination().y) ? -1.0f : 1.0f;
  351. else
  352. if (mIsZero(yDiff))
  353. movePtr->x = (location.x > obj->getNav()->getMoveDestination().x) ? -1.0f : 1.0f;
  354. else
  355. if (mFabs(xDiff) > mFabs(yDiff))
  356. {
  357. F32 value = mFabs(yDiff / xDiff);
  358. movePtr->y = (location.y > obj->getNav()->getMoveDestination().y) ? -value : value;
  359. movePtr->x = (location.x > obj->getNav()->getMoveDestination().x) ? -1.0f : 1.0f;
  360. }
  361. else
  362. {
  363. F32 value = mFabs(xDiff / yDiff);
  364. movePtr->x = (location.x > obj->getNav()->getMoveDestination().x) ? -value : value;
  365. movePtr->y = (location.y > obj->getNav()->getMoveDestination().y) ? -1.0f : 1.0f;
  366. }
  367. // Rotate the move into object space (this really only needs
  368. // a 2D matrix)
  369. Point3F newMove;
  370. MatrixF moveMatrix;
  371. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  372. moveMatrix.mulV(Point3F(movePtr->x, movePtr->y, 0.0f), &newMove);
  373. movePtr->x = newMove.x;
  374. movePtr->y = newMove.y;
  375. // Set movement speed. We'll slow down once we get close
  376. // to try and stop on the spot...
  377. if (obj->mMovement.mMoveSlowdown)
  378. {
  379. F32 speed = obj->mMovement.mMoveSpeed;
  380. F32 dist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  381. F32 maxDist = mMoveTolerance * 2;
  382. if (dist < maxDist)
  383. speed *= dist / maxDist;
  384. movePtr->x *= speed;
  385. movePtr->y *= speed;
  386. }
  387. else
  388. {
  389. movePtr->x *= obj->mMovement.mMoveSpeed;
  390. movePtr->y *= obj->mMovement.mMoveSpeed;
  391. }
  392. }
  393. void AIControllerData::resolveTriggerState(AIController* obj, Move* movePtr)
  394. {
  395. //check for scripted overides
  396. for (U32 slot = 0; slot < MaxTriggerKeys; slot++)
  397. {
  398. movePtr->trigger[slot] = obj->mTriggerState.mMoveTriggers[slot];
  399. }
  400. }
  401. void AIControllerData::resolveStuck(AIController* obj)
  402. {
  403. if (obj->mMovement.mMoveState == AIController::ModeStuck) return;
  404. if (!obj->getGoal()) return;
  405. ShapeBase* sbo = dynamic_cast<ShapeBase*>(obj->getAIInfo()->mObj.getPointer());
  406. // Don't check for ai stuckness if animation during
  407. // an anim-clip effect override.
  408. if (sbo->getDamageState() == ShapeBase::Enabled && !(sbo->anim_clip_flags & ShapeBase::ANIM_OVERRIDDEN) && !sbo->isAnimationLocked())
  409. {
  410. // We should check to see if we are stuck...
  411. F32 locationDelta = (obj->getAIInfo()->getPosition() - obj->getAIInfo()->mLastPos).len();
  412. if (locationDelta < mMoveStuckTolerance)
  413. {
  414. if (obj->mMovement.mMoveStuckTestCountdown > 0)
  415. --obj->mMovement.mMoveStuckTestCountdown;
  416. else
  417. {
  418. // If we are slowing down, then it's likely that our location delta will be less than
  419. // our move stuck tolerance. Because we can be both slowing and stuck
  420. // we should TRY to check if we've moved. This could use better detection.
  421. if (obj->mMovement.mMoveState != AIController::ModeSlowing || locationDelta == 0)
  422. {
  423. obj->mMovement.onStuck();
  424. obj->mMovement.mMoveStuckTestCountdown = obj->mControllerData->mMoveStuckTestDelay;
  425. }
  426. }
  427. }
  428. }
  429. }
  430. AIControllerData::AIControllerData()
  431. {
  432. mMoveTolerance = 0.25;
  433. mFollowTolerance = 1.0;
  434. mAttackRadius = 2.0;
  435. mMoveStuckTolerance = 0.01f;
  436. mMoveStuckTestDelay = 30;
  437. mLinkTypes = LinkData(AllFlags);
  438. mNavSize = AINavigation::Regular;
  439. mFlocking.mChance = 90;
  440. mFlocking.mMin = 1.0f;
  441. mFlocking.mMax = 3.0f;
  442. mFlocking.mSideStep = 0.01f;
  443. resolveYawPtr.bind(this, &AIControllerData::resolveYaw);
  444. resolvePitchPtr.bind(this, &AIControllerData::resolvePitch);
  445. resolveRollPtr.bind(this, &AIControllerData::resolveRoll);
  446. resolveSpeedPtr.bind(this, &AIControllerData::resolveSpeed);
  447. resolveTriggerStatePtr.bind(this, &AIControllerData::resolveTriggerState);
  448. resolveStuckPtr.bind(this, &AIControllerData::resolveStuck);
  449. }
  450. void AIControllerData::initPersistFields()
  451. {
  452. docsURL;
  453. addGroup("AI");
  454. addFieldV("moveTolerance", TypeRangedF32, Offset(mMoveTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  455. "@brief Distance from destination before stopping.\n\n"
  456. "When the AIPlayer is moving to a given destination it will move to within "
  457. "this distance of the destination and then stop. By providing this tolerance "
  458. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  459. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  460. addFieldV("followTolerance", TypeRangedF32, Offset(mFollowTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  461. "@brief Distance from destination before stopping.\n\n"
  462. "When the AIPlayer is moving to a given destination it will move to within "
  463. "this distance of the destination and then stop. By providing this tolerance "
  464. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  465. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  466. addFieldV("moveStuckTolerance", TypeRangedF32, Offset(mMoveStuckTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  467. "@brief Distance tolerance on stuck check.\n\n"
  468. "When the AIPlayer is moving to a given destination, if it ever moves less than "
  469. "this tolerance during a single tick, the AIPlayer is considered stuck. At this point "
  470. "the onMoveStuck() callback is called on the datablock.\n");
  471. addFieldV("moveStuckTestDelay", TypeRangedS32, Offset(mMoveStuckTestDelay, AIControllerData), &CommonValidators::PositiveInt,
  472. "@brief The number of ticks to wait before testing if the AIPlayer is stuck.\n\n"
  473. "When the AIPlayer is asked to move, this property is the number of ticks to wait "
  474. "before the AIPlayer starts to check if it is stuck. This delay allows the AIPlayer "
  475. "to accelerate to full speed without its initial slow start being considered as stuck.\n"
  476. "@note Set to zero to have the stuck test start immediately.\n");
  477. addFieldV("AttackRadius", TypeRangedF32, Offset(mAttackRadius, AIControllerData), &CommonValidators::PositiveFloat,
  478. "@brief Distance considered in firing range for callback purposes.");
  479. addFieldV("FlockChance", TypeRangedS32, Offset(mFlocking.mChance, AIControllerData), &CommonValidators::S32Percent,
  480. "@brief chance of flocking.");
  481. addFieldV("FlockMin", TypeRangedF32, Offset(mFlocking.mMin, AIControllerData), &CommonValidators::PositiveFloat,
  482. "@brief min flocking separation distance.");
  483. addFieldV("FlockMax", TypeRangedF32, Offset(mFlocking.mMax, AIControllerData), &CommonValidators::PositiveFloat,
  484. "@brief max flocking clustering distance.");
  485. addFieldV("FlockSideStep", TypeRangedF32, Offset(mFlocking.mSideStep, AIControllerData), &CommonValidators::PositiveFloat,
  486. "@brief Distance from destination before we stop moving out of the way.");
  487. endGroup("AI");
  488. #ifdef TORQUE_NAVIGATION_ENABLED
  489. addGroup("Pathfinding");
  490. addField("allowWalk", TypeBool, Offset(mLinkTypes.walk, AIControllerData),
  491. "Allow the character to walk on dry land.");
  492. addField("allowJump", TypeBool, Offset(mLinkTypes.jump, AIControllerData),
  493. "Allow the character to use jump links.");
  494. addField("allowDrop", TypeBool, Offset(mLinkTypes.drop, AIControllerData),
  495. "Allow the character to use drop links.");
  496. addField("allowSwim", TypeBool, Offset(mLinkTypes.swim, AIControllerData),
  497. "Allow the character to move in water.");
  498. addField("allowLedge", TypeBool, Offset(mLinkTypes.ledge, AIControllerData),
  499. "Allow the character to jump ledges.");
  500. addField("allowClimb", TypeBool, Offset(mLinkTypes.climb, AIControllerData),
  501. "Allow the character to use climb links.");
  502. addField("allowTeleport", TypeBool, Offset(mLinkTypes.teleport, AIControllerData),
  503. "Allow the character to use teleporters.");
  504. endGroup("Pathfinding");
  505. #endif // TORQUE_NAVIGATION_ENABLED
  506. Parent::initPersistFields();
  507. }
  508. //-----------------------------------------------------------------------------
  509. //-----------------------------------------------------------------------------
  510. IMPLEMENT_CO_DATABLOCK_V1(AIPlayerControllerData);
  511. void AIPlayerControllerData::resolvePitch(AIController* obj, Point3F location, Move* movePtr)
  512. {
  513. Player* po = dynamic_cast<Player*>(obj->getAIInfo()->mObj.getPointer());
  514. if (!po) return;//not a player
  515. if (obj->getAim() || obj->mMovement.mMoveState != AIController::ModeStop)
  516. {
  517. // Next do pitch.
  518. if (!obj->getAim())
  519. {
  520. // Level out if were just looking at our next way point.
  521. Point3F headRotation = po->getHeadRotation();
  522. movePtr->pitch = -headRotation.x;
  523. }
  524. else
  525. {
  526. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  527. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  528. // This should be adjusted to run from the
  529. // eye point to the object's center position. Though this
  530. // works well enough for now.
  531. F32 vertDist = obj->mMovement.mAimLocation.z - location.z;
  532. F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  533. F32 newPitch = mAtan2(horzDist, vertDist) - (M_PI_F / 2.0f);
  534. if (mFabs(newPitch) > 0.01f)
  535. {
  536. Point3F headRotation = po->getHeadRotation();
  537. movePtr->pitch = newPitch - headRotation.x;
  538. }
  539. }
  540. }
  541. else
  542. {
  543. // Level out if we're not doing anything else
  544. Point3F headRotation = po->getHeadRotation();
  545. movePtr->pitch = -headRotation.x;
  546. }
  547. }
  548. void AIPlayerControllerData::resolveTriggerState(AIController* obj, Move* movePtr)
  549. {
  550. Parent::resolveTriggerState(obj, movePtr);
  551. #ifdef TORQUE_NAVIGATION_ENABLED
  552. if (obj->getNav()->mJump == AINavigation::Now)
  553. {
  554. movePtr->trigger[2] = true;
  555. obj->getNav()->mJump = AINavigation::None;
  556. }
  557. else if (obj->getNav()->mJump == AINavigation::Ledge)
  558. {
  559. // If we're not touching the ground, jump!
  560. RayInfo info;
  561. if (!obj->getAIInfo()->mObj->getContainer()->castRay(obj->getAIInfo()->getPosition(), obj->getAIInfo()->getPosition() - Point3F(0, 0, 0.4f), StaticShapeObjectType, &info))
  562. {
  563. movePtr->trigger[2] = true;
  564. obj->getNav()->mJump = AINavigation::None;
  565. }
  566. }
  567. #endif // TORQUE_NAVIGATION_ENABLED
  568. }
  569. IMPLEMENT_CO_DATABLOCK_V1(AIWheeledVehicleControllerData);
  570. // Build a Triangle .. calculate angle of rotation required to meet target..
  571. // man there has to be a better way! >:)
  572. F32 AIWheeledVehicleControllerData::getSteeringAngle(AIController* obj, Point3F location)
  573. {
  574. WheeledVehicle* wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj.getPointer());
  575. if (!wvo)
  576. {
  577. //cover the case of a connection controling an object in turn controlling another
  578. if (obj->getAIInfo()->mObj->getObjectMount())
  579. wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  580. }
  581. if (!wvo) return 0;//not a WheeledVehicle
  582. DrivingState steerState = SteerNull;
  583. // What is our target
  584. Point3F desired;
  585. desired = obj->getNav()->getMoveDestination();
  586. MatrixF mat = wvo->getTransform();
  587. Point3F center, front;
  588. Point3F wFront;
  589. Box3F box = wvo->getObjBox();
  590. box.getCenter(&center);
  591. front = center;
  592. front.y = box.maxExtents.y; // should be true for all these objects
  593. obj->getAIInfo()->mObj->getWorldBox().getCenter(&center);
  594. front = center + front;
  595. Point3F objFront = front;
  596. Point3F offset = front - center;
  597. EulerF rot;
  598. rot = mat.toEuler();
  599. MatrixF transform(rot);
  600. transform.mulV(offset, &wFront);
  601. front = wFront + center;
  602. Point3F ftoc;
  603. ftoc.x = mFabs(front.x - center.x);
  604. ftoc.y = mFabs(front.y - center.y);
  605. ftoc.z = mFabs(front.z - center.z);
  606. F32 fToc = mSqrt((ftoc.x * ftoc.x) + (ftoc.y * ftoc.y));
  607. Point3F ltoc;
  608. ltoc.x = mFabs(desired.x - center.x);
  609. ltoc.y = mFabs(desired.y - center.y);
  610. ltoc.z = mFabs(desired.z - center.z);
  611. F32 lToc = mSqrt((ltoc.x * ltoc.x) + (ltoc.y * ltoc.y));
  612. Point3F ftol;
  613. ftol.x = mFabs(front.x - desired.x);
  614. ftol.y = mFabs(front.y - desired.y);
  615. ftol.z = mFabs(front.z - desired.z);
  616. F32 fTol = mSqrt((ftol.x * ftol.x) + (ftol.y * ftol.y));
  617. F32 myAngle = mAcos(((lToc * lToc) + (fToc * fToc) - (fTol * fTol)) / (2 * lToc * fToc));
  618. F32 finalYaw = mRadToDeg(myAngle);
  619. F32 maxSteeringAngle = 0;
  620. VehicleData* vd = (VehicleData*)(wvo->getDataBlock());
  621. maxSteeringAngle = vd->maxSteeringAngle;
  622. Point2F steering = wvo->getSteering();
  623. if (finalYaw < 5 && steering.x != 0.0f)
  624. steerState = Straight;
  625. else if (finalYaw < 5)
  626. steerState = SteerNull;
  627. else
  628. {// Quickly Hack out left or right turn info
  629. Point3F rotData = objFront - desired;
  630. MatrixF leftM(-rot);
  631. Point3F leftP;
  632. leftM.mulV(rotData, &leftP);
  633. leftP = leftP + desired;
  634. if (leftP.x < desired.x)
  635. steerState = Right;
  636. else
  637. steerState = Left;
  638. }
  639. F32 throttle = wvo->getThrottle();
  640. if (throttle < 0.0f && steerState != Straight)
  641. {
  642. F32 reverseReduction = 0.25;
  643. steering.x = steering.x * reverseReduction * throttle;
  644. }
  645. F32 turnAdjust = myAngle - steering.x;
  646. F32 steer = 0;
  647. switch (steerState)
  648. {
  649. case Left:
  650. steer = myAngle < maxSteeringAngle ? -turnAdjust : -maxSteeringAngle - steering.x;
  651. break;
  652. case Right:
  653. steer = myAngle < maxSteeringAngle ? turnAdjust : maxSteeringAngle - steering.x;
  654. break;
  655. case Straight:
  656. steer = -steering.x;
  657. break;
  658. default:
  659. break;
  660. };
  661. // Con::printf("AI Steering : %f", steer);
  662. return steer;
  663. }
  664. void AIWheeledVehicleControllerData::resolveYaw(AIController* obj, Point3F location, Move* movePtr)
  665. {
  666. WheeledVehicle* wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj.getPointer());
  667. if (!wvo)
  668. {
  669. //cover the case of a connection controling an object in turn controlling another
  670. if (obj->getAIInfo()->mObj->getObjectMount())
  671. wvo = dynamic_cast<WheeledVehicle*>(obj->getAIInfo()->mObj->getObjectMount());
  672. }
  673. if (!wvo) return;//not a WheeledVehicle
  674. // Orient towards our destination.
  675. if (obj->mMovement.mMoveState == AIController::ModeMove || obj->mMovement.mMoveState == AIController::ModeReverse) {
  676. movePtr->yaw = getSteeringAngle(obj, location);
  677. }
  678. };
  679. void AIWheeledVehicleControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  680. {
  681. F32 xDiff = obj->getNav()->getMoveDestination().x - location.x;
  682. F32 yDiff = obj->getNav()->getMoveDestination().y - location.y;
  683. Point3F rotation = obj->getAIInfo()->mObj->getTransform().toEuler();
  684. Point2F movTarg;
  685. // Build move direction in world space
  686. if (mIsZero(xDiff))
  687. movTarg.y = (location.y > obj->getNav()->getMoveDestination().y) ? -1.0f : 1.0f;
  688. else
  689. {
  690. if (mIsZero(yDiff))
  691. movTarg.x = (location.x > obj->getNav()->getMoveDestination().x) ? -1.0f : 1.0f;
  692. else
  693. {
  694. if (mFabs(xDiff) > mFabs(yDiff))
  695. {
  696. F32 value = mFabs(yDiff / xDiff);
  697. movTarg.y = (location.y > obj->getNav()->getMoveDestination().y) ? -value : value;
  698. movTarg.x = (location.x > obj->getNav()->getMoveDestination().x) ? -1.0f : 1.0f;
  699. }
  700. else
  701. {
  702. F32 value = mFabs(xDiff / yDiff);
  703. movTarg.x = (location.x > obj->getNav()->getMoveDestination().x) ? -value : value;
  704. movTarg.y = (location.y > obj->getNav()->getMoveDestination().y) ? -1.0f : 1.0f;
  705. }
  706. }
  707. }
  708. // Rotate the move into object space (this really only needs
  709. // a 2D matrix)
  710. Point3F newMove;
  711. MatrixF moveMatrix;
  712. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  713. moveMatrix.mulV(Point3F(movTarg.x, movTarg.y, 0.0f), &newMove);
  714. movTarg.y = newMove.y;
  715. // Set Throttle. We'll slow down once we get close
  716. // to try and stop on the spot...
  717. if (obj->mMovement.mMoveSlowdown)
  718. {
  719. F32 throttle = obj->mMovement.mMoveSpeed;
  720. F32 dist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  721. F32 maxDist = mMoveTolerance * 2;
  722. if (dist < maxDist)
  723. throttle *= dist / maxDist;
  724. movePtr->y *= throttle;
  725. }
  726. else
  727. {
  728. movePtr->y *= obj->mMovement.mMoveSpeed;
  729. }
  730. }
  731. #endif //_AICONTROLLER_H_