aiTurretShape.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  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 "T3D/turret/aiTurretShape.h"
  23. #include "console/console.h"
  24. #include "console/consoleTypes.h"
  25. #include "console/engineAPI.h"
  26. #include "core/stream/bitStream.h"
  27. #include "math/mMath.h"
  28. #include "math/mathIO.h"
  29. #include "math/mathUtils.h"
  30. #include "gfx/gfxDrawUtil.h"
  31. #include "ts/tsShapeInstance.h"
  32. #include "math/mRandom.h"
  33. static U32 sScanTypeMask = PlayerObjectType |
  34. VehicleObjectType;
  35. static U32 sAimTypeMask = TerrainObjectType |
  36. InteriorObjectType |
  37. WaterObjectType |
  38. PlayerObjectType |
  39. StaticShapeObjectType |
  40. VehicleObjectType |
  41. ItemObjectType;
  42. //----------------------------------------------------------------------------
  43. AITurretShapeData::StateData::StateData()
  44. {
  45. name = 0;
  46. transition.rest[0] = transition.rest[1] = -1;
  47. transition.target[0] = transition.target[1] = -1;
  48. transition.activated[0] = transition.activated[1] = -1;
  49. transition.timeout = -1;
  50. waitForTimeout = true;
  51. timeoutValue = 0;
  52. fire = false;
  53. scan = false;
  54. script = 0;
  55. scaleAnimation = false;
  56. direction = false;
  57. sequence = -1;
  58. }
  59. static AITurretShapeData::StateData gDefaultStateData;
  60. //----------------------------------------------------------------------------
  61. IMPLEMENT_CO_DATABLOCK_V1(AITurretShapeData);
  62. ConsoleDocClass( AITurretShapeData,
  63. "@brief Defines properties for an AITurretShape object.\n\n"
  64. "@see AITurretShape\n"
  65. "@see TurretShapeData\n"
  66. "@ingroup gameObjects\n"
  67. );
  68. AITurretShapeData::AITurretShapeData()
  69. {
  70. maxScanHeading = 90;
  71. maxScanPitch = 90;
  72. maxScanDistance = 20;
  73. // Do a full scan every three ticks
  74. scanTickFrequency = 3;
  75. // Randomly add 0 to 1 ticks to the scan frequency as
  76. // chosen every scan period.
  77. scanTickFrequencyVariance = 1;
  78. trackLostTargetTime = 0;
  79. scanNode = -1;
  80. aimNode = -1;
  81. maxWeaponRange = 100;
  82. weaponLeadVelocity = 0;
  83. for (int i = 0; i < MaxStates; i++) {
  84. stateName[i] = 0;
  85. stateTransitionAtRest[i] = 0;
  86. stateTransitionNotAtRest[i] = 0;
  87. stateTransitionTarget[i] = 0;
  88. stateTransitionNoTarget[i] = 0;
  89. stateTransitionActivated[i] = 0;
  90. stateTransitionDeactivated[i] = 0;
  91. stateTransitionTimeout[i] = 0;
  92. stateWaitForTimeout[i] = true;
  93. stateTimeoutValue[i] = 0;
  94. stateFire[i] = false;
  95. stateScan[i] = false;
  96. stateScaleAnimation[i] = true;
  97. stateDirection[i] = true;
  98. stateSequence[i] = 0;
  99. stateScript[i] = 0;
  100. }
  101. isAnimated = false;
  102. statesLoaded = false;
  103. }
  104. void AITurretShapeData::initPersistFields()
  105. {
  106. addField("maxScanHeading", TypeF32, Offset(maxScanHeading, AITurretShapeData),
  107. "@brief Maximum number of degrees to scan left and right.\n\n"
  108. "@note Maximum scan heading is 90 degrees.\n");
  109. addField("maxScanPitch", TypeF32, Offset(maxScanPitch, AITurretShapeData),
  110. "@brief Maximum number of degrees to scan up and down.\n\n"
  111. "@note Maximum scan pitch is 90 degrees.\n");
  112. addField("maxScanDistance", TypeF32, Offset(maxScanDistance, AITurretShapeData),
  113. "@brief Maximum distance to scan.\n\n"
  114. "When combined with maxScanHeading and maxScanPitch this forms a 3D scanning wedge used to initially "
  115. "locate a target.\n");
  116. addField("scanTickFrequency", TypeS32, Offset(scanTickFrequency, AITurretShapeData),
  117. "@brief How often should we perform a full scan when looking for a target.\n\n"
  118. "Expressed as the number of ticks between full scans, but no less than 1.\n");
  119. addField("scanTickFrequencyVariance", TypeS32, Offset(scanTickFrequencyVariance, AITurretShapeData),
  120. "@brief Random amount that should be added to the scan tick frequency each scan period.\n\n"
  121. "Expressed as the number of ticks to randomly add, but no less than zero.\n");
  122. addField("trackLostTargetTime", TypeF32, Offset(trackLostTargetTime, AITurretShapeData),
  123. "@brief How long after the turret has lost the target should it still track it.\n\n"
  124. "Expressed in seconds.\n");
  125. addField("maxWeaponRange", TypeF32, Offset(maxWeaponRange, AITurretShapeData),
  126. "@brief Maximum distance that the weapon will fire upon a target.\n\n");
  127. addField("weaponLeadVelocity", TypeF32, Offset(weaponLeadVelocity, AITurretShapeData),
  128. "@brief Velocity used to lead target.\n\n"
  129. "If value <= 0, don't lead target.\n");
  130. // State arrays
  131. addArray( "States", MaxStates );
  132. addField( "stateName", TypeCaseString, Offset(stateName, AITurretShapeData), MaxStates,
  133. "Name of this state." );
  134. addField( "stateTransitionOnAtRest", TypeString, Offset(stateTransitionAtRest, AITurretShapeData), MaxStates,
  135. "Name of the state to transition to when the turret is at rest (static).");
  136. addField( "stateTransitionOnNotAtRest", TypeString, Offset(stateTransitionNotAtRest, AITurretShapeData), MaxStates,
  137. "Name of the state to transition to when the turret is not at rest (not static).");
  138. addField( "stateTransitionOnTarget", TypeString, Offset(stateTransitionTarget, AITurretShapeData), MaxStates,
  139. "Name of the state to transition to when the turret gains a target." );
  140. addField( "stateTransitionOnNoTarget", TypeString, Offset(stateTransitionNoTarget, AITurretShapeData), MaxStates,
  141. "Name of the state to transition to when the turret loses a target." );
  142. addField( "stateTransitionOnActivated", TypeString, Offset(stateTransitionActivated, AITurretShapeData), MaxStates,
  143. "Name of the state to transition to when the turret goes from deactivated to activated.");
  144. addField( "stateTransitionOnDeactivated", TypeString, Offset(stateTransitionDeactivated, AITurretShapeData), MaxStates,
  145. "Name of the state to transition to when the turret goes from activated to deactivated");
  146. addField( "stateTransitionOnTimeout", TypeString, Offset(stateTransitionTimeout, AITurretShapeData), MaxStates,
  147. "Name of the state to transition to when we have been in this state "
  148. "for stateTimeoutValue seconds." );
  149. addField( "stateTimeoutValue", TypeF32, Offset(stateTimeoutValue, AITurretShapeData), MaxStates,
  150. "Time in seconds to wait before transitioning to stateTransitionOnTimeout." );
  151. addField( "stateWaitForTimeout", TypeBool, Offset(stateWaitForTimeout, AITurretShapeData), MaxStates,
  152. "If false, this state ignores stateTimeoutValue and transitions "
  153. "immediately if other transition conditions are met." );
  154. addField( "stateFire", TypeBool, Offset(stateFire, AITurretShapeData), MaxStates,
  155. "The first state with this set to true is the state entered by the "
  156. "client when it receives the 'fire' event." );
  157. addField( "stateScan", TypeBool, Offset(stateScan, AITurretShapeData), MaxStates,
  158. "Indicates the turret should perform a continuous scan looking for targets." );
  159. addField( "stateDirection", TypeBool, Offset(stateDirection, AITurretShapeData), MaxStates,
  160. "@brief Direction of the animation to play in this state.\n\n"
  161. "True is forward, false is backward." );
  162. addField( "stateSequence", TypeString, Offset(stateSequence, AITurretShapeData), MaxStates,
  163. "Name of the sequence to play on entry to this state." );
  164. addField( "stateScaleAnimation", TypeBool, Offset(stateScaleAnimation, AITurretShapeData), MaxStates,
  165. "If true, the timeScale of the stateSequence animation will be adjusted "
  166. "such that the sequence plays for stateTimeoutValue seconds. " );
  167. addField( "stateScript", TypeCaseString, Offset(stateScript, AITurretShapeData), MaxStates,
  168. "@brief Method to execute on entering this state.\n\n"
  169. "Scoped to AITurretShapeData.");
  170. endArray( "States" );
  171. Parent::initPersistFields();
  172. }
  173. bool AITurretShapeData::onAdd()
  174. {
  175. if (!Parent::onAdd())
  176. return false;
  177. // Copy state data from the scripting arrays into the
  178. // state structure array. If we have state data already,
  179. // we are on the client and need to leave it alone.
  180. for (U32 i = 0; i < MaxStates; i++) {
  181. StateData& s = state[i];
  182. if (statesLoaded == false) {
  183. s.name = stateName[i];
  184. s.transition.rest[0] = lookupState(stateTransitionNotAtRest[i]);
  185. s.transition.rest[1] = lookupState(stateTransitionAtRest[i]);
  186. s.transition.target[0] = lookupState(stateTransitionNoTarget[i]);
  187. s.transition.target[1] = lookupState(stateTransitionTarget[i]);
  188. s.transition.activated[0] = lookupState(stateTransitionDeactivated[i]);
  189. s.transition.activated[1] = lookupState(stateTransitionActivated[i]);
  190. s.transition.timeout = lookupState(stateTransitionTimeout[i]);
  191. s.waitForTimeout = stateWaitForTimeout[i];
  192. s.timeoutValue = stateTimeoutValue[i];
  193. s.fire = stateFire[i];
  194. s.scan = stateScan[i];
  195. s.scaleAnimation = stateScaleAnimation[i];
  196. s.direction = stateDirection[i];
  197. s.script = stateScript[i];
  198. // Resolved at load time
  199. s.sequence = -1;
  200. }
  201. // The first state marked as "fire" is the state entered on the
  202. // client when it recieves a fire event.
  203. if (s.fire && fireState == -1)
  204. fireState = i;
  205. }
  206. // Always preload images, this is needed to avoid problems with
  207. // resolving sequences before transmission to a client.
  208. return true;
  209. }
  210. bool AITurretShapeData::preload(bool server, String &errorStr)
  211. {
  212. if (!Parent::preload(server, errorStr))
  213. return false;
  214. // We have mShape at this point. Resolve nodes.
  215. scanNode = mShape->findNode("scanPoint");
  216. aimNode = mShape->findNode("aimPoint");
  217. if (aimNode == -1)
  218. {
  219. aimNode = pitchNode;
  220. }
  221. if (aimNode == -1)
  222. {
  223. aimNode = headingNode;
  224. }
  225. // Resolve state sequence names & emitter nodes
  226. isAnimated = false;
  227. for (U32 j = 0; j < MaxStates; j++) {
  228. StateData& s = state[j];
  229. if (stateSequence[j] && stateSequence[j][0])
  230. s.sequence = mShape->findSequence(stateSequence[j]);
  231. if (s.sequence != -1)
  232. {
  233. // This state has an animation sequence
  234. isAnimated = true;
  235. }
  236. }
  237. return true;
  238. }
  239. void AITurretShapeData::packData(BitStream* stream)
  240. {
  241. Parent::packData(stream);
  242. stream->write(maxScanHeading);
  243. stream->write(maxScanPitch);
  244. stream->write(maxScanDistance);
  245. stream->write(maxWeaponRange);
  246. stream->write(weaponLeadVelocity);
  247. for (U32 i = 0; i < MaxStates; i++)
  248. if (stream->writeFlag(state[i].name && state[i].name[0])) {
  249. StateData& s = state[i];
  250. // States info not needed on the client:
  251. // s.scriptNames
  252. // Transitions are inc. one to account for -1 values
  253. stream->writeString(state[i].name);
  254. stream->writeInt(s.transition.rest[0]+1,NumStateBits);
  255. stream->writeInt(s.transition.rest[1]+1,NumStateBits);
  256. stream->writeInt(s.transition.target[0]+1,NumStateBits);
  257. stream->writeInt(s.transition.target[1]+1,NumStateBits);
  258. stream->writeInt(s.transition.activated[0]+1,NumStateBits);
  259. stream->writeInt(s.transition.activated[1]+1,NumStateBits);
  260. stream->writeInt(s.transition.timeout+1,NumStateBits);
  261. if(stream->writeFlag(s.timeoutValue != gDefaultStateData.timeoutValue))
  262. stream->write(s.timeoutValue);
  263. stream->writeFlag(s.waitForTimeout);
  264. stream->writeFlag(s.fire);
  265. stream->writeFlag(s.scan);
  266. stream->writeFlag(s.scaleAnimation);
  267. stream->writeFlag(s.direction);
  268. if(stream->writeFlag(s.sequence != gDefaultStateData.sequence))
  269. stream->writeSignedInt(s.sequence, 16);
  270. }
  271. }
  272. void AITurretShapeData::unpackData(BitStream* stream)
  273. {
  274. Parent::unpackData(stream);
  275. stream->read(&maxScanHeading);
  276. stream->read(&maxScanPitch);
  277. stream->read(&maxScanDistance);
  278. stream->read(&maxWeaponRange);
  279. stream->read(&weaponLeadVelocity);
  280. for (U32 i = 0; i < MaxStates; i++) {
  281. if (stream->readFlag()) {
  282. StateData& s = state[i];
  283. // States info not needed on the client:
  284. // s.scriptNames
  285. // Transitions are dec. one to restore -1 values
  286. s.name = stream->readSTString();
  287. s.transition.rest[0] = stream->readInt(NumStateBits) - 1;
  288. s.transition.rest[1] = stream->readInt(NumStateBits) - 1;
  289. s.transition.target[0] = stream->readInt(NumStateBits) - 1;
  290. s.transition.target[1] = stream->readInt(NumStateBits) - 1;
  291. s.transition.activated[0] = stream->readInt(NumStateBits) - 1;
  292. s.transition.activated[1] = stream->readInt(NumStateBits) - 1;
  293. s.transition.timeout = stream->readInt(NumStateBits) - 1;
  294. if(stream->readFlag())
  295. stream->read(&s.timeoutValue);
  296. else
  297. s.timeoutValue = gDefaultStateData.timeoutValue;
  298. s.waitForTimeout = stream->readFlag();
  299. s.fire = stream->readFlag();
  300. s.scan = stream->readFlag();
  301. s.scaleAnimation = stream->readFlag();
  302. s.direction = stream->readFlag();
  303. if(stream->readFlag())
  304. s.sequence = stream->readSignedInt(16);
  305. }
  306. }
  307. statesLoaded = true;
  308. }
  309. S32 AITurretShapeData::lookupState(const char* name)
  310. {
  311. if (!name || !name[0])
  312. return -1;
  313. for (U32 i = 0; i < MaxStates; i++)
  314. if (stateName[i] && !dStricmp(name,stateName[i]))
  315. return i;
  316. Con::errorf(ConsoleLogEntry::General,"AITurretShapeData:: Could not resolve state \"%s\" for image \"%s\"",name,getName());
  317. return 0;
  318. }
  319. //----------------------------------------------------------------------------
  320. // Used to build potential target list
  321. static void _scanCallback( SceneObject* object, void* data )
  322. {
  323. AITurretShape* turret = (AITurretShape*)data;
  324. ShapeBase* shape = dynamic_cast<ShapeBase*>(object);
  325. if (shape && shape->getDamageState() == ShapeBase::Enabled)
  326. {
  327. Point3F targetPos = shape->getBoxCenter();
  328. // Put target position into the scan node's space
  329. turret->mScanWorkspaceScanWorldMat.mulP(targetPos);
  330. // Is the target within scanning distance
  331. if (targetPos.lenSquared() > turret->getMaxScanDistanceSquared())
  332. return;
  333. // Make sure the target is in front and within the maximum
  334. // heading range
  335. Point2F targetXY(targetPos.x, targetPos.y);
  336. targetXY.normalizeSafe();
  337. F32 headingDot = mDot(Point2F(0, 1), targetXY);
  338. F32 heading = mAcos(headingDot);
  339. if (headingDot < 0 || heading > turret->getMaxScanHeading())
  340. return;
  341. // Make sure the target is in front and within the maximum
  342. // pitch range
  343. Point2F targetZY(targetPos.z, targetPos.y);
  344. targetZY.normalizeSafe();
  345. F32 pitchDot = mDot(Point2F(0, 1), targetZY);
  346. F32 pitch = mAcos(pitchDot);
  347. if (pitchDot < 0 || pitch > turret->getMaxScanPitch())
  348. return;
  349. turret->addPotentialTarget(shape);
  350. }
  351. }
  352. // Used to sort potential target list based on distance
  353. static Point3F comparePoint;
  354. static S32 QSORT_CALLBACK _sortCallback(const void* a,const void* b)
  355. {
  356. const ShapeBase* s1 = (*reinterpret_cast<const ShapeBase* const*>(a));
  357. const ShapeBase* s2 = (*reinterpret_cast<const ShapeBase* const*>(b));
  358. F32 s1Len = (s1->getPosition() - comparePoint).lenSquared();
  359. F32 s2Len = (s2->getPosition() - comparePoint).lenSquared();
  360. return s1Len - s2Len;
  361. }
  362. IMPLEMENT_CO_NETOBJECT_V1(AITurretShape);
  363. ConsoleDocClass( AITurretShape,
  364. "@ingroup gameObjects"
  365. );
  366. AITurretShape::AITurretShape()
  367. {
  368. mTypeMask |= VehicleObjectType | DynamicShapeObjectType;
  369. mDataBlock = 0;
  370. mScanHeading = 0;
  371. mScanPitch = 0;
  372. mScanDistance = 0;
  373. mScanDistanceSquared = 0;
  374. mScanBox = Box3F::Zero;
  375. mScanTickFrequency = 1;
  376. mScanTickFrequencyVariance = 0;
  377. mTicksToNextScan = mScanTickFrequency;
  378. mWeaponRangeSquared = 0;
  379. mWeaponLeadVelocitySquared = 0;
  380. mScanForTargets = false;
  381. mTrackTarget = false;
  382. mState = NULL;
  383. mStateDelayTime = 0;
  384. mStateActive = true;
  385. mStateAnimThread = NULL;
  386. // For the TurretShape class
  387. mSubclassTurretShapeHandlesScene = true;
  388. }
  389. AITurretShape::~AITurretShape()
  390. {
  391. _cleanupPotentialTargets();
  392. }
  393. //----------------------------------------------------------------------------
  394. void AITurretShape::initPersistFields()
  395. {
  396. Parent::initPersistFields();
  397. }
  398. bool AITurretShape::onAdd()
  399. {
  400. if( !Parent::onAdd() )
  401. return false;
  402. // Add this object to the scene
  403. addToScene();
  404. _setScanBox();
  405. if (isServerObject())
  406. _initState();
  407. if (isServerObject())
  408. scriptOnAdd();
  409. return true;
  410. }
  411. void AITurretShape::onRemove()
  412. {
  413. Parent::onRemove();
  414. scriptOnRemove();
  415. mIgnoreObjects.clear();
  416. // Remove this object from the scene
  417. removeFromScene();
  418. }
  419. bool AITurretShape::onNewDataBlock(GameBaseData* dptr, bool reload)
  420. {
  421. mDataBlock = dynamic_cast<AITurretShapeData*>(dptr);
  422. if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
  423. return false;
  424. mScanHeading = mDegToRad(mDataBlock->maxScanHeading);
  425. if (mIsZero(mScanHeading))
  426. mScanHeading = M_PI_F;
  427. mScanPitch = mDegToRad(mDataBlock->maxScanPitch);
  428. if (mIsZero(mScanPitch))
  429. mScanPitch = M_PI_F;
  430. mScanDistance = mDataBlock->maxScanDistance;
  431. mScanDistanceSquared = mScanDistance * mScanDistance;
  432. mWeaponRangeSquared = mDataBlock->maxWeaponRange * mDataBlock->maxWeaponRange;
  433. mWeaponLeadVelocitySquared = (mDataBlock->weaponLeadVelocity > 0) ? (mDataBlock->weaponLeadVelocity * mDataBlock->weaponLeadVelocity) : 0;
  434. // The scan box is built such that the scanning origin is at (0,0,0) and the scanning distance
  435. // is out along the y axis. When this is transformed to the turret's location is provides a
  436. // scanning volume in front of the turret.
  437. F32 scanX = mScanDistance*mSin(mScanHeading);
  438. F32 scanY = mScanDistance;
  439. F32 scanZ = mScanDistance*mSin(mScanPitch);
  440. mScanBox.set(-scanX, 0, -scanZ, scanX, scanY, scanZ);
  441. mScanTickFrequency = mDataBlock->scanTickFrequency;
  442. if (mScanTickFrequency < 1)
  443. mScanTickFrequency = 1;
  444. mScanTickFrequencyVariance = mDataBlock->scanTickFrequencyVariance;
  445. if (mScanTickFrequencyVariance < 0)
  446. mScanTickFrequencyVariance = 0;
  447. mTicksToNextScan = mScanTickFrequency;
  448. // For states
  449. mStateAnimThread = 0;
  450. if (mDataBlock->isAnimated)
  451. {
  452. mStateAnimThread = mShapeInstance->addThread();
  453. mShapeInstance->setTimeScale(mStateAnimThread,0);
  454. }
  455. scriptOnNewDataBlock();
  456. return true;
  457. }
  458. //----------------------------------------------------------------------------
  459. void AITurretShape::addToIgnoreList(ShapeBase* obj)
  460. {
  461. mIgnoreObjects.addObject(obj);
  462. }
  463. void AITurretShape::removeFromIgnoreList(ShapeBase* obj)
  464. {
  465. mIgnoreObjects.removeObject(obj);
  466. }
  467. //----------------------------------------------------------------------------
  468. void AITurretShape::_initState()
  469. {
  470. // Set the turret to its starting state.
  471. setTurretState(0, true);
  472. }
  473. void AITurretShape::setTurretStateName(const char* newState, bool force)
  474. {
  475. S32 stateVal = mDataBlock->lookupState(newState);
  476. if (stateVal >= 0)
  477. {
  478. setTurretState(stateVal, force);
  479. }
  480. }
  481. void AITurretShape::setTurretState(U32 newState, bool force)
  482. {
  483. setMaskBits(TurretStateMask);
  484. // If going back into the same state, just reset the timer
  485. // and invoke the script callback
  486. if (!force && mState == &mDataBlock->state[newState])
  487. {
  488. mStateDelayTime = mState->timeoutValue;
  489. if (mState->script && !isGhost())
  490. _scriptCallback(mState->script);
  491. return;
  492. }
  493. mState = &mDataBlock->state[newState];
  494. // Reset cyclic sequences back to the first frame to turn it off
  495. // (the first key frame should be it's off state).
  496. if (mStateAnimThread && mStateAnimThread->getSequence()->isCyclic())
  497. {
  498. mShapeInstance->setPos(mStateAnimThread,0);
  499. mShapeInstance->setTimeScale(mStateAnimThread,0);
  500. }
  501. AITurretShapeData::StateData& stateData = *mState;
  502. // Check for immediate transitions
  503. S32 ns;
  504. if ((ns = stateData.transition.rest[mAtRest]) != -1)
  505. {
  506. setTurretState(ns);
  507. return;
  508. }
  509. if ((ns = stateData.transition.target[mTarget.isValid()]) != -1)
  510. {
  511. setTurretState(ns);
  512. return;
  513. }
  514. if ((ns = stateData.transition.activated[mStateActive]) != -1)
  515. {
  516. setTurretState(ns);
  517. return;
  518. }
  519. //
  520. // Initialize the new state...
  521. //
  522. mStateDelayTime = stateData.timeoutValue;
  523. // Play animation
  524. if (mStateAnimThread && stateData.sequence != -1)
  525. {
  526. mShapeInstance->setSequence(mStateAnimThread,stateData.sequence, stateData.direction ? 0.0f : 1.0f);
  527. F32 timeScale = (stateData.scaleAnimation && stateData.timeoutValue) ?
  528. mShapeInstance->getDuration(mStateAnimThread) / stateData.timeoutValue : 1.0f;
  529. mShapeInstance->setTimeScale(mStateAnimThread, stateData.direction ? timeScale : -timeScale);
  530. }
  531. // Script callback on server
  532. if (stateData.script && stateData.script[0] && !isGhost())
  533. _scriptCallback(stateData.script);
  534. // If there is a zero timeout, and a timeout transition, then
  535. // go ahead and transition imediately.
  536. if (!mStateDelayTime)
  537. {
  538. if ((ns = stateData.transition.timeout) != -1)
  539. {
  540. setTurretState(ns);
  541. return;
  542. }
  543. }
  544. }
  545. void AITurretShape::_updateTurretState(F32 dt)
  546. {
  547. AITurretShapeData::StateData& stateData = *mState;
  548. mStateDelayTime -= dt;
  549. // Check for transitions. On some states we must wait for the
  550. // full timeout value before moving on.
  551. if (mStateDelayTime <= 0 || !stateData.waitForTimeout)
  552. {
  553. S32 ns;
  554. if ((ns = stateData.transition.rest[mAtRest]) != -1)
  555. setTurretState(ns);
  556. else if ((ns = stateData.transition.target[mTarget.isValid()]) != -1)
  557. setTurretState(ns);
  558. else if ((ns = stateData.transition.activated[mStateActive]) != -1)
  559. setTurretState(ns);
  560. else if (mStateDelayTime <= 0 && (ns = stateData.transition.timeout) != -1)
  561. setTurretState(ns);
  562. }
  563. }
  564. void AITurretShape::_scriptCallback(const char* function)
  565. {
  566. Con::executef( mDataBlock, function, getIdString() );
  567. }
  568. //----------------------------------------------------------------------------
  569. void AITurretShape::_cleanupPotentialTargets()
  570. {
  571. mPotentialTargets.clear();
  572. }
  573. void AITurretShape::_performScan()
  574. {
  575. // Only on server
  576. if (isClientObject())
  577. return;
  578. // Are we ready for a scan?
  579. --mTicksToNextScan;
  580. if (mTicksToNextScan > 0)
  581. return;
  582. _cleanupPotentialTargets();
  583. _setScanBox();
  584. // Set up for the scan
  585. getScanTransform(mScanWorkspaceScanMat);
  586. mScanWorkspaceScanWorldMat = mScanWorkspaceScanMat;
  587. mScanWorkspaceScanWorldMat.affineInverse();
  588. disableCollision();
  589. for ( SimSetIterator iter(&mIgnoreObjects); *iter; ++iter )
  590. {
  591. ShapeBase* obj = static_cast<ShapeBase*>( *iter );
  592. obj->disableCollision();
  593. }
  594. gServerContainer.findObjects( mTransformedScanBox, sScanTypeMask, _scanCallback, (void*)this );
  595. for ( SimSetIterator iter(&mIgnoreObjects); *iter; ++iter )
  596. {
  597. ShapeBase* obj = static_cast<ShapeBase*>( *iter );
  598. obj->enableCollision();
  599. }
  600. enableCollision();
  601. if (mPotentialTargets.size() == 0)
  602. {
  603. // No targets in range. Clear out our current target, if necessary.
  604. _lostTarget();
  605. }
  606. else
  607. {
  608. // Sort the targets
  609. comparePoint = getPosition();
  610. dQsort(mPotentialTargets.address(),mPotentialTargets.size(),sizeof(SimObjectList::value_type),_sortCallback);
  611. // Go through the targets in order to find one that is not blocked from view
  612. Point3F start;
  613. mScanWorkspaceScanMat.getColumn(3, &start);
  614. S32 index = 0;
  615. bool los = false;
  616. disableCollision();
  617. for (index=0; index < mPotentialTargets.size(); ++index)
  618. {
  619. ShapeBase* shape = (ShapeBase*)mPotentialTargets[index];
  620. Point3F sightPoint;
  621. los = _testTargetLineOfSight(start, shape, sightPoint);
  622. // Check if we have a clear line of sight
  623. if (los)
  624. break;
  625. }
  626. enableCollision();
  627. // If we found a valid, visible target (no hits between here and there), latch on to it
  628. if (los)
  629. {
  630. _gainedTarget((ShapeBase*)mPotentialTargets[index]);
  631. }
  632. }
  633. // Prepare for next scan period
  634. mTicksToNextScan = mScanTickFrequency;
  635. if (mScanTickFrequencyVariance > 0)
  636. {
  637. mTicksToNextScan += gRandGen.randI(0, mScanTickFrequencyVariance);
  638. }
  639. }
  640. void AITurretShape::addPotentialTarget(ShapeBase* shape)
  641. {
  642. mPotentialTargets.push_back(shape);
  643. }
  644. void AITurretShape::_lostTarget()
  645. {
  646. mTarget.target = NULL;
  647. }
  648. void AITurretShape::_gainedTarget(ShapeBase* target)
  649. {
  650. mTarget.target = target;
  651. if (target)
  652. {
  653. mTarget.hadValidTarget = true;
  654. }
  655. }
  656. void AITurretShape::_trackTarget(F32 dt)
  657. {
  658. // Only on server
  659. if (isClientObject())
  660. return;
  661. // We can only track a target if we have one
  662. if (!mTarget.isValid())
  663. return;
  664. Point3F targetPos = mTarget.target->getBoxCenter();
  665. // Can we see the target?
  666. MatrixF aimMat;
  667. getAimTransform(aimMat);
  668. Point3F start;
  669. aimMat.getColumn(3, &start);
  670. RayInfo ri;
  671. Point3F sightPoint;
  672. disableCollision();
  673. bool los = _testTargetLineOfSight(start, mTarget.target, sightPoint);
  674. enableCollision();
  675. if (!los)
  676. {
  677. // Target is blocked. Should we try to track from its last
  678. // known position and velocity?
  679. SimTime curTime = Sim::getCurrentTime();
  680. if ( (curTime - mTarget.lastSightTime) > (mDataBlock->trackLostTargetTime * 1000.0f) )
  681. {
  682. // Time's up. Stop tracking.
  683. _cleanupTargetAndTurret();
  684. return;
  685. }
  686. // Use last known information to attempt to
  687. // continue to track target for a while.
  688. targetPos = mTarget.lastPos + mTarget.lastVel * F32(curTime - mTarget.lastSightTime) / 1000.0f;
  689. }
  690. else
  691. {
  692. // Target is visible
  693. // We only track targets that are alive
  694. if (mTarget.target->getDamageState() != Enabled)
  695. {
  696. // We can't track any more
  697. _cleanupTargetAndTurret();
  698. return;
  699. }
  700. targetPos = sightPoint;
  701. // Store latest target info
  702. mTarget.lastPos = targetPos;
  703. mTarget.lastVel = mTarget.target->getVelocity();
  704. mTarget.lastSightTime = Sim::getCurrentTime();
  705. }
  706. // Calculate angles to face the target, specifically the part that we can see
  707. VectorF toTarget;
  708. MatrixF mat;
  709. S32 node = mDataBlock->aimNode;
  710. if (node != -1)
  711. {
  712. // Get the current position of our node
  713. MatrixF* nodeTrans = &mShapeInstance->mNodeTransforms[node];
  714. Point3F currentPos;
  715. nodeTrans->getColumn(3, &currentPos);
  716. // Turn this into a matrix we can use to put the target
  717. // position into our space.
  718. MatrixF nodeMat(true);
  719. nodeMat.setColumn(3, currentPos);
  720. mat.mul(mObjToWorld, nodeMat);
  721. mat.affineInverse();
  722. }
  723. else
  724. {
  725. mat = mWorldToObj;
  726. }
  727. mat.mulP(targetPos, &toTarget);
  728. // lead the target
  729. F32 timeToTargetSquared = (mWeaponLeadVelocitySquared > 0) ? toTarget.lenSquared() / mWeaponLeadVelocitySquared : 0;
  730. if (timeToTargetSquared > 1.0)
  731. {
  732. targetPos = targetPos + (mTarget.lastVel * mSqrt(timeToTargetSquared));
  733. mat.mulP(targetPos, &toTarget);
  734. }
  735. F32 yaw, pitch;
  736. MathUtils::getAnglesFromVector(toTarget, yaw, pitch);
  737. if (yaw > M_PI_F)
  738. yaw = yaw - M_2PI_F;
  739. //if (pitch > M_PI_F)
  740. // pitch = -(pitch - M_2PI_F);
  741. Point3F rot(-pitch, 0.0f, yaw);
  742. // If we have a rotation rate make sure we follow it
  743. if (mHeadingRate > 0)
  744. {
  745. F32 rate = mHeadingRate * dt;
  746. F32 rateCheck = mFabs(rot.z - mRot.z);
  747. if (rateCheck > rate)
  748. {
  749. // This will clamp the new value to the rate regardless if it
  750. // is increasing or decreasing.
  751. rot.z = mClampF(rot.z, mRot.z-rate, mRot.z+rate);
  752. }
  753. }
  754. if (mPitchRate > 0)
  755. {
  756. F32 rate = mPitchRate * dt;
  757. F32 rateCheck = mFabs(rot.x - mRot.x);
  758. if (rateCheck > rate)
  759. {
  760. // This will clamp the new value to the rate regardless if it
  761. // is increasing or decreasing.
  762. rot.x = mClampF(rot.x, mRot.x-rate, mRot.x+rate);
  763. }
  764. }
  765. // Test if the rotation to the target is outside of our limits
  766. if (_outsideLimits(rot))
  767. {
  768. // We can't track any more
  769. _cleanupTargetAndTurret();
  770. return;
  771. }
  772. // Test if the target is out of weapons range
  773. if (toTarget.lenSquared() > mWeaponRangeSquared)
  774. {
  775. // We can't track any more
  776. _cleanupTargetAndTurret();
  777. return;
  778. }
  779. mRot = rot;
  780. _setRotation( mRot );
  781. setMaskBits(TurretUpdateMask);
  782. }
  783. void AITurretShape::_cleanupTargetAndTurret()
  784. {
  785. _lostTarget();
  786. resetTarget();
  787. }
  788. bool AITurretShape::_testTargetLineOfSight(Point3F& aimPoint, ShapeBase* target, Point3F& sightPoint)
  789. {
  790. Point3F targetCenter = target->getBoxCenter();
  791. RayInfo ri;
  792. bool hit = false;
  793. target->disableCollision();
  794. // First check for a clear line of sight to the target's center
  795. Point3F testPoint = targetCenter;
  796. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  797. if (hit)
  798. {
  799. // No clear line of sight to center, so try to the target's right. Players holding
  800. // a gun in their right hand will tend to stick their right shoulder out first if
  801. // they're peering around some cover to shoot, like a wall.
  802. Box3F targetBounds = target->getObjBox();
  803. F32 radius = targetBounds.len_x() > targetBounds.len_y() ? targetBounds.len_x() : targetBounds.len_y();
  804. radius *= 0.5;
  805. VectorF toTurret = aimPoint - targetCenter;
  806. toTurret.normalizeSafe();
  807. VectorF toTurretRight = mCross(toTurret, Point3F::UnitZ);
  808. testPoint = targetCenter + toTurretRight * radius;
  809. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  810. if (hit)
  811. {
  812. // No clear line of sight to right, so try the target's left
  813. VectorF toTurretLeft = toTurretRight * -1.0f;
  814. testPoint = targetCenter + toTurretLeft * radius;
  815. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  816. }
  817. if (hit)
  818. {
  819. // No clear line of sight to left, so try the target's top
  820. testPoint = targetCenter;
  821. testPoint.z += targetBounds.len_z() * 0.5f;
  822. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  823. }
  824. if (hit)
  825. {
  826. // No clear line of sight to top, so try the target's bottom
  827. testPoint = targetCenter;
  828. testPoint.z -= targetBounds.len_z() * 0.5f;
  829. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  830. }
  831. }
  832. target->enableCollision();
  833. if (!hit)
  834. {
  835. // Line of sight point is that last one we tested
  836. sightPoint = testPoint;
  837. }
  838. return !hit;
  839. }
  840. //----------------------------------------------------------------------------
  841. void AITurretShape::setAllGunsFiring(bool fire)
  842. {
  843. setImageTriggerState(0,fire);
  844. setImageTriggerState(1,fire);
  845. setImageTriggerState(2,fire);
  846. setImageTriggerState(3,fire);
  847. }
  848. void AITurretShape::setGunSlotFiring(S32 slot, bool fire)
  849. {
  850. if (slot < 0 || slot > 3)
  851. return;
  852. setImageTriggerState(slot, fire);
  853. }
  854. //----------------------------------------------------------------------------
  855. void AITurretShape::setTransform(const MatrixF& mat)
  856. {
  857. Parent::setTransform(mat);
  858. // Set the scanning box
  859. _setScanBox();
  860. }
  861. void AITurretShape::recenterTurret()
  862. {
  863. mRot.set(0,0,0);
  864. _setRotation( mRot );
  865. setMaskBits(TurretUpdateMask);
  866. }
  867. void AITurretShape::_setScanBox()
  868. {
  869. mTransformedScanBox = mScanBox;
  870. MatrixF mat;
  871. getScanTransform(mat);
  872. mat.mul(mTransformedScanBox);
  873. }
  874. void AITurretShape::getScanTransform(MatrixF& mat)
  875. {
  876. if (mDataBlock && mDataBlock->scanNode != -1)
  877. {
  878. if (getNodeTransform(mDataBlock->scanNode, mat))
  879. {
  880. return;
  881. }
  882. }
  883. mat = mObjToWorld;
  884. }
  885. void AITurretShape::getAimTransform(MatrixF& mat)
  886. {
  887. if (mDataBlock && mDataBlock->aimNode != -1)
  888. {
  889. if (getNodeTransform(mDataBlock->aimNode, mat))
  890. {
  891. return;
  892. }
  893. }
  894. mat = mObjToWorld;
  895. }
  896. //----------------------------------------------------------------------------
  897. void AITurretShape::processTick(const Move* move)
  898. {
  899. Parent::processTick(move);
  900. if (isServerObject() && mDamageState == Enabled)
  901. {
  902. _updateTurretState(TickSec);
  903. if (mScanForTargets)
  904. {
  905. // Perform a scan for targets
  906. _performScan();
  907. // If we found one, turn off the scan
  908. if (mTarget.isValid())
  909. {
  910. mScanForTargets = false;
  911. }
  912. }
  913. if (mTrackTarget)
  914. {
  915. _trackTarget(TickSec);
  916. // If the target is lost, no longer track it
  917. if (!mTarget.isValid())
  918. {
  919. mTrackTarget = false;
  920. }
  921. }
  922. }
  923. }
  924. void AITurretShape::advanceTime(F32 dt)
  925. {
  926. // If there were any ShapeBase script threads that
  927. // have played, then we need to update all code
  928. // controlled nodes. This is done before the Parent
  929. // call as script threads may play and be destroyed
  930. // before our code is called.
  931. bool updateNodes = false;
  932. for (U32 i = 0; i < MaxScriptThreads; i++)
  933. {
  934. Thread& st = mScriptThread[i];
  935. if (st.thread)
  936. {
  937. updateNodes = true;
  938. break;
  939. }
  940. }
  941. Parent::advanceTime(dt);
  942. // Update any state thread
  943. AITurretShapeData::StateData& stateData = *mState;
  944. if (mStateAnimThread && stateData.sequence != -1)
  945. {
  946. mShapeInstance->advanceTime(dt,mStateAnimThread);
  947. updateNodes = true;
  948. }
  949. if (updateNodes)
  950. {
  951. // Update all code controlled nodes
  952. _updateNodes(mRot);
  953. }
  954. }
  955. //----------------------------------------------------------------------------
  956. U32 AITurretShape::packUpdate(NetConnection *connection, U32 mask, BitStream *bstream)
  957. {
  958. U32 retMask = Parent::packUpdate(connection,mask,bstream);
  959. // Indicate that the transform has changed to update the scan box
  960. bstream->writeFlag(mask & PositionMask | ExtendedInfoMask);
  961. // Handle any state changes that need to be passed along
  962. if (bstream->writeFlag(mask & TurretStateMask))
  963. {
  964. bstream->write(mDataBlock->lookupState(mState->name));
  965. }
  966. return retMask;
  967. }
  968. void AITurretShape::unpackUpdate(NetConnection *connection, BitStream *bstream)
  969. {
  970. Parent::unpackUpdate(connection,bstream);
  971. // Transform has changed
  972. if (bstream->readFlag())
  973. {
  974. _setScanBox();
  975. }
  976. //TurretStateMask
  977. if (bstream->readFlag())
  978. {
  979. S32 newstate;
  980. bstream->read( &newstate );
  981. setTurretState(newstate);
  982. }
  983. }
  984. //----------------------------------------------------------------------------
  985. void AITurretShape::prepBatchRender( SceneRenderState *state, S32 mountedImageIndex )
  986. {
  987. Parent::prepBatchRender( state, mountedImageIndex );
  988. if ( !gShowBoundingBox )
  989. return;
  990. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  991. ri->renderDelegate.bind( this, &AITurretShape::_renderScanner );
  992. ri->type = RenderPassManager::RIT_Editor;
  993. state->getRenderPass()->addInst( ri );
  994. }
  995. void AITurretShape::_renderScanner( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  996. {
  997. GFXStateBlockDesc desc;
  998. desc.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  999. desc.setZReadWrite(false,true);
  1000. desc.fillMode = GFXFillWireframe;
  1001. // Render the scan box
  1002. GFX->getDrawUtil()->drawCube(desc, mTransformedScanBox.getExtents(), mTransformedScanBox.getCenter(), ColorI(255, 0, 0));
  1003. // Render a line from the scan node to the max scan distance
  1004. MatrixF nodeMat;
  1005. if (getNodeTransform(mDataBlock->scanNode, nodeMat))
  1006. {
  1007. Point3F start;
  1008. nodeMat.getColumn(3, &start);
  1009. Point3F end(0.0f, mScanDistance, 0.0f);
  1010. nodeMat.mulP(end);
  1011. GFX->getDrawUtil()->drawLine(start, end, ColorI(255, 255, 0));
  1012. }
  1013. }
  1014. //----------------------------------------------------------------------------
  1015. DefineEngineMethod( AITurretShape, addToIgnoreList, void, (ShapeBase* obj),,
  1016. "@brief Adds object to the turret's ignore list.\n\n"
  1017. "All objects in this list will be ignored by the turret's targeting.\n"
  1018. "@param obj The ShapeBase object to ignore.\n")
  1019. {
  1020. object->addToIgnoreList(obj);
  1021. }
  1022. DefineEngineMethod( AITurretShape, removeFromIgnoreList, void, (ShapeBase* obj),,
  1023. "@brief Removes object from the turret's ignore list.\n\n"
  1024. "All objects in this list will be ignored by the turret's targeting.\n"
  1025. "@param obj The ShapeBase object to once again allow for targeting.\n")
  1026. {
  1027. object->removeFromIgnoreList(obj);
  1028. }
  1029. DefineEngineMethod( AITurretShape, setTurretState, void, (const char* newState, bool force), (false),
  1030. "@brief Set the turret's current state.\n\n"
  1031. "Normally the turret's state comes from updating the state machine but this method "
  1032. "allows you to override this and jump to the requested state immediately.\n"
  1033. "@param newState The name of the new state.\n"
  1034. "@param force Is true then force the full processing of the new state even if it is the "
  1035. "same as the current state. If false then only the time out value is reset and the state's "
  1036. "script method is called, if any.\n")
  1037. {
  1038. object->setTurretStateName(newState, force);
  1039. }
  1040. DefineEngineMethod( AITurretShape, activateTurret, void, ( ),,
  1041. "@brief Activate a turret from a deactive state.\n\n")
  1042. {
  1043. object->activateTurret();
  1044. }
  1045. DefineEngineMethod( AITurretShape, deactivateTurret, void, ( ),,
  1046. "@brief Deactivate a turret from an active state.\n\n")
  1047. {
  1048. object->deactivateTurret();
  1049. }
  1050. DefineEngineMethod( AITurretShape, startScanForTargets, void, ( ),,
  1051. "@brief Begin scanning for a target.\n\n")
  1052. {
  1053. object->startScanForTargets();
  1054. }
  1055. DefineEngineMethod( AITurretShape, stopScanForTargets, void, ( ),,
  1056. "@brief Stop scanning for targets.\n\n"
  1057. "@note Only impacts the scanning for new targets. Does not effect a turret's current "
  1058. "target lock.\n")
  1059. {
  1060. object->stopScanForTargets();
  1061. }
  1062. DefineEngineMethod( AITurretShape, startTrackingTarget, void, ( ),,
  1063. "@brief Have the turret track the current target.\n\n")
  1064. {
  1065. object->startTrackingTarget();
  1066. }
  1067. DefineEngineMethod( AITurretShape, stopTrackingTarget, void, ( ),,
  1068. "@brief Stop the turret from tracking the current target.\n\n")
  1069. {
  1070. object->stopTrackingTarget();
  1071. }
  1072. DefineEngineMethod( AITurretShape, hasTarget, bool, (),,
  1073. "@brief Indicates if the turret has a target.\n\n"
  1074. "@returns True if the turret has a target.\n")
  1075. {
  1076. return object->hasTarget();
  1077. }
  1078. DefineEngineMethod( AITurretShape, getTarget, SimObject*, (),,
  1079. "@brief Get the turret's current target.\n\n"
  1080. "@returns The object that is the target's current target, or 0 if no target.\n")
  1081. {
  1082. return object->getTarget();
  1083. }
  1084. DefineEngineMethod( AITurretShape, resetTarget, void, ( ),,
  1085. "@brief Resets the turret's target tracking.\n\n"
  1086. "Only resets the internal target tracking. Does not modify the turret's facing.\n")
  1087. {
  1088. object->resetTarget();
  1089. }
  1090. DefineEngineMethod( AITurretShape, setWeaponLeadVelocity, void, (F32 velocity),,
  1091. "@brief Set the turret's projectile velocity to help lead the target.\n\n"
  1092. "This value normally comes from AITurretShapeData::weaponLeadVelocity but this method "
  1093. "allows you to override the datablock value. This can be useful if the turret changes "
  1094. "ammunition, uses a different weapon than the default, is damaged, etc.\n"
  1095. "@note Setting this to 0 will disable target leading.\n")
  1096. {
  1097. object->setWeaponLeadVelocity(velocity);
  1098. }
  1099. DefineEngineMethod( AITurretShape, getWeaponLeadVelocity, F32, (),,
  1100. "@brief Get the turret's defined projectile velocity that helps with target leading.\n\n"
  1101. "@returns The defined weapon projectile speed, or 0 if leading is disabled.\n")
  1102. {
  1103. return object->getWeaponLeadVelocity();
  1104. }
  1105. DefineEngineMethod( AITurretShape, setAllGunsFiring, void, (bool fire),,
  1106. "@brief Set the firing state of the turret's guns.\n\n"
  1107. "@param fire Set to true to activate all guns. False to deactivate them.\n")
  1108. {
  1109. object->setAllGunsFiring(fire);
  1110. }
  1111. DefineEngineMethod( AITurretShape, setGunSlotFiring, void, (S32 slot, bool fire),,
  1112. "@brief Set the firing state of the given gun slot.\n\n"
  1113. "@param slot The gun to modify. Valid range is 0-3 that corresponds to the weapon mount point.\n"
  1114. "@param fire Set to true to activate the gun. False to deactivate it.\n")
  1115. {
  1116. object->setGunSlotFiring(slot, fire);
  1117. }
  1118. DefineEngineMethod( AITurretShape, recenterTurret, void, ( ),,
  1119. "@brief Recenter the turret's weapon.\n\n")
  1120. {
  1121. object->recenterTurret();
  1122. }