vehicle.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  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 "platform/platform.h"
  23. #include "T3D/vehicles/vehicle.h"
  24. #include "math/mMath.h"
  25. #include "console/simBase.h"
  26. #include "console/console.h"
  27. #include "console/consoleTypes.h"
  28. #include "console/engineAPI.h"
  29. #include "collision/clippedPolyList.h"
  30. #include "collision/planeExtractor.h"
  31. #include "core/stream/bitStream.h"
  32. #include "core/dnet.h"
  33. #include "T3D/gameBase/gameConnection.h"
  34. #include "T3D/fx/cameraFXMgr.h"
  35. #include "ts/tsShapeInstance.h"
  36. #include "T3D/fx/particleEmitter.h"
  37. #include "sfx/sfxSystem.h"
  38. #include "sfx/sfxProfile.h"
  39. #include "sfx/sfxSource.h"
  40. #include "math/mathIO.h"
  41. #include "scene/sceneRenderState.h"
  42. #include "T3D/trigger.h"
  43. #include "T3D/item.h"
  44. #include "gfx/primBuilder.h"
  45. #include "gfx/gfxDrawUtil.h"
  46. #include "materials/materialDefinition.h"
  47. #include "T3D/physics/physicsPlugin.h"
  48. #include "T3D/physics/physicsBody.h"
  49. #include "T3D/physics/physicsCollision.h"
  50. namespace {
  51. static U32 sWorkingQueryBoxStaleThreshold = 10; // The maximum number of ticks that go by before
  52. // the mWorkingQueryBox is considered stale and
  53. // needs updating. Set to -1 to disable.
  54. static F32 sWorkingQueryBoxSizeMultiplier = 2.0f; // How much larger should the mWorkingQueryBox be
  55. // made when updating the working collision list.
  56. // The larger this number the less often the working list
  57. // will be updated due to motion, but any non-static shape
  58. // that moves into the query box will not be noticed.
  59. // Client prediction
  60. const S32 sMaxWarpTicks = 3; // Max warp duration in ticks
  61. const S32 sMaxPredictionTicks = 30; // Number of ticks to predict
  62. // Physics and collision constants
  63. static F32 sRestTol = 0.5; // % of gravity energy to be at rest
  64. static S32 sRestCount = 10; // Consecutive ticks before comming to rest
  65. } // namespace {}
  66. // Trigger objects that are not normally collided with.
  67. static U32 sTriggerMask = ItemObjectType |
  68. TriggerObjectType |
  69. CorpseObjectType;
  70. IMPLEMENT_CONOBJECT(VehicleData);
  71. typedef VehicleData::Body::Sounds bodySounds;
  72. DefineEnumType(bodySounds);
  73. ImplementEnumType(bodySounds, "enum types.\n"
  74. "@ingroup VehicleData\n\n")
  75. { VehicleData::Body::SoftImpactSound, "SoftImpactSound", "..." },
  76. { VehicleData::Body::HardImpactSound, "HardImpactSound", "..." },
  77. EndImplementEnumType;
  78. typedef VehicleData::Sounds vehSoundsEnum;
  79. DefineEnumType(vehSoundsEnum);
  80. ImplementEnumType(vehSoundsEnum, "enum types.\n"
  81. "@ingroup VehicleData\n\n")
  82. { VehicleData::ExitWater, "ExitWater", "..." },
  83. { VehicleData::ImpactSoft, "ImpactSoft", "..." },
  84. { VehicleData::ImpactMedium, "ImpactMedium", "..." },
  85. { VehicleData::ImpactHard, "ImpactHard", "..." },
  86. { VehicleData::Wake, "Wake", "..." },
  87. EndImplementEnumType;
  88. ConsoleDocClass( VehicleData,
  89. "@brief Base properties shared by all Vehicles (FlyingVehicle, HoverVehicle, "
  90. "WheeledVehicle).\n\n"
  91. "This datablock defines properties shared by all Vehicle types, but should "
  92. "not be instantiated directly. Instead, set the desired properties in the "
  93. "FlyingVehicleData, HoverVehicleData or WheeledVehicleData datablock.\n"
  94. "@section VehicleData_damage Damage\n\n"
  95. "The VehicleData class extends the basic energy/damage functionality provided "
  96. "by ShapeBaseData to include damage from collisions, as well as particle "
  97. "emitters activated automatically when damage levels reach user specified "
  98. "thresholds.\n\n"
  99. "The example below shows how to setup a Vehicle to:\n"
  100. "<ul>\n"
  101. " <li>take damage when colliding with another object\n"
  102. " <li>emit gray smoke particles from two locations on the Vehicle when damaged above 50%</li>\n"
  103. " <li>emit black smoke particles from two locations on the Vehicle when damaged above 85%</li>\n"
  104. " <li>emit bubbles when any active damage emitter point is underwater</li>\n"
  105. "</ul>\n\n"
  106. "@tsexample\n"
  107. "// damage from collisions\n"
  108. "collDamageMultiplier = 0.05;\n"
  109. "collDamageThresholdVel = 15;\n\n"
  110. "// damage levels\n"
  111. "damageLevelTolerance[0] = 0.5;\n"
  112. "damageEmitter[0] = GraySmokeEmitter; // emitter used when damage is >= 50%\n"
  113. "damageLevelTolerance[1] = 0.85;\n"
  114. "damageEmitter[1] = BlackSmokeEmitter; // emitter used when damage is >= 85%\n"
  115. "damageEmitter[2] = DamageBubbleEmitter; // emitter used instead of damageEmitter[0:1]\n"
  116. " // when offset point is underwater\n"
  117. "// emit offsets (used for all active damage level emitters)\n"
  118. "damageEmitterOffset[0] = \"0.5 3 1\";\n"
  119. "damageEmitterOffset[1] = \"-0.5 3 1\";\n"
  120. "numDmgEmitterAreas = 2;\n"
  121. "@endtsexample\n"
  122. "@ingroup Vehicles\n"
  123. );
  124. //----------------------------------------------------------------------------
  125. VehicleData::VehicleData()
  126. {
  127. shadowEnable = true;
  128. shadowSize = 256;
  129. shadowProjectionDistance = 14.0f;
  130. body.friction = 0;
  131. body.restitution = 1;
  132. minImpactSpeed = 25;
  133. softImpactSpeed = 25;
  134. hardImpactSpeed = 50;
  135. minRollSpeed = 0;
  136. maxSteeringAngle = M_PI_F/4.0f; // 45 deg.
  137. cameraRoll = true;
  138. cameraLag = 0;
  139. cameraDecay = 0;
  140. cameraOffset = 0;
  141. minDrag = 0;
  142. maxDrag = 0;
  143. integration = 1;
  144. collisionTol = 0.1f;
  145. contactTol = 0.1f;
  146. massCenter.set(0,0,0);
  147. massBox.set(0,0,0);
  148. drag = 0.7f;
  149. density = 4;
  150. jetForce = 500;
  151. jetEnergyDrain = 0.8f;
  152. minJetEnergy = 1;
  153. steeringReturn = 0.0f;
  154. steeringReturnSpeedScale = 0.01f;
  155. powerSteering = false;
  156. for (S32 i = 0; i < Body::MaxSounds; i++)
  157. {
  158. INIT_ASSET_ARRAY(VehicleBodySounds, i);
  159. }
  160. dustEmitter = NULL;
  161. dustID = 0;
  162. triggerDustHeight = 3.0;
  163. dustHeight = 1.0;
  164. dMemset( damageEmitterList, 0, sizeof( damageEmitterList ) );
  165. dMemset( damageEmitterOffset, 0, sizeof( damageEmitterOffset ) );
  166. dMemset( damageEmitterIDList, 0, sizeof( damageEmitterIDList ) );
  167. dMemset( damageLevelTolerance, 0, sizeof( damageLevelTolerance ) );
  168. dMemset( splashEmitterList, 0, sizeof( splashEmitterList ) );
  169. dMemset( splashEmitterIDList, 0, sizeof( splashEmitterIDList ) );
  170. numDmgEmitterAreas = 0;
  171. splashFreqMod = 300.0;
  172. splashVelEpsilon = 0.50;
  173. exitSplashSoundVel = 2.0;
  174. softSplashSoundVel = 1.0;
  175. medSplashSoundVel = 2.0;
  176. hardSplashSoundVel = 3.0;
  177. for (S32 i = 0; i < Sounds::MaxSounds; i++)
  178. INIT_ASSET_ARRAY(VehicleWaterSounds, i);
  179. collDamageThresholdVel = 20;
  180. collDamageMultiplier = 0.05f;
  181. enablePhysicsRep = true;
  182. }
  183. //----------------------------------------------------------------------------
  184. bool VehicleData::preload(bool server, String &errorStr)
  185. {
  186. if (!Parent::preload(server, errorStr))
  187. return false;
  188. // Vehicle objects must define a collision detail
  189. if (!collisionDetails.size() || collisionDetails[0] == -1)
  190. {
  191. Con::errorf("VehicleData::preload failed: Vehicle models must define a collision-1 detail");
  192. errorStr = String::ToString("VehicleData: Couldn't load shape asset \"%s\"", mShapeAsset.getAssetId());
  193. return false;
  194. }
  195. // Resolve objects transmitted from server
  196. if (!server) {
  197. for (S32 i = 0; i < Body::MaxSounds; i++)
  198. {
  199. if (getVehicleBodySounds(i) != StringTable->EmptyString() )
  200. {
  201. _setVehicleBodySounds(getVehicleBodySounds(i), i);
  202. }
  203. }
  204. for (S32 j = 0; j < Sounds::MaxSounds; j++)
  205. {
  206. if (getVehicleWaterSounds(j) != StringTable->EmptyString())
  207. {
  208. _setVehicleWaterSounds(getVehicleWaterSounds(j), j);
  209. }
  210. }
  211. }
  212. if( !dustEmitter && dustID != 0 )
  213. {
  214. if( !Sim::findObject( dustID, dustEmitter ) )
  215. {
  216. Con::errorf( ConsoleLogEntry::General, "VehicleData::preload Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID );
  217. }
  218. }
  219. U32 i;
  220. for( i=0; i<VC_NUM_DAMAGE_EMITTERS; i++ )
  221. {
  222. if( !damageEmitterList[i] && damageEmitterIDList[i] != 0 )
  223. {
  224. if( !Sim::findObject( damageEmitterIDList[i], damageEmitterList[i] ) )
  225. {
  226. Con::errorf( ConsoleLogEntry::General, "VehicleData::preload Invalid packet, bad datablockId(damageEmitter): 0x%x", damageEmitterIDList[i] );
  227. }
  228. }
  229. }
  230. for( i=0; i<VC_NUM_SPLASH_EMITTERS; i++ )
  231. {
  232. if( !splashEmitterList[i] && splashEmitterIDList[i] != 0 )
  233. {
  234. if( !Sim::findObject( splashEmitterIDList[i], splashEmitterList[i] ) )
  235. {
  236. Con::errorf( ConsoleLogEntry::General, "VehicleData::preload Invalid packet, bad datablockId(splashEmitter): 0x%x", splashEmitterIDList[i] );
  237. }
  238. }
  239. }
  240. return true;
  241. }
  242. //----------------------------------------------------------------------------
  243. void VehicleData::packData(BitStream* stream)
  244. {
  245. S32 i;
  246. Parent::packData(stream);
  247. stream->write(body.restitution);
  248. stream->write(body.friction);
  249. for (i = 0; i < Body::MaxSounds; i++)
  250. {
  251. PACKDATA_ASSET_ARRAY(VehicleBodySounds, i);
  252. }
  253. stream->write(minImpactSpeed);
  254. stream->write(softImpactSpeed);
  255. stream->write(hardImpactSpeed);
  256. stream->write(minRollSpeed);
  257. stream->write(maxSteeringAngle);
  258. stream->write(maxDrag);
  259. stream->write(minDrag);
  260. stream->write(integration);
  261. stream->write(collisionTol);
  262. stream->write(contactTol);
  263. mathWrite(*stream,massCenter);
  264. mathWrite(*stream,massBox);
  265. stream->write(jetForce);
  266. stream->write(jetEnergyDrain);
  267. stream->write(minJetEnergy);
  268. stream->write(steeringReturn);
  269. stream->write(steeringReturnSpeedScale);
  270. stream->writeFlag(powerSteering);
  271. stream->writeFlag(cameraRoll);
  272. stream->write(cameraLag);
  273. stream->write(cameraDecay);
  274. stream->write(cameraOffset);
  275. stream->write( triggerDustHeight );
  276. stream->write( dustHeight );
  277. stream->write( numDmgEmitterAreas );
  278. stream->write(exitSplashSoundVel);
  279. stream->write(softSplashSoundVel);
  280. stream->write(medSplashSoundVel);
  281. stream->write(hardSplashSoundVel);
  282. stream->write(enablePhysicsRep);
  283. // write the water sound profiles
  284. for (i = 0; i < MaxSounds; i++)
  285. {
  286. PACKDATA_ASSET_ARRAY(VehicleWaterSounds, i);
  287. }
  288. if (stream->writeFlag( dustEmitter ))
  289. {
  290. stream->writeRangedU32( dustEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  291. }
  292. for (i = 0; i < VC_NUM_DAMAGE_EMITTERS; i++)
  293. {
  294. if( stream->writeFlag( damageEmitterList[i] != NULL ) )
  295. {
  296. stream->writeRangedU32( damageEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  297. }
  298. }
  299. for (i = 0; i < VC_NUM_SPLASH_EMITTERS; i++)
  300. {
  301. if( stream->writeFlag( splashEmitterList[i] != NULL ) )
  302. {
  303. stream->writeRangedU32( splashEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  304. }
  305. }
  306. for (S32 j = 0; j < VC_NUM_DAMAGE_EMITTER_AREAS; j++)
  307. {
  308. stream->write( damageEmitterOffset[j].x );
  309. stream->write( damageEmitterOffset[j].y );
  310. stream->write( damageEmitterOffset[j].z );
  311. }
  312. for (S32 k = 0; k < VC_NUM_DAMAGE_LEVELS; k++)
  313. {
  314. stream->write( damageLevelTolerance[k] );
  315. }
  316. stream->write(splashFreqMod);
  317. stream->write(splashVelEpsilon);
  318. stream->write(collDamageThresholdVel);
  319. stream->write(collDamageMultiplier);
  320. }
  321. void VehicleData::unpackData(BitStream* stream)
  322. {
  323. Parent::unpackData(stream);
  324. stream->read(&body.restitution);
  325. stream->read(&body.friction);
  326. S32 i;
  327. for (i = 0; i < Body::MaxSounds; i++)
  328. {
  329. UNPACKDATA_ASSET_ARRAY(VehicleBodySounds, i);
  330. }
  331. stream->read(&minImpactSpeed);
  332. stream->read(&softImpactSpeed);
  333. stream->read(&hardImpactSpeed);
  334. stream->read(&minRollSpeed);
  335. stream->read(&maxSteeringAngle);
  336. stream->read(&maxDrag);
  337. stream->read(&minDrag);
  338. stream->read(&integration);
  339. stream->read(&collisionTol);
  340. stream->read(&contactTol);
  341. mathRead(*stream,&massCenter);
  342. mathRead(*stream,&massBox);
  343. stream->read(&jetForce);
  344. stream->read(&jetEnergyDrain);
  345. stream->read(&minJetEnergy);
  346. stream->read(&steeringReturn);
  347. stream->read(&steeringReturnSpeedScale);
  348. powerSteering = stream->readFlag();
  349. cameraRoll = stream->readFlag();
  350. stream->read(&cameraLag);
  351. stream->read(&cameraDecay);
  352. stream->read(&cameraOffset);
  353. stream->read( &triggerDustHeight );
  354. stream->read( &dustHeight );
  355. stream->read( &numDmgEmitterAreas );
  356. stream->read(&exitSplashSoundVel);
  357. stream->read(&softSplashSoundVel);
  358. stream->read(&medSplashSoundVel);
  359. stream->read(&hardSplashSoundVel);
  360. stream->read(&enablePhysicsRep);
  361. // write the water sound profiles
  362. for (i = 0; i < Sounds::MaxSounds; i++)
  363. {
  364. UNPACKDATA_ASSET_ARRAY(VehicleWaterSounds, i);
  365. }
  366. if( stream->readFlag() )
  367. {
  368. dustID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  369. }
  370. for (i = 0; i < VC_NUM_DAMAGE_EMITTERS; i++)
  371. {
  372. if( stream->readFlag() )
  373. {
  374. damageEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  375. }
  376. }
  377. for (i = 0; i < VC_NUM_SPLASH_EMITTERS; i++)
  378. {
  379. if( stream->readFlag() )
  380. {
  381. splashEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  382. }
  383. }
  384. for( S32 j=0; j<VC_NUM_DAMAGE_EMITTER_AREAS; j++ )
  385. {
  386. stream->read( &damageEmitterOffset[j].x );
  387. stream->read( &damageEmitterOffset[j].y );
  388. stream->read( &damageEmitterOffset[j].z );
  389. }
  390. for( S32 k=0; k<VC_NUM_DAMAGE_LEVELS; k++ )
  391. {
  392. stream->read( &damageLevelTolerance[k] );
  393. }
  394. stream->read(&splashFreqMod);
  395. stream->read(&splashVelEpsilon);
  396. stream->read(&collDamageThresholdVel);
  397. stream->read(&collDamageMultiplier);
  398. }
  399. //----------------------------------------------------------------------------
  400. void VehicleData::initPersistFields()
  401. {
  402. addGroup("Physics");
  403. addField("enablePhysicsRep", TypeBool, Offset(enablePhysicsRep, VehicleData),
  404. "@brief Creates a representation of the object in the physics plugin.\n");
  405. endGroup("Physics");
  406. addField( "jetForce", TypeF32, Offset(jetForce, VehicleData),
  407. "@brief Additional force applied to the vehicle when it is jetting.\n\n"
  408. "For WheeledVehicles, the force is applied in the forward direction. For "
  409. "FlyingVehicles, the force is applied in the thrust direction." );
  410. addField( "jetEnergyDrain", TypeF32, Offset(jetEnergyDrain, VehicleData),
  411. "@brief Energy amount to drain for each tick the vehicle is jetting.\n\n"
  412. "Once the vehicle's energy level reaches 0, it will no longer be able to jet." );
  413. addField( "minJetEnergy", TypeF32, Offset(minJetEnergy, VehicleData),
  414. "Minimum vehicle energy level to begin jetting." );
  415. addField( "steeringReturn", TypeF32, Offset(steeringReturn, VehicleData),
  416. "Rate at which the vehicle's steering returns to forwards when it is moving." );
  417. addField( "steeringReturnSpeedScale", TypeF32, Offset(steeringReturnSpeedScale, VehicleData),
  418. "Amount of effect the vehicle's speed has on its rate of steering return." );
  419. addField( "powerSteering", TypeBool, Offset(powerSteering, VehicleData),
  420. "If true, steering does not auto-centre while the vehicle is being steered by its driver." );
  421. addField( "massCenter", TypePoint3F, Offset(massCenter, VehicleData),
  422. "Defines the vehicle's center of mass (offset from the origin of the model)." );
  423. addField( "massBox", TypePoint3F, Offset(massBox, VehicleData),
  424. "@brief Define the box used to estimate the vehicle's moment of inertia.\n\n"
  425. "Currently only used by WheeledVehicle; other vehicle types use a "
  426. "unit sphere to compute inertia." );
  427. addField( "bodyRestitution", TypeF32, Offset(body.restitution, VehicleData),
  428. "Collision 'bounciness'.\nNormally in the range 0 (not bouncy at all) to "
  429. "1 (100% bounciness)." );
  430. addField( "bodyFriction", TypeF32, Offset(body.friction, VehicleData),
  431. "Collision friction coefficient.\nHow well this object will slide against "
  432. "objects it collides with." );
  433. INITPERSISTFIELD_SOUNDASSET_ENUMED(VehicleBodySounds, bodySounds, Body::Sounds::MaxSounds, VehicleData, "Sounds for vehicle body impacts.");
  434. addField( "minImpactSpeed", TypeF32, Offset(minImpactSpeed, VehicleData),
  435. "Minimum collision speed for the onImpact callback to be invoked." );
  436. addField( "softImpactSpeed", TypeF32, Offset(softImpactSpeed, VehicleData),
  437. "Minimum collision speed for the softImpactSound to be played." );
  438. addField( "hardImpactSpeed", TypeF32, Offset(hardImpactSpeed, VehicleData),
  439. "Minimum collision speed for the hardImpactSound to be played." );
  440. addField( "minRollSpeed", TypeF32, Offset(minRollSpeed, VehicleData),
  441. "Unused" );
  442. addField( "maxSteeringAngle", TypeF32, Offset(maxSteeringAngle, VehicleData),
  443. "Maximum yaw (horizontal) and pitch (vertical) steering angle in radians." );
  444. addField( "maxDrag", TypeF32, Offset(maxDrag, VehicleData),
  445. "Maximum drag coefficient.\nCurrently unused." );
  446. addField( "minDrag", TypeF32, Offset(minDrag, VehicleData),
  447. "Minimum drag coefficient.\nCurrently only used by FlyingVehicle." );
  448. addField( "integration", TypeS32, Offset(integration, VehicleData),
  449. "Number of integration steps per tick.\nIncrease this to improve simulation "
  450. "stability (also increases simulation processing time)." );
  451. addField( "collisionTol", TypeF32, Offset(collisionTol, VehicleData),
  452. "Minimum distance between objects for them to be considered as colliding." );
  453. addField( "contactTol", TypeF32, Offset(contactTol, VehicleData),
  454. "Maximum relative velocity between objects for collisions to be resolved "
  455. "as contacts.\nVelocities greater than this are handled as collisions." );
  456. addField( "cameraRoll", TypeBool, Offset(cameraRoll, VehicleData),
  457. "If true, the camera will roll with the vehicle. If false, the camera will "
  458. "always have the positive Z axis as up." );
  459. addField( "cameraLag", TypeF32, Offset(cameraLag, VehicleData),
  460. "@brief How much the camera lags behind the vehicle depending on vehicle speed.\n\n"
  461. "Increasing this value will make the camera fall further behind the vehicle "
  462. "as it accelerates away.\n\n@see cameraDecay." );
  463. addField("cameraDecay", TypeF32, Offset(cameraDecay, VehicleData),
  464. "How quickly the camera moves back towards the vehicle when stopped.\n\n"
  465. "@see cameraLag." );
  466. addField("cameraOffset", TypeF32, Offset(cameraOffset, VehicleData),
  467. "Vertical (Z axis) height of the camera above the vehicle." );
  468. addField( "dustEmitter", TYPEID< ParticleEmitterData >(), Offset(dustEmitter, VehicleData),
  469. "Dust particle emitter.\n\n@see triggerDustHeight\n\n@see dustHeight");
  470. addField( "triggerDustHeight", TypeF32, Offset(triggerDustHeight, VehicleData),
  471. "@brief Maximum height above surface to emit dust particles.\n\n"
  472. "If the vehicle is less than triggerDustHeight above a static surface "
  473. "with a material that has 'showDust' set to true, the vehicle will emit "
  474. "particles from the dustEmitter." );
  475. addField( "dustHeight", TypeF32, Offset(dustHeight, VehicleData),
  476. "Height above ground at which to emit particles from the dustEmitter." );
  477. addField( "damageEmitter", TYPEID< ParticleEmitterData >(), Offset(damageEmitterList, VehicleData), VC_NUM_DAMAGE_EMITTERS,
  478. "@brief Array of particle emitters used to generate damage (dust, smoke etc) "
  479. "effects.\n\n"
  480. "Currently, the first two emitters (indices 0 and 1) are used when the damage "
  481. "level exceeds the associated damageLevelTolerance. The 3rd emitter is used "
  482. "when the emitter point is underwater.\n\n"
  483. "@see damageEmitterOffset" );
  484. addField( "damageEmitterOffset", TypePoint3F, Offset(damageEmitterOffset, VehicleData), VC_NUM_DAMAGE_EMITTER_AREAS,
  485. "@brief Object space \"x y z\" offsets used to emit particles for the "
  486. "active damageEmitter.\n\n"
  487. "@tsexample\n"
  488. "// damage levels\n"
  489. "damageLevelTolerance[0] = 0.5;\n"
  490. "damageEmitter[0] = SmokeEmitter;\n"
  491. "// emit offsets (used for all active damage level emitters)\n"
  492. "damageEmitterOffset[0] = \"0.5 3 1\";\n"
  493. "damageEmitterOffset[1] = \"-0.5 3 1\";\n"
  494. "numDmgEmitterAreas = 2;\n"
  495. "@endtsexample\n" );
  496. addField( "damageLevelTolerance", TypeF32, Offset(damageLevelTolerance, VehicleData), VC_NUM_DAMAGE_LEVELS,
  497. "@brief Damage levels (as a percentage of maxDamage) above which to begin "
  498. "emitting particles from the associated damageEmitter.\n\n"
  499. "Levels should be in order of increasing damage.\n\n"
  500. "@see damageEmitterOffset" );
  501. addField( "numDmgEmitterAreas", TypeF32, Offset(numDmgEmitterAreas, VehicleData),
  502. "Number of damageEmitterOffset values to use for each damageEmitter.\n\n"
  503. "@see damageEmitterOffset" );
  504. addField( "splashEmitter", TYPEID< ParticleEmitterData >(), Offset(splashEmitterList, VehicleData), VC_NUM_SPLASH_EMITTERS,
  505. "Array of particle emitters used to generate splash effects." );
  506. addField( "splashFreqMod", TypeF32, Offset(splashFreqMod, VehicleData),
  507. "@brief Number of splash particles to generate based on vehicle speed.\n\n"
  508. "This value is multiplied by the current speed to determine how many "
  509. "particles to generate each frame." );
  510. addField( "splashVelEpsilon", TypeF32, Offset(splashVelEpsilon, VehicleData),
  511. "Minimum speed when moving through water to generate splash particles." );
  512. addField( "exitSplashSoundVelocity", TypeF32, Offset(exitSplashSoundVel, VehicleData),
  513. "Minimum velocity when leaving the water for the exitingWater sound to play." );
  514. addField( "softSplashSoundVelocity", TypeF32, Offset(softSplashSoundVel, VehicleData),
  515. "Minimum velocity when entering the water for the imapactWaterEasy sound "
  516. "to play.\n\n@see impactWaterEasy" );
  517. addField( "mediumSplashSoundVelocity", TypeF32, Offset(medSplashSoundVel, VehicleData),
  518. "Minimum velocity when entering the water for the imapactWaterMedium sound "
  519. "to play.\n\n@see impactWaterMedium" );
  520. addField( "hardSplashSoundVelocity", TypeF32, Offset(hardSplashSoundVel, VehicleData),
  521. "Minimum velocity when entering the water for the imapactWaterHard sound "
  522. "to play.\n\n@see impactWaterHard" );
  523. INITPERSISTFIELD_SOUNDASSET_ENUMED(WaterSounds, vehSoundsEnum, VehicleData::Sounds::MaxSounds, VehicleData, "Sounds for interacting with water.");
  524. addField( "collDamageThresholdVel", TypeF32, Offset(collDamageThresholdVel, VehicleData),
  525. "Minimum collision velocity to cause damage to this vehicle.\nCurrently unused." );
  526. addField( "collDamageMultiplier", TypeF32, Offset(collDamageMultiplier, VehicleData),
  527. "@brief Damage to this vehicle after a collision (multiplied by collision "
  528. "velocity).\n\nCurrently unused." );
  529. Parent::initPersistFields();
  530. }
  531. //----------------------------------------------------------------------------
  532. //----------------------------------------------------------------------------
  533. //----------------------------------------------------------------------------
  534. IMPLEMENT_CONOBJECT(Vehicle);
  535. ConsoleDocClass( Vehicle,
  536. "@brief Base functionality shared by all Vehicles (FlyingVehicle, HoverVehicle, "
  537. "WheeledVehicle).\n\n"
  538. "This object implements functionality shared by all Vehicle types, but should "
  539. "not be instantiated directly. Create a FlyingVehicle, HoverVehicle, or "
  540. "WheeledVehicle instead.\n"
  541. "@note The model used for any Vehicle must include a collision mesh at detail "
  542. "size -1.\n"
  543. "@ingroup Vehicles\n"
  544. );
  545. Vehicle::Vehicle()
  546. {
  547. mDataBlock = 0;
  548. mTypeMask |= VehicleObjectType | DynamicShapeObjectType;
  549. mDelta.pos = Point3F(0,0,0);
  550. mDelta.posVec = Point3F(0,0,0);
  551. mDelta.warpTicks = mDelta.warpCount = 0;
  552. mDelta.dt = 1;
  553. mDelta.move = NullMove;
  554. mPredictionCount = 0;
  555. mDelta.cameraOffset.set(0,0,0);
  556. mDelta.cameraVec.set(0,0,0);
  557. mDelta.cameraRot.set(0,0,0);
  558. mDelta.cameraRotVec.set(0,0,0);
  559. mRigid.linPosition.set(0, 0, 0);
  560. mRigid.linVelocity.set(0, 0, 0);
  561. mRigid.angPosition.identity();
  562. mRigid.angVelocity.set(0, 0, 0);
  563. mRigid.linMomentum.set(0, 0, 0);
  564. mRigid.angMomentum.set(0, 0, 0);
  565. mContacts.clear();
  566. mSteering.set(0,0);
  567. mThrottle = 0;
  568. mJetting = false;
  569. mCameraOffset.set(0,0,0);
  570. dMemset( mDamageEmitterList, 0, sizeof( mDamageEmitterList ) );
  571. mDisableMove = false;
  572. restCount = 0;
  573. inLiquid = false;
  574. mWakeSound = NULL;
  575. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  576. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  577. mWorkingQueryBoxCountDown = sWorkingQueryBoxStaleThreshold;
  578. mPhysicsRep = NULL;
  579. }
  580. U32 Vehicle::getCollisionMask()
  581. {
  582. AssertFatal(false, "Vehicle::getCollisionMask is pure virtual!");
  583. return 0;
  584. }
  585. //----------------------------------------------------------------------------
  586. bool Vehicle::onAdd()
  587. {
  588. if (!Parent::onAdd())
  589. return false;
  590. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  591. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  592. // When loading from a mission script, the base SceneObject's transform
  593. // will have been set and needs to be transfered to the rigid body.
  594. mRigid.setTransform(mObjToWorld);
  595. // Initialize interpolation vars.
  596. mDelta.rot[1] = mDelta.rot[0] = mRigid.angPosition;
  597. mDelta.pos = mRigid.linPosition;
  598. mDelta.posVec = Point3F(0,0,0);
  599. // Create Emitters on the client
  600. if( isClientObject() )
  601. {
  602. U32 j;
  603. for( j=0; j<VehicleData::VC_NUM_DAMAGE_EMITTERS; j++ )
  604. {
  605. if( mDataBlock->damageEmitterList[j] )
  606. {
  607. mDamageEmitterList[j] = new ParticleEmitter;
  608. mDamageEmitterList[j]->onNewDataBlock( mDataBlock->damageEmitterList[j], false );
  609. if( !mDamageEmitterList[j]->registerObject() )
  610. {
  611. Con::warnf( ConsoleLogEntry::General, "Could not register damage emitter for class: %s", mDataBlock->getName() );
  612. delete mDamageEmitterList[j];
  613. mDamageEmitterList[j] = NULL;
  614. }
  615. }
  616. }
  617. }
  618. // Create a new convex.
  619. AssertFatal(mDataBlock->collisionDetails[0] != -1, "Error, a vehicle must have a collision-1 detail!");
  620. mConvex.mObject = this;
  621. mConvex.pShapeBase = this;
  622. mConvex.hullId = 0;
  623. mConvex.box = mObjBox;
  624. mConvex.box.minExtents.convolve(mObjScale);
  625. mConvex.box.maxExtents.convolve(mObjScale);
  626. mConvex.findNodeTransform();
  627. _createPhysics();
  628. return true;
  629. }
  630. void Vehicle::onRemove()
  631. {
  632. SAFE_DELETE(mPhysicsRep);
  633. U32 i=0;
  634. for( i=0; i<VehicleData::VC_NUM_DAMAGE_EMITTERS; i++ )
  635. {
  636. if( mDamageEmitterList[i] )
  637. {
  638. mDamageEmitterList[i]->deleteWhenEmpty();
  639. mDamageEmitterList[i] = NULL;
  640. }
  641. }
  642. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  643. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  644. Parent::onRemove();
  645. }
  646. //----------------------------------------------------------------------------
  647. void Vehicle::processTick(const Move* move)
  648. {
  649. PROFILE_SCOPE( Vehicle_ProcessTick );
  650. ShapeBase::processTick(move);
  651. if ( isMounted() )
  652. return;
  653. // Warp to catch up to server
  654. if (mDelta.warpCount < mDelta.warpTicks)
  655. {
  656. mDelta.warpCount++;
  657. // Set new pos.
  658. mObjToWorld.getColumn(3,&mDelta.pos);
  659. mDelta.pos += mDelta.warpOffset;
  660. mDelta.rot[0] = mDelta.rot[1];
  661. mDelta.rot[1].interpolate(mDelta.warpRot[0],mDelta.warpRot[1],F32(mDelta.warpCount)/mDelta.warpTicks);
  662. setPosition(mDelta.pos,mDelta.rot[1]);
  663. // Pos backstepping
  664. mDelta.posVec.x = -mDelta.warpOffset.x;
  665. mDelta.posVec.y = -mDelta.warpOffset.y;
  666. mDelta.posVec.z = -mDelta.warpOffset.z;
  667. }
  668. else
  669. {
  670. if (!move)
  671. {
  672. if (isGhost())
  673. {
  674. // If we haven't run out of prediction time,
  675. // predict using the last known move.
  676. if (mPredictionCount-- <= 0)
  677. return;
  678. move = &mDelta.move;
  679. }
  680. else
  681. move = &NullMove;
  682. }
  683. // Process input move
  684. updateMove(move);
  685. // Save current rigid state interpolation
  686. mDelta.posVec = mRigid.linPosition;
  687. mDelta.rot[0] = mRigid.angPosition;
  688. // Update the physics based on the integration rate
  689. S32 count = mDataBlock->integration;
  690. --mWorkingQueryBoxCountDown;
  691. if (!mDisableMove)
  692. updateWorkingCollisionSet(getCollisionMask());
  693. for (U32 i = 0; i < count; i++)
  694. updatePos(TickSec / count);
  695. // Wrap up interpolation info
  696. mDelta.pos = mRigid.linPosition;
  697. mDelta.posVec -= mRigid.linPosition;
  698. mDelta.rot[1] = mRigid.angPosition;
  699. // Update container database
  700. setPosition(mRigid.linPosition, mRigid.angPosition);
  701. setMaskBits(PositionMask);
  702. updateContainer();
  703. //TODO: Only update when position has actually changed
  704. //no need to check if mDataBlock->enablePhysicsRep is false as mPhysicsRep will be NULL if it is
  705. if (mPhysicsRep)
  706. mPhysicsRep->moveKinematicTo(getTransform());
  707. }
  708. }
  709. void Vehicle::advanceTime(F32 dt)
  710. {
  711. PROFILE_SCOPE( Vehicle_AdvanceTime );
  712. Parent::advanceTime(dt);
  713. updateLiftoffDust( dt );
  714. updateDamageSmoke( dt );
  715. }
  716. //----------------------------------------------------------------------------
  717. bool Vehicle::onNewDataBlock(GameBaseData* dptr,bool reload)
  718. {
  719. mDataBlock = dynamic_cast<VehicleData*>(dptr);
  720. if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
  721. return false;
  722. // Update Rigid Info
  723. mRigid.mass = mDataBlock->mass;
  724. mRigid.oneOverMass = 1 / mRigid.mass;
  725. mRigid.friction = mDataBlock->body.friction;
  726. mRigid.restitution = mDataBlock->body.restitution;
  727. mRigid.setCenterOfMass(mDataBlock->massCenter);
  728. // Ignores massBox, just set sphere for now. Derived objects
  729. // can set what they want.
  730. mRigid.setObjectInertia();
  731. if (isGhost())
  732. {
  733. // Create the sound ahead of time. This reduces runtime
  734. // costs and makes the system easier to understand.
  735. SFX_DELETE( mWakeSound );
  736. if ( mDataBlock->getVehicleWaterSounds(VehicleData::Wake) != NULL )
  737. mWakeSound = SFX->createSource( mDataBlock->getVehicleWaterSoundProfile(VehicleData::Wake), &getTransform() );
  738. }
  739. return true;
  740. }
  741. //----------------------------------------------------------------------------
  742. void Vehicle::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot)
  743. {
  744. *min = mDataBlock->cameraMinDist;
  745. *max = mDataBlock->cameraMaxDist;
  746. off->set(0,0,mDataBlock->cameraOffset);
  747. rot->identity();
  748. }
  749. //----------------------------------------------------------------------------
  750. void Vehicle::getCameraTransform(F32* pos, MatrixF* mat)
  751. {
  752. // Returns camera to world space transform
  753. // Handles first person / third person camera position
  754. if (isServerObject() && mShapeInstance)
  755. mShapeInstance->animateNodeSubtrees(true);
  756. if (*pos == 0)
  757. {
  758. getRenderEyeTransform(mat);
  759. }
  760. else
  761. {
  762. // Get the shape's camera parameters.
  763. F32 min, max;
  764. MatrixF rot;
  765. Point3F offset;
  766. getCameraParameters(&min, &max, &offset, &rot);
  767. // Start with the current eye position
  768. MatrixF eye;
  769. getRenderEyeTransform(&eye);
  770. // Build a transform that points along the eye axis
  771. // but where the Z axis is always up.
  772. if (mDataBlock->cameraRoll)
  773. mat->mul(eye, rot);
  774. else
  775. {
  776. MatrixF cam(1);
  777. VectorF x, y, z(0, 0, 1);
  778. eye.getColumn(1, &y);
  779. mCross(y, z, &x);
  780. x.normalize();
  781. mCross(x, y, &z);
  782. z.normalize();
  783. cam.setColumn(0, x);
  784. cam.setColumn(1, y);
  785. cam.setColumn(2, z);
  786. mat->mul(cam, rot);
  787. }
  788. // Camera is positioned straight back along the eye's -Y axis.
  789. // A ray is cast to make sure the camera doesn't go through
  790. // anything solid.
  791. VectorF vp, vec;
  792. vp.x = vp.z = 0;
  793. vp.y = -(max - min) * *pos;
  794. eye.mulV(vp, &vec);
  795. // Use the camera node as the starting position if it exists.
  796. Point3F osp, sp;
  797. if (mDataBlock->cameraNode != -1)
  798. {
  799. mShapeInstance->mNodeTransforms[mDataBlock->cameraNode].getColumn(3, &osp);
  800. getRenderTransform().mulP(osp, &sp);
  801. }
  802. else
  803. eye.getColumn(3, &sp);
  804. // Make sure we don't hit ourself...
  805. disableCollision();
  806. if (isMounted())
  807. getObjectMount()->disableCollision();
  808. // Cast the ray into the container database to see if we're going
  809. // to hit anything.
  810. RayInfo collision;
  811. Point3F ep = sp + vec + offset + mCameraOffset;
  812. if (mContainer->castRay(sp, ep,
  813. ~(WaterObjectType | GameBaseObjectType | DefaultObjectType | sTriggerMask),
  814. &collision) == true) {
  815. // Shift the collision point back a little to try and
  816. // avoid clipping against the front camera plane.
  817. F32 t = collision.t - (-mDot(vec, collision.normal) / vec.len()) * 0.1;
  818. if (t > 0.0f)
  819. ep = sp + offset + mCameraOffset + (vec * t);
  820. else
  821. eye.getColumn(3, &ep);
  822. }
  823. mat->setColumn(3, ep);
  824. // Re-enable our collision.
  825. if (isMounted())
  826. getObjectMount()->enableCollision();
  827. enableCollision();
  828. }
  829. // Apply Camera FX.
  830. mat->mul( gCamFXMgr.getTrans() );
  831. }
  832. //----------------------------------------------------------------------------
  833. void Vehicle::updateMove(const Move* move)
  834. {
  835. PROFILE_SCOPE( Vehicle_UpdateMove );
  836. mDelta.move = *move;
  837. // Image Triggers
  838. if (mDamageState == Enabled) {
  839. setImageTriggerState(0,move->trigger[0]);
  840. setImageTriggerState(1,move->trigger[1]);
  841. }
  842. // Throttle
  843. if(!mDisableMove)
  844. mThrottle = move->y;
  845. // Steering
  846. if (move != &NullMove) {
  847. F32 y = move->yaw;
  848. mSteering.x = mClampF(mSteering.x + y,-mDataBlock->maxSteeringAngle,
  849. mDataBlock->maxSteeringAngle);
  850. F32 p = move->pitch;
  851. mSteering.y = mClampF(mSteering.y + p,-mDataBlock->maxSteeringAngle,
  852. mDataBlock->maxSteeringAngle);
  853. }
  854. else {
  855. mSteering.x = 0;
  856. mSteering.y = 0;
  857. }
  858. // Steering return
  859. if(mDataBlock->steeringReturn > 0.0f &&
  860. (!mDataBlock->powerSteering || (move->yaw == 0.0f && move->pitch == 0.0f)))
  861. {
  862. Point2F returnAmount(mSteering.x * mDataBlock->steeringReturn * TickSec,
  863. mSteering.y * mDataBlock->steeringReturn * TickSec);
  864. if(mDataBlock->steeringReturnSpeedScale > 0.0f)
  865. {
  866. Point3F vel;
  867. mWorldToObj.mulV(getVelocity(), &vel);
  868. returnAmount += Point2F(mSteering.x * vel.y * mDataBlock->steeringReturnSpeedScale * TickSec,
  869. mSteering.y * vel.y * mDataBlock->steeringReturnSpeedScale * TickSec);
  870. }
  871. mSteering -= returnAmount;
  872. }
  873. // Jetting flag
  874. if (move->trigger[3]) {
  875. if (!mJetting && getEnergyLevel() >= mDataBlock->minJetEnergy)
  876. mJetting = true;
  877. if (mJetting) {
  878. F32 newEnergy = getEnergyLevel() - mDataBlock->jetEnergyDrain;
  879. if (newEnergy < 0) {
  880. newEnergy = 0;
  881. mJetting = false;
  882. }
  883. setEnergyLevel(newEnergy);
  884. }
  885. }
  886. else
  887. mJetting = false;
  888. }
  889. //----------------------------------------------------------------------------
  890. /** Update the physics
  891. */
  892. void Vehicle::updatePos(F32 dt)
  893. {
  894. PROFILE_SCOPE( Vehicle_UpdatePos );
  895. Point3F origVelocity = mRigid.linVelocity;
  896. // Update internal forces acting on the body.
  897. mRigid.clearForces();
  898. updateForces(dt);
  899. // Update collision information based on our current pos.
  900. bool collided = false;
  901. if (!mRigid.atRest && !mDisableMove)
  902. {
  903. collided = updateCollision(dt);
  904. // Now that all the forces have been processed, lets
  905. // see if we're at rest. Basically, if the kinetic energy of
  906. // the vehicles is less than some percentage of the energy added
  907. // by gravity for a short period, we're considered at rest.
  908. // This should really be part of the rigid class...
  909. if (mCollisionList.getCount())
  910. {
  911. F32 k = mRigid.getKineticEnergy();
  912. F32 G = mNetGravity * dt;
  913. F32 Kg = 0.5 * mRigid.mass * G * G;
  914. if (k < sRestTol * Kg && ++restCount > sRestCount)
  915. mRigid.setAtRest();
  916. }
  917. else
  918. restCount = 0;
  919. }
  920. // Integrate forward
  921. if (!mRigid.atRest && !mDisableMove)
  922. mRigid.integrate(dt);
  923. // Deal with client and server scripting, sounds, etc.
  924. if (isServerObject()) {
  925. // Check triggers and other objects that we normally don't
  926. // collide with. This function must be called before notifyCollision
  927. // as it will queue collision.
  928. checkTriggers();
  929. // Invoke the onCollision notify callback for all the objects
  930. // we've just hit.
  931. notifyCollision();
  932. // Server side impact script callback
  933. if (collided) {
  934. VectorF collVec = mRigid.linVelocity - origVelocity;
  935. F32 collSpeed = collVec.len();
  936. if (collSpeed > mDataBlock->minImpactSpeed)
  937. onImpact(collVec);
  938. }
  939. // Water script callbacks
  940. if (!inLiquid && mWaterCoverage != 0.0f) {
  941. mDataBlock->onEnterLiquid_callback( this, mWaterCoverage, mLiquidType.c_str() );
  942. inLiquid = true;
  943. }
  944. else if (inLiquid && mWaterCoverage == 0.0f) {
  945. mDataBlock->onLeaveLiquid_callback( this, mLiquidType.c_str() );
  946. inLiquid = false;
  947. }
  948. }
  949. else {
  950. // Play impact sounds on the client.
  951. if (collided) {
  952. F32 collSpeed = (mRigid.linVelocity - origVelocity).len();
  953. S32 impactSound = -1;
  954. if (collSpeed >= mDataBlock->hardImpactSpeed)
  955. impactSound = VehicleData::Body::HardImpactSound;
  956. else
  957. if (collSpeed >= mDataBlock->softImpactSpeed)
  958. impactSound = VehicleData::Body::SoftImpactSound;
  959. if (impactSound != -1 && mDataBlock->getVehicleBodySounds(impactSound) != NULL)
  960. SFX->playOnce( mDataBlock->getVehicleBodySoundProfile(impactSound), &getTransform() );
  961. }
  962. // Water volume sounds
  963. F32 vSpeed = getVelocity().len();
  964. if (!inLiquid && mWaterCoverage >= 0.8f) {
  965. if (vSpeed >= mDataBlock->hardSplashSoundVel)
  966. SFX->playOnce( mDataBlock->getVehicleWaterSoundProfile(VehicleData::ImpactHard), &getTransform() );
  967. else
  968. if (vSpeed >= mDataBlock->medSplashSoundVel)
  969. SFX->playOnce( mDataBlock->getVehicleWaterSoundProfile(VehicleData::ImpactMedium), &getTransform() );
  970. else
  971. if (vSpeed >= mDataBlock->softSplashSoundVel)
  972. SFX->playOnce( mDataBlock->getVehicleWaterSoundProfile(VehicleData::ImpactSoft), &getTransform() );
  973. inLiquid = true;
  974. }
  975. else
  976. if(inLiquid && mWaterCoverage < 0.8f) {
  977. if (vSpeed >= mDataBlock->exitSplashSoundVel)
  978. SFX->playOnce( mDataBlock->getVehicleWaterSoundProfile(VehicleData::ExitWater), &getTransform() );
  979. inLiquid = false;
  980. }
  981. }
  982. }
  983. //----------------------------------------------------------------------------
  984. void Vehicle::updateForces(F32 /*dt*/)
  985. {
  986. // Nothing here.
  987. }
  988. /** The callback used in by the checkTriggers() method.
  989. The checkTriggers method uses a container search which will
  990. invoke this callback on each obj that matches.
  991. */
  992. void Vehicle::findCallback(SceneObject* obj,void *key)
  993. {
  994. Vehicle* vehicle = reinterpret_cast<Vehicle*>(key);
  995. U32 objectMask = obj->getTypeMask();
  996. // Check: triggers, corpses and items, basically the same things
  997. // that the player class checks for
  998. if (objectMask & TriggerObjectType) {
  999. Trigger* pTrigger = static_cast<Trigger*>(obj);
  1000. pTrigger->potentialEnterObject(vehicle);
  1001. }
  1002. else if (objectMask & CorpseObjectType) {
  1003. ShapeBase* col = static_cast<ShapeBase*>(obj);
  1004. vehicle->queueCollision(col,vehicle->getVelocity() - col->getVelocity());
  1005. }
  1006. else if (objectMask & ItemObjectType) {
  1007. Item* item = static_cast<Item*>(obj);
  1008. if (vehicle != item->getCollisionObject())
  1009. vehicle->queueCollision(item,vehicle->getVelocity() - item->getVelocity());
  1010. }
  1011. }
  1012. //----------------------------------------------------------------------------
  1013. void Vehicle::writePacketData(GameConnection *connection, BitStream *stream)
  1014. {
  1015. Parent::writePacketData(connection, stream);
  1016. mathWrite(*stream, mSteering);
  1017. mathWrite(*stream, mRigid.linPosition);
  1018. mathWrite(*stream, mRigid.angPosition);
  1019. mathWrite(*stream, mRigid.linMomentum);
  1020. mathWrite(*stream, mRigid.angMomentum);
  1021. stream->writeFlag(mRigid.atRest);
  1022. stream->writeFlag(mContacts.getCount() == 0);
  1023. stream->writeFlag(mDisableMove);
  1024. stream->setCompressionPoint(mRigid.linPosition);
  1025. }
  1026. void Vehicle::readPacketData(GameConnection *connection, BitStream *stream)
  1027. {
  1028. Parent::readPacketData(connection, stream);
  1029. mathRead(*stream, &mSteering);
  1030. mathRead(*stream, &mRigid.linPosition);
  1031. mathRead(*stream, &mRigid.angPosition);
  1032. mathRead(*stream, &mRigid.linMomentum);
  1033. mathRead(*stream, &mRigid.angMomentum);
  1034. mRigid.atRest = stream->readFlag();
  1035. if (stream->readFlag())
  1036. mContacts.clear();
  1037. mRigid.updateInertialTensor();
  1038. mRigid.updateVelocity();
  1039. mRigid.updateCenterOfMass();
  1040. mDisableMove = stream->readFlag();
  1041. stream->setCompressionPoint(mRigid.linPosition);
  1042. }
  1043. //----------------------------------------------------------------------------
  1044. U32 Vehicle::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  1045. {
  1046. U32 retMask = Parent::packUpdate(con, mask, stream);
  1047. stream->writeFlag(mJetting);
  1048. // The rest of the data is part of the control object packet update.
  1049. // If we're controlled by this client, we don't need to send it.
  1050. if (stream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask)))
  1051. return retMask;
  1052. F32 yaw = (mSteering.x + mDataBlock->maxSteeringAngle) / (2 * mDataBlock->maxSteeringAngle);
  1053. F32 pitch = (mSteering.y + mDataBlock->maxSteeringAngle) / (2 * mDataBlock->maxSteeringAngle);
  1054. stream->writeFloat(yaw,9);
  1055. stream->writeFloat(pitch,9);
  1056. mDelta.move.pack(stream);
  1057. if (stream->writeFlag(mask & PositionMask))
  1058. {
  1059. stream->writeCompressedPoint(mRigid.linPosition);
  1060. mathWrite(*stream, mRigid.angPosition);
  1061. mathWrite(*stream, mRigid.linMomentum);
  1062. mathWrite(*stream, mRigid.angMomentum);
  1063. stream->writeFlag(mRigid.atRest);
  1064. }
  1065. stream->writeFloat(mClampF(getEnergyValue(), 0.f, 1.f), 8);
  1066. return retMask;
  1067. }
  1068. void Vehicle::unpackUpdate(NetConnection *con, BitStream *stream)
  1069. {
  1070. Parent::unpackUpdate(con,stream);
  1071. mJetting = stream->readFlag();
  1072. if (stream->readFlag())
  1073. return;
  1074. F32 yaw = stream->readFloat(9);
  1075. F32 pitch = stream->readFloat(9);
  1076. mSteering.x = (2 * yaw * mDataBlock->maxSteeringAngle) - mDataBlock->maxSteeringAngle;
  1077. mSteering.y = (2 * pitch * mDataBlock->maxSteeringAngle) - mDataBlock->maxSteeringAngle;
  1078. mDelta.move.unpack(stream);
  1079. if (stream->readFlag())
  1080. {
  1081. mPredictionCount = sMaxPredictionTicks;
  1082. F32 speed = mRigid.linVelocity.len();
  1083. mDelta.warpRot[0] = mRigid.angPosition;
  1084. // Read in new position and momentum values
  1085. stream->readCompressedPoint(&mRigid.linPosition);
  1086. mathRead(*stream, &mRigid.angPosition);
  1087. mathRead(*stream, &mRigid.linMomentum);
  1088. mathRead(*stream, &mRigid.angMomentum);
  1089. mRigid.atRest = stream->readFlag();
  1090. mRigid.updateVelocity();
  1091. if (isProperlyAdded())
  1092. {
  1093. // Determine number of ticks to warp based on the average
  1094. // of the client and server velocities.
  1095. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt;
  1096. mDelta.warpOffset = mRigid.linPosition - cp;
  1097. // Calc the distance covered in one tick as the average of
  1098. // the old speed and the new speed from the server.
  1099. F32 dt,as = (speed + mRigid.linVelocity.len()) * 0.5 * TickSec;
  1100. // Cal how many ticks it will take to cover the warp offset.
  1101. // If it's less than what's left in the current tick, we'll just
  1102. // warp in the remaining time.
  1103. if (!as || (dt = mDelta.warpOffset.len() / as) > sMaxWarpTicks)
  1104. dt = mDelta.dt + sMaxWarpTicks;
  1105. else
  1106. dt = (dt <= mDelta.dt)? mDelta.dt : mCeil(dt - mDelta.dt) + mDelta.dt;
  1107. // Adjust current frame interpolation
  1108. if (mDelta.dt) {
  1109. mDelta.pos = cp + (mDelta.warpOffset * (mDelta.dt / dt));
  1110. mDelta.posVec = (cp - mDelta.pos) / mDelta.dt;
  1111. QuatF cr;
  1112. cr.interpolate(mDelta.rot[1],mDelta.rot[0],mDelta.dt);
  1113. mDelta.rot[1].interpolate(cr,mRigid.angPosition,mDelta.dt / dt);
  1114. mDelta.rot[0].extrapolate(mDelta.rot[1],cr,mDelta.dt);
  1115. }
  1116. // Calculated multi-tick warp
  1117. mDelta.warpCount = 0;
  1118. mDelta.warpTicks = (S32)(mFloor(dt));
  1119. if (mDelta.warpTicks)
  1120. {
  1121. mDelta.warpOffset = mRigid.linPosition - mDelta.pos;
  1122. mDelta.warpOffset /= (F32)mDelta.warpTicks;
  1123. mDelta.warpRot[0] = mDelta.rot[1];
  1124. mDelta.warpRot[1] = mRigid.angPosition;
  1125. }
  1126. }
  1127. else
  1128. {
  1129. // Set the vehicle to the server position
  1130. mDelta.dt = 0;
  1131. mDelta.pos = mRigid.linPosition;
  1132. mDelta.posVec.set(0,0,0);
  1133. mDelta.rot[1] = mDelta.rot[0] = mRigid.angPosition;
  1134. mDelta.warpCount = mDelta.warpTicks = 0;
  1135. setPosition(mRigid.linPosition, mRigid.angPosition);
  1136. }
  1137. mRigid.updateCenterOfMass();
  1138. }
  1139. setEnergyLevel(stream->readFloat(8) * mDataBlock->maxEnergy);
  1140. }
  1141. //----------------------------------------------------------------------------
  1142. void Vehicle::consoleInit()
  1143. {
  1144. Con::addVariable("$vehicle::workingQueryBoxStaleThreshold",TypeS32,&sWorkingQueryBoxStaleThreshold,
  1145. "@brief The maximum number of ticks that go by before the mWorkingQueryBox is considered stale and needs updating.\n\n"
  1146. "Other factors can cause the collision working query box to become invalidated, such as the vehicle moving far "
  1147. "enough outside of this cached box. The smaller this number, the more times the working list of triangles that are "
  1148. "considered for collision is refreshed. This has the greatest impact with colliding with high triangle count meshes.\n\n"
  1149. "@note Set to -1 to disable any time-based forced check.\n\n"
  1150. "@ingroup GameObjects\n");
  1151. Con::addVariable("$vehicle::workingQueryBoxSizeMultiplier",TypeF32,&sWorkingQueryBoxSizeMultiplier,
  1152. "@brief How much larger the mWorkingQueryBox should be made when updating the working collision list.\n\n"
  1153. "The larger this number the less often the working list will be updated due to motion, but any non-static shape that "
  1154. "moves into the query box will not be noticed.\n\n"
  1155. "@ingroup GameObjects\n");
  1156. }
  1157. void Vehicle::initPersistFields()
  1158. {
  1159. addField( "disableMove", TypeBool, Offset(mDisableMove, Vehicle),
  1160. "When this flag is set, the vehicle will ignore throttle changes." );
  1161. Parent::initPersistFields();
  1162. }
  1163. void Vehicle::mountObject(SceneObject *obj, S32 node, const MatrixF &xfm )
  1164. {
  1165. Parent::mountObject( obj, node, xfm );
  1166. // Clear objects off the working list that are from objects mounted to us.
  1167. // (This applies mostly to players...)
  1168. for ( CollisionWorkingList* itr = mConvex.getWorkingList().wLink.mNext;
  1169. itr != &mConvex.getWorkingList();
  1170. itr = itr->wLink.mNext)
  1171. {
  1172. if (itr->mConvex->getObject() == obj)
  1173. {
  1174. CollisionWorkingList* cl = itr;
  1175. itr = itr->wLink.mPrev;
  1176. cl->free();
  1177. }
  1178. }
  1179. }
  1180. //----------------------------------------------------------------------------
  1181. void Vehicle::updateLiftoffDust( F32 dt )
  1182. {
  1183. Point3F offset( 0.0, 0.0, mDataBlock->dustHeight );
  1184. emitDust( mDustEmitterList[ 0 ], mDataBlock->triggerDustHeight, offset,
  1185. ( U32 )( dt * 1000 ) );
  1186. }
  1187. //----------------------------------------------------------------------------
  1188. void Vehicle::updateDamageSmoke( F32 dt )
  1189. {
  1190. for( S32 j=VehicleData::VC_NUM_DAMAGE_LEVELS-1; j>=0; j-- )
  1191. {
  1192. F32 damagePercent = mDamage / mDataBlock->maxDamage;
  1193. if( damagePercent >= mDataBlock->damageLevelTolerance[j] )
  1194. {
  1195. for( S32 i=0; i<mDataBlock->numDmgEmitterAreas; i++ )
  1196. {
  1197. MatrixF trans = getTransform();
  1198. Point3F offset = mDataBlock->damageEmitterOffset[i];
  1199. trans.mulP( offset );
  1200. Point3F emitterPoint = offset;
  1201. if( pointInWater(offset ) )
  1202. {
  1203. U32 emitterOffset = VehicleData::VC_BUBBLE_EMITTER;
  1204. if( mDamageEmitterList[emitterOffset] )
  1205. {
  1206. mDamageEmitterList[emitterOffset]->emitParticles( emitterPoint, emitterPoint, Point3F( 0.0, 0.0, 1.0 ), getVelocity(), (U32)( dt * 1000 ) );
  1207. }
  1208. }
  1209. else
  1210. {
  1211. if( mDamageEmitterList[j] )
  1212. {
  1213. mDamageEmitterList[j]->emitParticles( emitterPoint, emitterPoint, Point3F( 0.0, 0.0, 1.0 ), getVelocity(), (U32)(dt * 1000));
  1214. }
  1215. }
  1216. }
  1217. break;
  1218. }
  1219. }
  1220. }
  1221. //--------------------------------------------------------------------------
  1222. void Vehicle::updateFroth( F32 dt )
  1223. {
  1224. // update bubbles
  1225. Point3F moveDir = getVelocity();
  1226. Point3F contactPoint;
  1227. if( !collidingWithWater( contactPoint ) )
  1228. {
  1229. if ( mWakeSound )
  1230. mWakeSound->stop();
  1231. return;
  1232. }
  1233. F32 speed = moveDir.len();
  1234. if( speed < mDataBlock->splashVelEpsilon ) speed = 0.0;
  1235. U32 emitRate = (U32)(speed * mDataBlock->splashFreqMod * dt);
  1236. U32 i;
  1237. if ( mWakeSound )
  1238. {
  1239. if ( !mWakeSound->isPlaying() )
  1240. mWakeSound->play();
  1241. mWakeSound->setTransform( getTransform() );
  1242. mWakeSound->setVelocity( getVelocity() );
  1243. }
  1244. for( i=0; i<VehicleData::VC_NUM_SPLASH_EMITTERS; i++ )
  1245. {
  1246. if( mSplashEmitterList[i] )
  1247. {
  1248. mSplashEmitterList[i]->emitParticles( contactPoint, contactPoint, Point3F( 0.0, 0.0, 1.0 ),
  1249. moveDir, emitRate );
  1250. }
  1251. }
  1252. }
  1253. void Vehicle::prepBatchRender( SceneRenderState *state, S32 mountedImageIndex )
  1254. {
  1255. Parent::prepBatchRender( state, mountedImageIndex );
  1256. if ( !gShowBoundingBox )
  1257. return;
  1258. if ( mountedImageIndex != -1 )
  1259. {
  1260. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1261. ri->renderDelegate.bind( this, &Vehicle::_renderMuzzleVector );
  1262. ri->objectIndex = mountedImageIndex;
  1263. ri->type = RenderPassManager::RIT_Editor;
  1264. state->getRenderPass()->addInst( ri );
  1265. return;
  1266. }
  1267. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1268. ri->renderDelegate.bind( this, &Vehicle::_renderMassAndContacts );
  1269. ri->type = RenderPassManager::RIT_Editor;
  1270. state->getRenderPass()->addInst( ri );
  1271. }
  1272. void Vehicle::_renderMassAndContacts( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  1273. {
  1274. GFXStateBlockDesc desc;
  1275. desc.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1276. desc.setZReadWrite(false,true);
  1277. desc.fillMode = GFXFillWireframe;
  1278. // Render the mass center.
  1279. GFX->getDrawUtil()->drawCube(desc, Point3F(0.1f,0.1f,0.1f),mDataBlock->massCenter, ColorI(255, 255, 255), &mRenderObjToWorld);
  1280. // Now render all the contact points.
  1281. for (S32 i = 0; i < mCollisionList.getCount(); i++)
  1282. {
  1283. const Collision& collision = mCollisionList[i];
  1284. GFX->getDrawUtil()->drawCube(desc, Point3F(0.05f,0.05f,0.05f),collision.point, ColorI(0, 0, 255));
  1285. }
  1286. // Finally render the normals as one big batch.
  1287. PrimBuild::begin(GFXLineList, mCollisionList.getCount() * 2);
  1288. for (S32 i = 0; i < mCollisionList.getCount(); i++)
  1289. {
  1290. const Collision& collision = mCollisionList[i];
  1291. PrimBuild::color3f(1, 1, 1);
  1292. PrimBuild::vertex3fv(collision.point);
  1293. PrimBuild::vertex3fv(collision.point + collision.normal * 0.05f);
  1294. }
  1295. PrimBuild::end();
  1296. // Build and render the collision polylist which is returned
  1297. // in the server's world space.
  1298. ClippedPolyList polyList;
  1299. polyList.mPlaneList.setSize(6);
  1300. polyList.mPlaneList[0].set(getWorldBox().minExtents,VectorF(-1,0,0));
  1301. polyList.mPlaneList[1].set(getWorldBox().minExtents,VectorF(0,-1,0));
  1302. polyList.mPlaneList[2].set(getWorldBox().minExtents,VectorF(0,0,-1));
  1303. polyList.mPlaneList[3].set(getWorldBox().maxExtents,VectorF(1,0,0));
  1304. polyList.mPlaneList[4].set(getWorldBox().maxExtents,VectorF(0,1,0));
  1305. polyList.mPlaneList[5].set(getWorldBox().maxExtents,VectorF(0,0,1));
  1306. Box3F dummyBox;
  1307. SphereF dummySphere;
  1308. buildPolyList(PLC_Collision, &polyList, dummyBox, dummySphere);
  1309. //polyList.render();
  1310. }
  1311. void Vehicle::_renderMuzzleVector( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  1312. {
  1313. const U32 index = ri->objectIndex;
  1314. AssertFatal( index > 0 && index < MaxMountedImages, "Vehicle::_renderMuzzleVector() - Bad object index!" );
  1315. AssertFatal( mMountedImageList[index].dataBlock, "Vehicle::_renderMuzzleVector() - Bad object index!" );
  1316. Point3F muzzlePoint, muzzleVector, endpoint;
  1317. getMuzzlePoint(index, &muzzlePoint);
  1318. getMuzzleVector(index, &muzzleVector);
  1319. endpoint = muzzlePoint + muzzleVector * 250;
  1320. if (mSolidSB.isNull())
  1321. {
  1322. GFXStateBlockDesc desc;
  1323. desc.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1324. desc.setZReadWrite(false);
  1325. mSolidSB = GFX->createStateBlock(desc);
  1326. }
  1327. GFX->setStateBlock(mSolidSB);
  1328. PrimBuild::begin(GFXLineList, 2);
  1329. PrimBuild::color4f(0, 1, 0, 1);
  1330. PrimBuild::vertex3fv(muzzlePoint);
  1331. PrimBuild::vertex3fv(endpoint);
  1332. PrimBuild::end();
  1333. }