aiTurretShape.cpp 43 KB

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