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