AIController.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. IMPLEMENT_CONOBJECT(AIController);
  25. //-----------------------------------------------------------------------------
  26. void AIController::throwCallback(const char* name)
  27. {
  28. Con::executef(mControllerData, name, getIdString()); //controller data callbacks
  29. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  30. if (!gbo) return;
  31. Con::executef(gbo->getDataBlock(), name, getAIInfo()->mObj->getIdString()); //legacy support for object db callbacks
  32. }
  33. void AIController::initPersistFields()
  34. {
  35. addProtectedField("ControllerData", TYPEID< AIControllerData >(), Offset(mControllerData, AIController),
  36. &setControllerDataProperty, &defaultProtectedGetFn,
  37. "Script datablock used for game objects.");
  38. addFieldV("MoveSpeed", TypeRangedF32, Offset(mMovement.mMoveSpeed, AIController), &CommonValidators::PositiveFloat,
  39. "@brief default move sepeed.");
  40. }
  41. bool AIController::setControllerDataProperty(void* obj, const char* index, const char* db)
  42. {
  43. if (db == NULL || !db[0])
  44. {
  45. Con::errorf("AIController::setControllerDataProperty - Can't unset ControllerData on AIController objects");
  46. return false;
  47. }
  48. AIController* object = static_cast<AIController*>(obj);
  49. AIControllerData* data;
  50. if (Sim::findObject(db, data))
  51. {
  52. object->mControllerData = data;
  53. return true;
  54. }
  55. Con::errorf("AIController::setControllerDataProperty - Could not find ControllerData \"%s\"", db);
  56. return false;
  57. }
  58. #ifdef TORQUE_NAVIGATION_ENABLED
  59. bool AIController::getAIMove(Move* movePtr)
  60. {
  61. *movePtr = NullMove;
  62. ShapeBase* sbo = dynamic_cast<ShapeBase*>(getAIInfo()->mObj.getPointer());
  63. if (!sbo) return false;
  64. // Use the eye as the current position.
  65. MatrixF eye;
  66. sbo->getEyeTransform(&eye);
  67. Point3F location = eye.getPosition();
  68. Point3F rotation = sbo->getTransform().getForwardVector();
  69. #ifdef TORQUE_NAVIGATION_ENABLED
  70. if (sbo->getDamageState() == ShapeBase::Enabled)
  71. {
  72. if (mMovement.mMoveState != ModeStop)
  73. getNav()->updateNavMesh();
  74. if (!getGoal()->mObj.isNull())
  75. {
  76. if (getNav()->mPathData.path.isNull())
  77. {
  78. if (getGoal()->getDist() > mControllerData->mMoveTolerance)
  79. getNav()->followObject(getGoal());
  80. }
  81. else
  82. {
  83. if (getGoal()->getDist() > mControllerData->mMoveTolerance)
  84. getNav()->repath();
  85. if (getAim()->getDist() < mControllerData->mMoveTolerance)
  86. {
  87. getNav()->clearPath();
  88. mMovement.mMoveState = ModeStop;
  89. throwCallback("onTargetInRange");
  90. }
  91. else if (getAim()->getDist() < mControllerData->mAttackRadius)
  92. {
  93. throwCallback("onTargetInFiringRange");
  94. }
  95. }
  96. }
  97. }
  98. #endif // TORQUE_NAVIGATION_ENABLED
  99. // Orient towards the aim point, aim object, or towards
  100. // our destination.
  101. if (getAim()->mObj || getAim()->mPosSet || mMovement.mMoveState != ModeStop)
  102. {
  103. // Update the aim position if we're aiming for an object or explicit position
  104. if (getAim()->mObj || getAim()->mPosSet)
  105. mMovement.mAimLocation = getAim()->getPosition();
  106. else
  107. mMovement.mAimLocation = mMovement.mMoveDestination;
  108. mControllerData->resolveYaw(this, location, movePtr);
  109. mControllerData->resolvePitch(this, location, movePtr);
  110. mControllerData->resolveRoll(this, location, movePtr);
  111. mControllerData->resolveSpeed(this, location, movePtr);
  112. mControllerData->resolveStuck(this);
  113. }
  114. // Test for target location in sight if it's an object. The LOS is
  115. // run from the eye position to the center of the object's bounding,
  116. // which is not very accurate.
  117. if (getAim()->mObj)
  118. {
  119. GameBase* gbo = dynamic_cast<GameBase*>(getAIInfo()->mObj.getPointer());
  120. if (getAim()->checkInLos(gbo))
  121. {
  122. if (!getAim()->mTargetInLOS)
  123. {
  124. throwCallback("onTargetEnterLOS");
  125. getAim()->mTargetInLOS = true;
  126. }
  127. }
  128. else if (getAim()->mTargetInLOS)
  129. {
  130. throwCallback("onTargetExitLOS");
  131. getAim()->mTargetInLOS = false;
  132. }
  133. }
  134. /*
  135. // Replicate the trigger state into the move so that
  136. // triggers can be controlled from scripts.
  137. for (U32 i = 0; i < MaxTriggerKeys; i++)
  138. movePtr->trigger[i] = getImageTriggerState(i);
  139. */
  140. #ifdef TORQUE_NAVIGATION_ENABLED
  141. if (getNav()->mJump == AINavigation::Now)
  142. {
  143. movePtr->trigger[2] = true;
  144. getNav()->mJump = AINavigation::None;
  145. }
  146. else if (getNav()->mJump == AINavigation::Ledge)
  147. {
  148. // If we're not touching the ground, jump!
  149. RayInfo info;
  150. if (!getAIInfo()->mObj->getContainer()->castRay(getAIInfo()->getPosition(), getAIInfo()->getPosition() - Point3F(0, 0, 0.4f), StaticShapeObjectType, &info))
  151. {
  152. movePtr->trigger[2] = true;
  153. getNav()->mJump = AINavigation::None;
  154. }
  155. }
  156. #endif // TORQUE_NAVIGATION_ENABLED
  157. return true;
  158. }
  159. void AIController::clearCover()
  160. {
  161. // Notify cover that we are no longer on our way.
  162. if (!getCover()->mCoverPoint.isNull())
  163. getCover()->mCoverPoint->setOccupied(false);
  164. SAFE_DELETE(mCover);
  165. }
  166. //-----------------------------------------------------------------------------
  167. IMPLEMENT_CO_DATABLOCK_V1(AIControllerData);
  168. void AIControllerData::resolveYaw(AIController* obj, Point3F location, Move* move)
  169. {
  170. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  171. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  172. Point3F rotation = obj->getAIInfo()->mObj->getTransform().getForwardVector();
  173. if (!mIsZero(xDiff) || !mIsZero(yDiff))
  174. {
  175. // First do Yaw
  176. // use the cur yaw between -Pi and Pi
  177. F32 curYaw = rotation.z;
  178. while (curYaw > M_2PI_F)
  179. curYaw -= M_2PI_F;
  180. while (curYaw < -M_2PI_F)
  181. curYaw += M_2PI_F;
  182. // find the yaw offset
  183. F32 newYaw = mAtan2(xDiff, yDiff);
  184. F32 yawDiff = newYaw - curYaw;
  185. // make it between 0 and 2PI
  186. if (yawDiff < 0.0f)
  187. yawDiff += M_2PI_F;
  188. else if (yawDiff >= M_2PI_F)
  189. yawDiff -= M_2PI_F;
  190. // now make sure we take the short way around the circle
  191. if (yawDiff > M_PI_F)
  192. yawDiff -= M_2PI_F;
  193. else if (yawDiff < -M_PI_F)
  194. yawDiff += M_2PI_F;
  195. move->yaw = yawDiff;
  196. }
  197. }
  198. void AIControllerData::resolveRoll(AIController* obj, Point3F location, Move* movePtr)
  199. {
  200. }
  201. void AIControllerData::resolveSpeed(AIController* obj, Point3F location, Move* movePtr)
  202. {
  203. // Move towards the destination
  204. if (obj->mMovement.mMoveState != AIController::ModeStop)
  205. {
  206. F32 xDiff = obj->mMovement.mMoveDestination.x - location.x;
  207. F32 yDiff = obj->mMovement.mMoveDestination.y - location.y;
  208. Point3F rotation = obj->getAIInfo()->mObj->getTransform().getForwardVector();
  209. // Check if we should mMove, or if we are 'close enough'
  210. if (mFabs(xDiff) < mMoveTolerance && mFabs(yDiff) < mMoveTolerance)
  211. {
  212. obj->mMovement.mMoveState = AIController::ModeStop;
  213. obj->getNav()->onReachDestination();
  214. }
  215. else
  216. {
  217. // Build move direction in world space
  218. if (mIsZero(xDiff))
  219. movePtr->y = (location.y > obj->mMovement.mMoveDestination.y) ? -1.0f : 1.0f;
  220. else
  221. if (mIsZero(yDiff))
  222. movePtr->x = (location.x > obj->mMovement.mMoveDestination.x) ? -1.0f : 1.0f;
  223. else
  224. if (mFabs(xDiff) > mFabs(yDiff))
  225. {
  226. F32 value = mFabs(yDiff / xDiff);
  227. movePtr->y = (location.y > obj->mMovement.mMoveDestination.y) ? -value : value;
  228. movePtr->x = (location.x > obj->mMovement.mMoveDestination.x) ? -1.0f : 1.0f;
  229. }
  230. else
  231. {
  232. F32 value = mFabs(xDiff / yDiff);
  233. movePtr->x = (location.x > obj->mMovement.mMoveDestination.x) ? -value : value;
  234. movePtr->y = (location.y > obj->mMovement.mMoveDestination.y) ? -1.0f : 1.0f;
  235. }
  236. // Rotate the move into object space (this really only needs
  237. // a 2D matrix)
  238. Point3F newMove;
  239. MatrixF moveMatrix;
  240. moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
  241. moveMatrix.mulV(Point3F(movePtr->x, movePtr->y, 0.0f), &newMove);
  242. movePtr->x = newMove.x;
  243. movePtr->y = newMove.y;
  244. // Set movement speed. We'll slow down once we get close
  245. // to try and stop on the spot...
  246. if (obj->mMovement.mMoveSlowdown)
  247. {
  248. F32 speed = obj->mMovement.mMoveSpeed;
  249. F32 dist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  250. F32 maxDist = mMoveTolerance * 2;
  251. if (dist < maxDist)
  252. speed *= dist / maxDist;
  253. movePtr->x *= speed;
  254. movePtr->y *= speed;
  255. obj->mMovement.mMoveState = AIController::ModeSlowing;
  256. }
  257. else
  258. {
  259. movePtr->x *= obj->mMovement.mMoveSpeed;
  260. movePtr->y *= obj->mMovement.mMoveSpeed;
  261. obj->mMovement.mMoveState = AIController::ModeMove;
  262. }
  263. }
  264. }
  265. }
  266. void AIControllerData::resolveStuck(AIController* obj)
  267. {
  268. ShapeBase* sbo = dynamic_cast<ShapeBase*>(obj->getAIInfo()->mObj.getPointer());
  269. // Don't check for ai stuckness if animation during
  270. // an anim-clip effect override.
  271. if (sbo->getDamageState() == ShapeBase::Enabled && !(sbo->anim_clip_flags & ShapeBase::ANIM_OVERRIDDEN) && !sbo->isAnimationLocked()) {
  272. if (obj->mMovement.mMoveStuckTestCountdown > 0)
  273. --obj->mMovement.mMoveStuckTestCountdown;
  274. else
  275. {
  276. // We should check to see if we are stuck...
  277. F32 locationDelta = (obj->getAIInfo()->getPosition() - obj->getAIInfo()->mLastPos).len();
  278. if (locationDelta < mMoveStuckTolerance && (sbo->getDamageState() == ShapeBase::Enabled))
  279. {
  280. // If we are slowing down, then it's likely that our location delta will be less than
  281. // our move stuck tolerance. Because we can be both slowing and stuck
  282. // we should TRY to check if we've moved. This could use better detection.
  283. if (obj->mMovement.mMoveState != AIController::ModeSlowing || locationDelta == 0)
  284. {
  285. obj->mMovement.mMoveState = AIController::ModeStuck;
  286. obj->throwCallback("onStuck");
  287. }
  288. }
  289. }
  290. obj->getAIInfo()->mLastPos = obj->getAIInfo()->getPosition();
  291. }
  292. }
  293. void AIControllerData::initPersistFields()
  294. {
  295. docsURL;
  296. addGroup("AI");
  297. addFieldV("moveTolerance", TypeRangedF32, Offset(mMoveTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  298. "@brief Distance from destination before stopping.\n\n"
  299. "When the AIPlayer is moving to a given destination it will move to within "
  300. "this distance of the destination and then stop. By providing this tolerance "
  301. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  302. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  303. addFieldV("followTolerance", TypeRangedF32, Offset(mFollowTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  304. "@brief Distance from destination before stopping.\n\n"
  305. "When the AIPlayer is moving to a given destination it will move to within "
  306. "this distance of the destination and then stop. By providing this tolerance "
  307. "it helps the AIPlayer from never reaching its destination due to minor obstacles, "
  308. "rounding errors on its position calculation, etc. By default it is set to 0.25.\n");
  309. addFieldV("moveStuckTolerance", TypeRangedF32, Offset(mMoveStuckTolerance, AIControllerData), &CommonValidators::PositiveFloat,
  310. "@brief Distance tolerance on stuck check.\n\n"
  311. "When the AIPlayer is moving to a given destination, if it ever moves less than "
  312. "this tolerance during a single tick, the AIPlayer is considered stuck. At this point "
  313. "the onMoveStuck() callback is called on the datablock.\n");
  314. addFieldV("moveStuckTestDelay", TypeRangedS32, Offset(mMoveStuckTestDelay, AIControllerData), &CommonValidators::PositiveInt,
  315. "@brief The number of ticks to wait before testing if the AIPlayer is stuck.\n\n"
  316. "When the AIPlayer is asked to move, this property is the number of ticks to wait "
  317. "before the AIPlayer starts to check if it is stuck. This delay allows the AIPlayer "
  318. "to accelerate to full speed without its initial slow start being considered as stuck.\n"
  319. "@note Set to zero to have the stuck test start immediately.\n");
  320. addFieldV("AttackRadius", TypeRangedF32, Offset(mAttackRadius, AIControllerData), &CommonValidators::PositiveFloat,
  321. "@brief Distance considered in firing range for callback purposes.");
  322. endGroup("AI");
  323. #ifdef TORQUE_NAVIGATION_ENABLED
  324. addGroup("Pathfinding");
  325. addField("allowWalk", TypeBool, Offset(mLinkTypes.walk, AIControllerData),
  326. "Allow the character to walk on dry land.");
  327. addField("allowJump", TypeBool, Offset(mLinkTypes.jump, AIControllerData),
  328. "Allow the character to use jump links.");
  329. addField("allowDrop", TypeBool, Offset(mLinkTypes.drop, AIControllerData),
  330. "Allow the character to use drop links.");
  331. addField("allowSwim", TypeBool, Offset(mLinkTypes.swim, AIControllerData),
  332. "Allow the character to move in water.");
  333. addField("allowLedge", TypeBool, Offset(mLinkTypes.ledge, AIControllerData),
  334. "Allow the character to jump ledges.");
  335. addField("allowClimb", TypeBool, Offset(mLinkTypes.climb, AIControllerData),
  336. "Allow the character to use climb links.");
  337. addField("allowTeleport", TypeBool, Offset(mLinkTypes.teleport, AIControllerData),
  338. "Allow the character to use teleporters.");
  339. endGroup("Pathfinding");
  340. #endif // TORQUE_NAVIGATION_ENABLED
  341. Parent::initPersistFields();
  342. }
  343. //-----------------------------------------------------------------------------
  344. //-----------------------------------------------------------------------------
  345. IMPLEMENT_CO_DATABLOCK_V1(AIPlayerControllerData);
  346. void AIPlayerControllerData::resolvePitch(AIController* obj, Point3F location, Move* movePtr)
  347. {
  348. Player* po = dynamic_cast<Player*>(obj->getAIInfo()->mObj.getPointer());
  349. if (!po) return;//not a player
  350. if (obj->getAim()->mObj || obj->getAim()->mPosSet || obj->mMovement.mMoveState != AIController::ModeStop)
  351. {
  352. // Next do pitch.
  353. if (!obj->getAim()->mObj && !obj->getAim()->mPosSet)
  354. {
  355. // Level out if were just looking at our next way point.
  356. Point3F headRotation = po->getHeadRotation();
  357. movePtr->pitch = -headRotation.x;
  358. }
  359. else
  360. {
  361. F32 xDiff = obj->mMovement.mAimLocation.x - location.x;
  362. F32 yDiff = obj->mMovement.mAimLocation.y - location.y;
  363. // This should be adjusted to run from the
  364. // eye point to the object's center position. Though this
  365. // works well enough for now.
  366. F32 vertDist = obj->mMovement.mAimLocation.z - location.z;
  367. F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
  368. F32 newPitch = mAtan2(horzDist, vertDist) - (M_PI_F / 2.0f);
  369. if (mFabs(newPitch) > 0.01f)
  370. {
  371. Point3F headRotation = po->getHeadRotation();
  372. movePtr->pitch = newPitch - headRotation.x;
  373. }
  374. }
  375. }
  376. else
  377. {
  378. // Level out if we're not doing anything else
  379. Point3F headRotation = po->getHeadRotation();
  380. movePtr->pitch = -headRotation.x;
  381. }
  382. }
  383. #endif //_AICONTROLLER_H_