rigidShape.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  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/rigidShape.h"
  24. #include "app/game.h"
  25. #include "math/mMath.h"
  26. #include "console/simBase.h"
  27. #include "console/console.h"
  28. #include "console/consoleTypes.h"
  29. #include "collision/clippedPolyList.h"
  30. #include "collision/planeExtractor.h"
  31. #include "T3D/gameBase/moveManager.h"
  32. #include "core/stream/bitStream.h"
  33. #include "core/dnet.h"
  34. #include "T3D/gameBase/gameConnection.h"
  35. #include "ts/tsShapeInstance.h"
  36. #include "math/mathIO.h"
  37. #include "scene/sceneRenderState.h"
  38. #include "scene/sceneManager.h"
  39. #include "T3D/fx/cameraFXMgr.h"
  40. #include "T3D/trigger.h"
  41. #include "T3D/item.h"
  42. #include "gfx/primBuilder.h"
  43. #include "gfx/gfxDrawUtil.h"
  44. #include "sfx/sfxTypes.h"
  45. #include "sfx/sfxSystem.h"
  46. #include "T3D/fx/particleEmitter.h"
  47. #include "console/engineAPI.h"
  48. IMPLEMENT_CO_DATABLOCK_V1(RigidShapeData);
  49. ConsoleDocClass( RigidShapeData,
  50. "@brief Defines the physics properties for an individual RigidShapeData physics object.\n\n"
  51. "@tsexample\n"
  52. " datablock RigidShapeData( BouncingBoulder )\n"
  53. " {\n"
  54. " category = \"RigidShape\";\n"
  55. "\n"
  56. " shapeFile = \"~/data/shapes/boulder/boulder.dts\";\n"
  57. " emap = true;\n"
  58. "\n"
  59. " // Rigid Body\n"
  60. " mass = 500;\n"
  61. " massCenter = \"0 0 0\"; // Center of mass for rigid body\n"
  62. " massBox = \"0 0 0\"; // Size of box used for moment of inertia,\n"
  63. " // if zero it defaults to object bounding box\n"
  64. " drag = 0.2; // Drag coefficient\n"
  65. " bodyFriction = 0.2;\n"
  66. " bodyRestitution = 0.1;\n"
  67. " minImpactSpeed = 5; // Impacts over this invoke the script callback\n"
  68. " softImpactSpeed = 5; // Play SoftImpact Sound\n"
  69. " hardImpactSpeed = 15; // Play HardImpact Sound\n"
  70. " integration = 4; // Physics integration: TickSec/Rate\n"
  71. " collisionTol = 0.1; // Collision distance tolerance\n"
  72. " contactTol = 0.1; // Contact velocity tolerance\n"
  73. "\n"
  74. " minRollSpeed = 10;\n"
  75. "\n"
  76. " maxDrag = 0.5;\n"
  77. " minDrag = 0.01;\n"
  78. "\n"
  79. " dustHeight = 10;\n"
  80. "\n"
  81. " dragForce = 0.05;\n"
  82. " vertFactor = 0.05;\n"
  83. " };\n"
  84. "@endtsexample\n\n"
  85. "@see RigidShape\n"
  86. "@see ShapeBase\n\n"
  87. "@ingroup Physics\n"
  88. );
  89. IMPLEMENT_CO_NETOBJECT_V1(RigidShape);
  90. ConsoleDocClass( RigidShape,
  91. "@brief The RigidShape class implements rigid-body physics for DTS objects in the world.\n\n"
  92. "\"Rigid body physics\" refers to a system whereby objects are assumed to have a finite size,\n"
  93. "equally distributed masses, and where deformations of the objects themselves are not accounted for.\n"
  94. "Uses the RigidShape class to control its physics.\n\n"
  95. "@tsexample\n"
  96. " datablock RigidShapeData( BouncingBoulder )\n"
  97. " {\n"
  98. " category = \"RigidShape\";\n"
  99. "\n"
  100. " shapeFile = \"~/data/shapes/boulder/boulder.dts\";\n"
  101. " emap = true;\n"
  102. "\n"
  103. " // Rigid Body\n"
  104. " mass = 500;\n"
  105. " massCenter = \"0 0 0\"; // Center of mass for rigid body\n"
  106. " massBox = \"0 0 0\"; // Size of box used for moment of inertia,\n"
  107. " // if zero it defaults to object bounding box\n"
  108. " drag = 0.2; // Drag coefficient\n"
  109. " bodyFriction = 0.2;\n"
  110. " bodyRestitution = 0.1;\n"
  111. " minImpactSpeed = 5; // Impacts over this invoke the script callback\n"
  112. " softImpactSpeed = 5; // Play SoftImpact Sound\n"
  113. " hardImpactSpeed = 15; // Play HardImpact Sound\n"
  114. " integration = 4; // Physics integration: TickSec/Rate\n"
  115. " collisionTol = 0.1; // Collision distance tolerance\n"
  116. " contactTol = 0.1; // Contact velocity tolerance\n"
  117. "\n"
  118. " minRollSpeed = 10;\n"
  119. "\n"
  120. " maxDrag = 0.5;\n"
  121. " minDrag = 0.01;\n"
  122. "\n"
  123. " dustHeight = 10;\n"
  124. "\n"
  125. " dragForce = 0.05;\n"
  126. " vertFactor = 0.05;\n"
  127. " };\n"
  128. "\n"
  129. " new RigidShape()\n"
  130. " {\n"
  131. " dataBlock = \"BouncingBoulder\";\n"
  132. " parentGroup = EWCreatorWindow.objectGroup;\n"
  133. " };\n"
  134. "@endtsexample\n\n"
  135. "@see RigidShapeData\n"
  136. "@see ShapeBase\n\n"
  137. "@ingroup Physics\n"
  138. );
  139. IMPLEMENT_CALLBACK( RigidShape, onEnterLiquid, void, ( const char* objId, F32 waterCoverage, const char* liquidType ),
  140. ( objId, waterCoverage, liquidType ),
  141. "@brief Called whenever this RigidShape object enters liquid.\n\n"
  142. "@param objId The ID of the rigidShape object.\n"
  143. "@param waterCoverage Amount of water coverage the RigidShape has.\n"
  144. "@param liquidType Type of liquid that was entered.\n\n"
  145. "@tsexample\n"
  146. "// The RigidShape object falls in a body of liquid, causing the callback to occur.\n"
  147. "RigidShape::onEnterLiquid(%this,%objId,%waterCoverage,%liquidType)\n"
  148. " {\n"
  149. " // Code to run whenever this callback occurs.\n"
  150. " }\n"
  151. "@endtsexample\n\n"
  152. "@see ShapeBase\n\n"
  153. );
  154. IMPLEMENT_CALLBACK( RigidShape, onLeaveLiquid, void, ( const char* objId, const char* liquidType ),( objId, liquidType ),
  155. "@brief Called whenever the RigidShape object exits liquid.\n\n"
  156. "@param objId The ID of the RigidShape object.\n"
  157. "@param liquidType Type if liquid that was exited.\n\n"
  158. "@tsexample\n"
  159. "// The RigidShape object exits in a body of liquid, causing the callback to occur.\n"
  160. "RigidShape::onLeaveLiquid(%this,%objId,%liquidType)\n"
  161. " {\n"
  162. " // Code to run whenever this callback occurs.\n"
  163. " }\n"
  164. "@endtsexample\n\n"
  165. "@see ShapeBase\n\n"
  166. );
  167. //----------------------------------------------------------------------------
  168. namespace {
  169. const U32 sMoveRetryCount = 3;
  170. // Client prediction
  171. const S32 sMaxWarpTicks = 3; // Max warp duration in ticks
  172. const S32 sMaxPredictionTicks = 30; // Number of ticks to predict
  173. const F32 sRigidShapeGravity = -20;
  174. // Physics and collision constants
  175. static F32 sRestTol = 0.5; // % of gravity energy to be at rest
  176. static S32 sRestCount = 10; // Consecutive ticks before comming to rest
  177. const U32 sCollisionMoveMask = ( TerrainObjectType | PlayerObjectType |
  178. StaticShapeObjectType | VehicleObjectType |
  179. VehicleBlockerObjectType );
  180. const U32 sServerCollisionMask = sCollisionMoveMask; // ItemObjectType
  181. const U32 sClientCollisionMask = sCollisionMoveMask;
  182. void nonFilter(SceneObject* object,void *key)
  183. {
  184. SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
  185. object->buildPolyList(info->context,info->polyList,info->boundingBox,info->boundingSphere);
  186. }
  187. } // namespace {}
  188. // Trigger objects that are not normally collided with.
  189. static U32 sTriggerMask = ItemObjectType |
  190. TriggerObjectType |
  191. CorpseObjectType;
  192. //----------------------------------------------------------------------------
  193. RigidShapeData::RigidShapeData()
  194. {
  195. shadowEnable = true;
  196. body.friction = 0;
  197. body.restitution = 1;
  198. minImpactSpeed = 25;
  199. softImpactSpeed = 25;
  200. hardImpactSpeed = 50;
  201. minRollSpeed = 0;
  202. cameraRoll = true;
  203. cameraLag = 0;
  204. cameraDecay = 0;
  205. cameraOffset = 0;
  206. minDrag = 0;
  207. maxDrag = 0;
  208. integration = 1;
  209. collisionTol = 0.1f;
  210. contactTol = 0.1f;
  211. massCenter.set(0,0,0);
  212. massBox.set(0,0,0);
  213. drag = 0.7f;
  214. density = 4;
  215. for (S32 i = 0; i < Body::MaxSounds; i++)
  216. body.sound[i] = 0;
  217. dustEmitter = NULL;
  218. dustID = 0;
  219. dustHeight = 1.0;
  220. dMemset( splashEmitterList, 0, sizeof( splashEmitterList ) );
  221. dMemset( splashEmitterIDList, 0, sizeof( splashEmitterIDList ) );
  222. splashFreqMod = 300.0;
  223. splashVelEpsilon = 0.50;
  224. exitSplashSoundVel = 2.0;
  225. softSplashSoundVel = 1.0;
  226. medSplashSoundVel = 2.0;
  227. hardSplashSoundVel = 3.0;
  228. dMemset(waterSound, 0, sizeof(waterSound));
  229. dragForce = 0;
  230. vertFactor = 0.25;
  231. dustTrailEmitter = NULL;
  232. dustTrailID = 0;
  233. }
  234. RigidShapeData::~RigidShapeData()
  235. {
  236. }
  237. //----------------------------------------------------------------------------
  238. bool RigidShapeData::onAdd()
  239. {
  240. if(!Parent::onAdd())
  241. return false;
  242. return true;
  243. }
  244. bool RigidShapeData::preload(bool server, String &errorStr)
  245. {
  246. if (!Parent::preload(server, errorStr))
  247. return false;
  248. // RigidShape objects must define a collision detail
  249. if (!collisionDetails.size() || collisionDetails[0] == -1)
  250. {
  251. Con::errorf("RigidShapeData::preload failed: Rigid shapes must define a collision-1 detail");
  252. errorStr = String::ToString("RigidShapeData: Couldn't load shape \"%s\"",shapeName);
  253. return false;
  254. }
  255. // Resolve objects transmitted from server
  256. if (!server) {
  257. for (S32 i = 0; i < Body::MaxSounds; i++)
  258. sfxResolve( &body.sound[ i ], errorStr );
  259. }
  260. if( !dustEmitter && dustID != 0 )
  261. {
  262. if( !Sim::findObject( dustID, dustEmitter ) )
  263. {
  264. Con::errorf( ConsoleLogEntry::General, "RigidShapeData::preload Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID );
  265. }
  266. }
  267. U32 i;
  268. for( i=0; i<VC_NUM_SPLASH_EMITTERS; i++ )
  269. {
  270. if( !splashEmitterList[i] && splashEmitterIDList[i] != 0 )
  271. {
  272. if( !Sim::findObject( splashEmitterIDList[i], splashEmitterList[i] ) )
  273. {
  274. Con::errorf( ConsoleLogEntry::General, "RigidShapeData::preload Invalid packet, bad datablockId(splashEmitter): 0x%x", splashEmitterIDList[i] );
  275. }
  276. }
  277. }
  278. if (dragForce <= 0.01f)
  279. {
  280. Con::warnf("RigidShapeData::preload: dragForce must be at least 0.01");
  281. dragForce = 0.01f;
  282. }
  283. if (vertFactor < 0.0f || vertFactor > 1.0f)
  284. {
  285. Con::warnf("RigidShapeData::preload: vert factor must be [0, 1]");
  286. vertFactor = vertFactor < 0.0f ? 0.0f : 1.0f;
  287. }
  288. if( !dustTrailEmitter && dustTrailID != 0 )
  289. {
  290. if( !Sim::findObject( dustTrailID, dustTrailEmitter ) )
  291. {
  292. Con::errorf( ConsoleLogEntry::General, "RigidShapeData::preload Invalid packet, bad datablockId(dustTrailEmitter): 0x%x", dustTrailID );
  293. }
  294. }
  295. return true;
  296. }
  297. //----------------------------------------------------------------------------
  298. void RigidShapeData::packData(BitStream* stream)
  299. {
  300. Parent::packData(stream);
  301. stream->write(body.restitution);
  302. stream->write(body.friction);
  303. for( U32 i = 0; i < Body::MaxSounds; ++ i )
  304. sfxWrite( stream, body.sound[ i ] );
  305. stream->write(minImpactSpeed);
  306. stream->write(softImpactSpeed);
  307. stream->write(hardImpactSpeed);
  308. stream->write(minRollSpeed);
  309. stream->write(maxDrag);
  310. stream->write(minDrag);
  311. stream->write(integration);
  312. stream->write(collisionTol);
  313. stream->write(contactTol);
  314. mathWrite(*stream,massCenter);
  315. mathWrite(*stream,massBox);
  316. stream->writeFlag(cameraRoll);
  317. stream->write(cameraLag);
  318. stream->write(cameraDecay);
  319. stream->write(cameraOffset);
  320. stream->write( dustHeight );
  321. stream->write(exitSplashSoundVel);
  322. stream->write(softSplashSoundVel);
  323. stream->write(medSplashSoundVel);
  324. stream->write(hardSplashSoundVel);
  325. // write the water sound profiles
  326. for( U32 i = 0; i < MaxSounds; ++ i )
  327. sfxWrite( stream, waterSound[ i ] );
  328. if (stream->writeFlag( dustEmitter ))
  329. stream->writeRangedU32( dustEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  330. for( U32 i = 0; i < VC_NUM_SPLASH_EMITTERS; ++ i )
  331. {
  332. if( stream->writeFlag( splashEmitterList[i] != NULL ) )
  333. stream->writeRangedU32( splashEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  334. }
  335. stream->write(splashFreqMod);
  336. stream->write(splashVelEpsilon);
  337. stream->write(dragForce);
  338. stream->write(vertFactor);
  339. if (stream->writeFlag( dustTrailEmitter ))
  340. stream->writeRangedU32( dustTrailEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  341. }
  342. void RigidShapeData::unpackData(BitStream* stream)
  343. {
  344. Parent::unpackData(stream);
  345. stream->read(&body.restitution);
  346. stream->read(&body.friction);
  347. for( U32 i = 0; i < Body::MaxSounds; i++)
  348. sfxRead( stream, &body.sound[ i ] );
  349. stream->read(&minImpactSpeed);
  350. stream->read(&softImpactSpeed);
  351. stream->read(&hardImpactSpeed);
  352. stream->read(&minRollSpeed);
  353. stream->read(&maxDrag);
  354. stream->read(&minDrag);
  355. stream->read(&integration);
  356. stream->read(&collisionTol);
  357. stream->read(&contactTol);
  358. mathRead(*stream,&massCenter);
  359. mathRead(*stream,&massBox);
  360. cameraRoll = stream->readFlag();
  361. stream->read(&cameraLag);
  362. stream->read(&cameraDecay);
  363. stream->read(&cameraOffset);
  364. stream->read( &dustHeight );
  365. stream->read(&exitSplashSoundVel);
  366. stream->read(&softSplashSoundVel);
  367. stream->read(&medSplashSoundVel);
  368. stream->read(&hardSplashSoundVel);
  369. // write the water sound profiles
  370. for( U32 i = 0; i < MaxSounds; ++ i )
  371. sfxRead( stream, &waterSound[ i ] );
  372. if( stream->readFlag() )
  373. dustID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  374. for( U32 i = 0; i < VC_NUM_SPLASH_EMITTERS; ++ i )
  375. {
  376. if( stream->readFlag() )
  377. splashEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  378. }
  379. stream->read(&splashFreqMod);
  380. stream->read(&splashVelEpsilon);
  381. stream->read(&dragForce);
  382. stream->read(&vertFactor);
  383. if( stream->readFlag() )
  384. dustTrailID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  385. }
  386. //----------------------------------------------------------------------------
  387. void RigidShapeData::initPersistFields()
  388. {
  389. addField("massCenter", TypePoint3F, Offset(massCenter, RigidShapeData), "Center of mass for rigid body.");
  390. addField("massBox", TypePoint3F, Offset(massBox, RigidShapeData), "Size of inertial box.");
  391. addField("bodyRestitution", TypeF32, Offset(body.restitution, RigidShapeData), "The percentage of kinetic energy kept by this object in a collision.");
  392. addField("bodyFriction", TypeF32, Offset(body.friction, RigidShapeData), "How much friction this object has. Lower values will cause the object to appear to be more slippery.");
  393. addField("minImpactSpeed", TypeF32, Offset(minImpactSpeed, RigidShapeData),
  394. "Minimum collision speed to classify collision as impact (triggers onImpact on server object)." );
  395. addField("softImpactSpeed", TypeF32, Offset(softImpactSpeed, RigidShapeData), "Minimum speed at which this object must be travelling for the soft impact sound to be played.");
  396. addField("hardImpactSpeed", TypeF32, Offset(hardImpactSpeed, RigidShapeData), "Minimum speed at which the object must be travelling for the hard impact sound to be played.");
  397. addField("minRollSpeed", TypeF32, Offset(minRollSpeed, RigidShapeData));
  398. addField("maxDrag", TypeF32, Offset(maxDrag, RigidShapeData), "Maximum drag available to this object.");
  399. addField("minDrag", TypeF32, Offset(minDrag, RigidShapeData), "Minimum drag available to this object.");
  400. addField("integration", TypeS32, Offset(integration, RigidShapeData), "Number of physics steps to process per tick.");
  401. addField("collisionTol", TypeF32, Offset(collisionTol, RigidShapeData), "Collision distance tolerance.");
  402. addField("contactTol", TypeF32, Offset(contactTol, RigidShapeData), "Contact velocity tolerance.");
  403. addGroup( "Forces" );
  404. addField("dragForce", TypeF32, Offset(dragForce, RigidShapeData), "Used to simulate the constant drag acting on the object");
  405. addField("vertFactor", TypeF32, Offset(vertFactor, RigidShapeData), "The scalar applied to the vertical portion of the velocity drag acting on a object.");
  406. endGroup( "Forces" );
  407. addGroup( "Particle Effects" );
  408. addField("dustEmitter", TYPEID< ParticleEmitterData >(), Offset(dustEmitter, RigidShapeData), "Array of pointers to ParticleEmitterData datablocks which will be used to emit particles at object/terrain contact point.\n");
  409. addField("triggerDustHeight", TypeF32, Offset(triggerDustHeight, RigidShapeData), "Maximum height from the ground at which the object will generate dust.\n");
  410. addField("dustHeight", TypeF32, Offset(dustHeight, RigidShapeData), "Height of dust effects.\n");
  411. addField("dustTrailEmitter", TYPEID< ParticleEmitterData >(), Offset(dustTrailEmitter, RigidShapeData), "Particle emitter used to create a dust trail for the moving object.\n");
  412. addField("splashEmitter", TYPEID< ParticleEmitterData >(), Offset(splashEmitterList, RigidShapeData), VC_NUM_SPLASH_EMITTERS, "Array of pointers to ParticleEmitterData datablocks which will generate splash effects.\n");
  413. addField("splashFreqMod", TypeF32, Offset(splashFreqMod, RigidShapeData), "The simulated frequency modulation of a splash generated by this object. Multiplied along with speed and time elapsed when determining splash emition rate.\n");
  414. addField("splashVelEpsilon", TypeF32, Offset(splashVelEpsilon, RigidShapeData), "The threshold speed at which we consider the object's movement to have stopped when updating splash effects.\n");
  415. endGroup( "Particle Effects" );
  416. addGroup( "Sounds" );
  417. addField("softImpactSound", TypeSFXTrackName, Offset(body.sound[Body::SoftImpactSound], RigidShapeData),
  418. "Sound to play when body impacts with at least softImageSpeed but less than hardImpactSpeed." );
  419. addField("hardImpactSound", TypeSFXTrackName, Offset(body.sound[Body::HardImpactSound], RigidShapeData),
  420. "Sound to play when body impacts with at least hardImpactSpeed." );
  421. addField("exitSplashSoundVelocity", TypeF32, Offset(exitSplashSoundVel, RigidShapeData), "The minimum velocity at which the exit splash sound will be played when emerging from water.\n");
  422. addField("softSplashSoundVelocity", TypeF32, Offset(softSplashSoundVel, RigidShapeData),"The minimum velocity at which the soft splash sound will be played when impacting water.\n");
  423. addField("mediumSplashSoundVelocity", TypeF32, Offset(medSplashSoundVel, RigidShapeData), "The minimum velocity at which the medium splash sound will be played when impacting water.\n");
  424. addField("hardSplashSoundVelocity", TypeF32, Offset(hardSplashSoundVel, RigidShapeData), "The minimum velocity at which the hard splash sound will be played when impacting water.\n");
  425. addField("exitingWater", TypeSFXTrackName, Offset(waterSound[ExitWater], RigidShapeData), "The AudioProfile will be used to produce sounds when emerging from water.\n");
  426. addField("impactWaterEasy", TypeSFXTrackName, Offset(waterSound[ImpactSoft], RigidShapeData), "The AudioProfile will be used to produce sounds when a soft impact with water occurs.\n");
  427. addField("impactWaterMedium", TypeSFXTrackName, Offset(waterSound[ImpactMedium], RigidShapeData), "The AudioProfile will be used to produce sounds when a medium impact with water occurs.\n");
  428. addField("impactWaterHard", TypeSFXTrackName, Offset(waterSound[ImpactHard], RigidShapeData), "The AudioProfile will be used to produce sounds when a hard impact with water occurs.\n");
  429. addField("waterWakeSound", TypeSFXTrackName, Offset(waterSound[Wake], RigidShapeData), "The AudioProfile will be used to produce sounds when a water wake is displayed.\n");
  430. endGroup( "Sounds" );
  431. addGroup( "Camera" );
  432. addField("cameraRoll", TypeBool, Offset(cameraRoll, RigidShapeData), "Specifies whether the camera's rotation matrix, and the render eye transform are multiplied during camera updates.\n");
  433. addField("cameraLag", TypeF32, Offset(cameraLag, RigidShapeData), "Scalar amount by which the third person camera lags the object, relative to the object's linear velocity.\n");
  434. addField("cameraDecay", TypeF32, Offset(cameraDecay, RigidShapeData), "Scalar rate at which the third person camera offset decays, per tick.\n");
  435. addField("cameraOffset", TypeF32, Offset(cameraOffset, RigidShapeData), "The vertical offset of the object's camera.\n");
  436. endGroup( "Camera" );
  437. Parent::initPersistFields();
  438. }
  439. //----------------------------------------------------------------------------
  440. //----------------------------------------------------------------------------
  441. //----------------------------------------------------------------------------
  442. RigidShape::RigidShape()
  443. {
  444. mNetFlags.set(Ghostable);
  445. mDustTrailEmitter = NULL;
  446. mDataBlock = 0;
  447. // [rene, 27-Apr-11] WTH is a RigidShape a vehicle???
  448. mTypeMask |= VehicleObjectType | DynamicShapeObjectType;
  449. mDelta.pos = Point3F(0,0,0);
  450. mDelta.posVec = Point3F(0,0,0);
  451. mDelta.warpTicks = mDelta.warpCount = 0;
  452. mDelta.dt = 1;
  453. mDelta.move = NullMove;
  454. mPredictionCount = 0;
  455. mDelta.cameraOffset.set(0,0,0);
  456. mDelta.cameraVec.set(0,0,0);
  457. mDelta.cameraRot.set(0,0,0);
  458. mDelta.cameraRotVec.set(0,0,0);
  459. mRigid.linPosition.set(0, 0, 0);
  460. mRigid.linVelocity.set(0, 0, 0);
  461. mRigid.angPosition.identity();
  462. mRigid.angVelocity.set(0, 0, 0);
  463. mRigid.linMomentum.set(0, 0, 0);
  464. mRigid.angMomentum.set(0, 0, 0);
  465. mContacts.clear();
  466. mCameraOffset.set(0,0,0);
  467. dMemset( mDustEmitterList, 0, sizeof( mDustEmitterList ) );
  468. dMemset( mSplashEmitterList, 0, sizeof( mSplashEmitterList ) );
  469. mDisableMove = false; // start frozen by default
  470. restCount = 0;
  471. inLiquid = false;
  472. }
  473. RigidShape::~RigidShape()
  474. {
  475. //
  476. }
  477. U32 RigidShape::getCollisionMask()
  478. {
  479. if (isServerObject())
  480. return sServerCollisionMask;
  481. else
  482. return sClientCollisionMask;
  483. }
  484. Point3F RigidShape::getVelocity() const
  485. {
  486. return mRigid.linVelocity;
  487. }
  488. //----------------------------------------------------------------------------
  489. bool RigidShape::onAdd()
  490. {
  491. if (!Parent::onAdd())
  492. return false;
  493. // When loading from a mission script, the base SceneObject's transform
  494. // will have been set and needs to be transfered to the rigid body.
  495. mRigid.setTransform(mObjToWorld);
  496. // Initialize interpolation vars.
  497. mDelta.rot[1] = mDelta.rot[0] = mRigid.angPosition;
  498. mDelta.pos = mRigid.linPosition;
  499. mDelta.posVec = Point3F(0,0,0);
  500. // Create Emitters on the client
  501. if( isClientObject() )
  502. {
  503. if( mDataBlock->dustEmitter )
  504. {
  505. for( U32 i=0; i<RigidShapeData::VC_NUM_DUST_EMITTERS; i++ )
  506. {
  507. mDustEmitterList[i] = new ParticleEmitter;
  508. mDustEmitterList[i]->onNewDataBlock( mDataBlock->dustEmitter, false );
  509. if( !mDustEmitterList[i]->registerObject() )
  510. {
  511. Con::warnf( ConsoleLogEntry::General, "Could not register dust emitter for class: %s", mDataBlock->getName() );
  512. delete mDustEmitterList[i];
  513. mDustEmitterList[i] = NULL;
  514. }
  515. }
  516. }
  517. for( U32 j=0; j<RigidShapeData::VC_NUM_SPLASH_EMITTERS; j++ )
  518. {
  519. if( mDataBlock->splashEmitterList[j] )
  520. {
  521. mSplashEmitterList[j] = new ParticleEmitter;
  522. mSplashEmitterList[j]->onNewDataBlock( mDataBlock->splashEmitterList[j], false );
  523. if( !mSplashEmitterList[j]->registerObject() )
  524. {
  525. Con::warnf( ConsoleLogEntry::General, "Could not register splash emitter for class: %s", mDataBlock->getName() );
  526. delete mSplashEmitterList[j];
  527. mSplashEmitterList[j] = NULL;
  528. }
  529. }
  530. }
  531. }
  532. // Create a new convex.
  533. AssertFatal(mDataBlock->collisionDetails[0] != -1, "Error, a rigid shape must have a collision-1 detail!");
  534. mConvex.mObject = this;
  535. mConvex.pShapeBase = this;
  536. mConvex.hullId = 0;
  537. mConvex.box = mObjBox;
  538. mConvex.box.minExtents.convolve(mObjScale);
  539. mConvex.box.maxExtents.convolve(mObjScale);
  540. mConvex.findNodeTransform();
  541. addToScene();
  542. if( !isServerObject() )
  543. {
  544. if( mDataBlock->dustTrailEmitter )
  545. {
  546. mDustTrailEmitter = new ParticleEmitter;
  547. mDustTrailEmitter->onNewDataBlock( mDataBlock->dustTrailEmitter, false );
  548. if( !mDustTrailEmitter->registerObject() )
  549. {
  550. Con::warnf( ConsoleLogEntry::General, "Could not register dust emitter for class: %s", mDataBlock->getName() );
  551. delete mDustTrailEmitter;
  552. mDustTrailEmitter = NULL;
  553. }
  554. }
  555. }
  556. if (isServerObject())
  557. scriptOnAdd();
  558. return true;
  559. }
  560. void RigidShape::onRemove()
  561. {
  562. scriptOnRemove();
  563. removeFromScene();
  564. U32 i=0;
  565. for( i=0; i<RigidShapeData::VC_NUM_DUST_EMITTERS; i++ )
  566. {
  567. if( mDustEmitterList[i] )
  568. {
  569. mDustEmitterList[i]->deleteWhenEmpty();
  570. mDustEmitterList[i] = NULL;
  571. }
  572. }
  573. for( i=0; i<RigidShapeData::VC_NUM_SPLASH_EMITTERS; i++ )
  574. {
  575. if( mSplashEmitterList[i] )
  576. {
  577. mSplashEmitterList[i]->deleteWhenEmpty();
  578. mSplashEmitterList[i] = NULL;
  579. }
  580. }
  581. Parent::onRemove();
  582. }
  583. //----------------------------------------------------------------------------
  584. void RigidShape::processTick(const Move* move)
  585. {
  586. Parent::processTick(move);
  587. // Warp to catch up to server
  588. if (mDelta.warpCount < mDelta.warpTicks)
  589. {
  590. mDelta.warpCount++;
  591. // Set new pos.
  592. mObjToWorld.getColumn(3,&mDelta.pos);
  593. mDelta.pos += mDelta.warpOffset;
  594. mDelta.rot[0] = mDelta.rot[1];
  595. mDelta.rot[1].interpolate(mDelta.warpRot[0],mDelta.warpRot[1],F32(mDelta.warpCount)/mDelta.warpTicks);
  596. setPosition(mDelta.pos,mDelta.rot[1]);
  597. // Pos backstepping
  598. mDelta.posVec.x = -mDelta.warpOffset.x;
  599. mDelta.posVec.y = -mDelta.warpOffset.y;
  600. mDelta.posVec.z = -mDelta.warpOffset.z;
  601. }
  602. else
  603. {
  604. if (!move)
  605. {
  606. if (isGhost())
  607. {
  608. // If we haven't run out of prediction time,
  609. // predict using the last known move.
  610. if (mPredictionCount-- <= 0)
  611. return;
  612. move = &mDelta.move;
  613. }
  614. else
  615. move = &NullMove;
  616. }
  617. // Process input move
  618. updateMove(move);
  619. // Save current rigid state interpolation
  620. mDelta.posVec = mRigid.linPosition;
  621. mDelta.rot[0] = mRigid.angPosition;
  622. // Update the physics based on the integration rate
  623. S32 count = mDataBlock->integration;
  624. if (!mDisableMove)
  625. updateWorkingCollisionSet(getCollisionMask());
  626. for (U32 i = 0; i < count; i++)
  627. updatePos(TickSec / count);
  628. // Wrap up interpolation info
  629. mDelta.pos = mRigid.linPosition;
  630. mDelta.posVec -= mRigid.linPosition;
  631. mDelta.rot[1] = mRigid.angPosition;
  632. // Update container database
  633. setPosition(mRigid.linPosition, mRigid.angPosition);
  634. setMaskBits(PositionMask);
  635. updateContainer();
  636. }
  637. }
  638. void RigidShape::interpolateTick(F32 dt)
  639. {
  640. Parent::interpolateTick(dt);
  641. if(dt == 0.0f)
  642. setRenderPosition(mDelta.pos, mDelta.rot[1]);
  643. else
  644. {
  645. QuatF rot;
  646. rot.interpolate(mDelta.rot[1], mDelta.rot[0], dt);
  647. Point3F pos = mDelta.pos + mDelta.posVec * dt;
  648. setRenderPosition(pos,rot);
  649. }
  650. mDelta.dt = dt;
  651. }
  652. void RigidShape::advanceTime(F32 dt)
  653. {
  654. Parent::advanceTime(dt);
  655. updateFroth(dt);
  656. // Update 3rd person camera offset. Camera update is done
  657. // here as it's a client side only animation.
  658. mCameraOffset -=
  659. (mCameraOffset * mDataBlock->cameraDecay +
  660. mRigid.linVelocity * mDataBlock->cameraLag) * dt;
  661. }
  662. //----------------------------------------------------------------------------
  663. bool RigidShape::onNewDataBlock(GameBaseData* dptr, bool reload)
  664. {
  665. mDataBlock = dynamic_cast<RigidShapeData*>(dptr);
  666. if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
  667. return false;
  668. // Update Rigid Info
  669. mRigid.mass = mDataBlock->mass;
  670. mRigid.oneOverMass = 1 / mRigid.mass;
  671. mRigid.friction = mDataBlock->body.friction;
  672. mRigid.restitution = mDataBlock->body.restitution;
  673. mRigid.setCenterOfMass(mDataBlock->massCenter);
  674. // Ignores massBox, just set sphere for now. Derived objects
  675. // can set what they want.
  676. mRigid.setObjectInertia();
  677. scriptOnNewDataBlock();
  678. return true;
  679. }
  680. //----------------------------------------------------------------------------
  681. void RigidShape::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot)
  682. {
  683. *min = mDataBlock->cameraMinDist;
  684. *max = mDataBlock->cameraMaxDist;
  685. off->set(0,0,mDataBlock->cameraOffset);
  686. rot->identity();
  687. }
  688. //----------------------------------------------------------------------------
  689. void RigidShape::getCameraTransform(F32* pos,MatrixF* mat)
  690. {
  691. // Returns camera to world space transform
  692. // Handles first person / third person camera position
  693. if (isServerObject() && mShapeInstance)
  694. mShapeInstance->animateNodeSubtrees(true);
  695. if (*pos == 0)
  696. {
  697. getRenderEyeTransform(mat);
  698. return;
  699. }
  700. // Get the shape's camera parameters.
  701. F32 min,max;
  702. MatrixF rot;
  703. Point3F offset;
  704. getCameraParameters(&min,&max,&offset,&rot);
  705. // Start with the current eye position
  706. MatrixF eye;
  707. getRenderEyeTransform(&eye);
  708. // Build a transform that points along the eye axis
  709. // but where the Z axis is always up.
  710. if (mDataBlock->cameraRoll)
  711. mat->mul(eye,rot);
  712. else
  713. {
  714. MatrixF cam(1);
  715. VectorF x,y,z(0,0,1);
  716. eye.getColumn(1, &y);
  717. mCross(y, z, &x);
  718. x.normalize();
  719. mCross(x, y, &z);
  720. z.normalize();
  721. cam.setColumn(0,x);
  722. cam.setColumn(1,y);
  723. cam.setColumn(2,z);
  724. mat->mul(cam,rot);
  725. }
  726. // Camera is positioned straight back along the eye's -Y axis.
  727. // A ray is cast to make sure the camera doesn't go through
  728. // anything solid.
  729. VectorF vp,vec;
  730. vp.x = vp.z = 0;
  731. vp.y = -(max - min) * *pos;
  732. eye.mulV(vp,&vec);
  733. // Use the camera node as the starting position if it exists.
  734. Point3F osp,sp;
  735. if (mDataBlock->cameraNode != -1)
  736. {
  737. mShapeInstance->mNodeTransforms[mDataBlock->cameraNode].getColumn(3,&osp);
  738. getRenderTransform().mulP(osp,&sp);
  739. }
  740. else
  741. eye.getColumn(3,&sp);
  742. // Make sure we don't hit ourself...
  743. disableCollision();
  744. if (isMounted())
  745. getObjectMount()->disableCollision();
  746. // Cast the ray into the container database to see if we're going
  747. // to hit anything.
  748. RayInfo collision;
  749. Point3F ep = sp + vec + offset + mCameraOffset;
  750. if (mContainer->castRay(sp, ep,
  751. ~(WaterObjectType | GameBaseObjectType | DefaultObjectType),
  752. &collision) == true)
  753. {
  754. // Shift the collision point back a little to try and
  755. // avoid clipping against the front camera plane.
  756. F32 t = collision.t - (-mDot(vec, collision.normal) / vec.len()) * 0.1;
  757. if (t > 0.0f)
  758. ep = sp + offset + mCameraOffset + (vec * t);
  759. else
  760. eye.getColumn(3,&ep);
  761. }
  762. mat->setColumn(3,ep);
  763. // Re-enable our collision.
  764. if (isMounted())
  765. getObjectMount()->enableCollision();
  766. enableCollision();
  767. // Apply Camera FX.
  768. mat->mul( gCamFXMgr.getTrans() );
  769. }
  770. //----------------------------------------------------------------------------
  771. void RigidShape::getVelocity(const Point3F& r, Point3F* v)
  772. {
  773. mRigid.getVelocity(r, v);
  774. }
  775. void RigidShape::applyImpulse(const Point3F &pos, const Point3F &impulse)
  776. {
  777. Point3F r;
  778. mRigid.getOriginVector(pos,&r);
  779. mRigid.applyImpulse(r, impulse);
  780. }
  781. //----------------------------------------------------------------------------
  782. void RigidShape::updateMove(const Move* move)
  783. {
  784. mDelta.move = *move;
  785. }
  786. //----------------------------------------------------------------------------
  787. void RigidShape::setPosition(const Point3F& pos,const QuatF& rot)
  788. {
  789. MatrixF mat;
  790. rot.setMatrix(&mat);
  791. mat.setColumn(3,pos);
  792. Parent::setTransform(mat);
  793. }
  794. void RigidShape::setRenderPosition(const Point3F& pos, const QuatF& rot)
  795. {
  796. MatrixF mat;
  797. rot.setMatrix(&mat);
  798. mat.setColumn(3,pos);
  799. Parent::setRenderTransform(mat);
  800. }
  801. void RigidShape::setTransform(const MatrixF& newMat)
  802. {
  803. mRigid.setTransform(newMat);
  804. Parent::setTransform(newMat);
  805. mRigid.atRest = false;
  806. mContacts.clear();
  807. }
  808. void RigidShape::forceClientTransform()
  809. {
  810. setMaskBits(ForceMoveMask);
  811. }
  812. //-----------------------------------------------------------------------------
  813. void RigidShape::disableCollision()
  814. {
  815. Parent::disableCollision();
  816. }
  817. void RigidShape::enableCollision()
  818. {
  819. Parent::enableCollision();
  820. }
  821. //----------------------------------------------------------------------------
  822. /** Update the physics
  823. */
  824. void RigidShape::updatePos(F32 dt)
  825. {
  826. Point3F origVelocity = mRigid.linVelocity;
  827. // Update internal forces acting on the body.
  828. mRigid.clearForces();
  829. updateForces(dt);
  830. // Update collision information based on our current pos.
  831. bool collided = false;
  832. if (!mRigid.atRest && !mDisableMove)
  833. {
  834. collided = updateCollision(dt);
  835. // Now that all the forces have been processed, lets
  836. // see if we're at rest. Basically, if the kinetic energy of
  837. // the shape is less than some percentage of the energy added
  838. // by gravity for a short period, we're considered at rest.
  839. // This should really be part of the rigid class...
  840. if (mCollisionList.getCount())
  841. {
  842. F32 k = mRigid.getKineticEnergy();
  843. F32 G = sRigidShapeGravity * dt;
  844. F32 Kg = 0.5 * mRigid.mass * G * G;
  845. if (k < sRestTol * Kg && ++restCount > sRestCount)
  846. mRigid.setAtRest();
  847. }
  848. else
  849. restCount = 0;
  850. }
  851. // Integrate forward
  852. if (!mRigid.atRest && !mDisableMove)
  853. mRigid.integrate(dt);
  854. // Deal with client and server scripting, sounds, etc.
  855. if (isServerObject())
  856. {
  857. // Check triggers and other objects that we normally don't
  858. // collide with. This function must be called before notifyCollision
  859. // as it will queue collision.
  860. checkTriggers();
  861. // Invoke the onCollision notify callback for all the objects
  862. // we've just hit.
  863. notifyCollision();
  864. // Server side impact script callback
  865. if (collided)
  866. {
  867. VectorF collVec = mRigid.linVelocity - origVelocity;
  868. F32 collSpeed = collVec.len();
  869. if (collSpeed > mDataBlock->minImpactSpeed)
  870. onImpact(collVec);
  871. }
  872. // Water script callbacks
  873. if (!inLiquid && mWaterCoverage != 0.0f)
  874. {
  875. onEnterLiquid_callback(getIdString(), mWaterCoverage, mLiquidType.c_str() );
  876. inLiquid = true;
  877. }
  878. else if (inLiquid && mWaterCoverage == 0.0f)
  879. {
  880. onLeaveLiquid_callback(getIdString(), mLiquidType.c_str() );
  881. inLiquid = false;
  882. }
  883. }
  884. else {
  885. // Play impact sounds on the client.
  886. if (collided) {
  887. F32 collSpeed = (mRigid.linVelocity - origVelocity).len();
  888. S32 impactSound = -1;
  889. if (collSpeed >= mDataBlock->hardImpactSpeed)
  890. impactSound = RigidShapeData::Body::HardImpactSound;
  891. else
  892. if (collSpeed >= mDataBlock->softImpactSpeed)
  893. impactSound = RigidShapeData::Body::SoftImpactSound;
  894. if (impactSound != -1 && mDataBlock->body.sound[impactSound] != NULL)
  895. SFX->playOnce(mDataBlock->body.sound[impactSound], &getTransform());
  896. }
  897. // Water volume sounds
  898. F32 vSpeed = getVelocity().len();
  899. if (!inLiquid && mWaterCoverage >= 0.8f) {
  900. if (vSpeed >= mDataBlock->hardSplashSoundVel)
  901. SFX->playOnce(mDataBlock->waterSound[RigidShapeData::ImpactHard], &getTransform());
  902. else
  903. if (vSpeed >= mDataBlock->medSplashSoundVel)
  904. SFX->playOnce(mDataBlock->waterSound[RigidShapeData::ImpactMedium], &getTransform());
  905. else
  906. if (vSpeed >= mDataBlock->softSplashSoundVel)
  907. SFX->playOnce(mDataBlock->waterSound[RigidShapeData::ImpactSoft], &getTransform());
  908. inLiquid = true;
  909. }
  910. else
  911. if(inLiquid && mWaterCoverage < 0.8f) {
  912. if (vSpeed >= mDataBlock->exitSplashSoundVel)
  913. SFX->playOnce(mDataBlock->waterSound[RigidShapeData::ExitWater], &getTransform());
  914. inLiquid = false;
  915. }
  916. }
  917. }
  918. //----------------------------------------------------------------------------
  919. void RigidShape::updateForces(F32 /*dt*/)
  920. {
  921. if (mDisableMove) return;
  922. Point3F gravForce(0, 0, sRigidShapeGravity * mRigid.mass * mGravityMod);
  923. MatrixF currTransform;
  924. mRigid.getTransform(&currTransform);
  925. Point3F torque(0, 0, 0);
  926. Point3F force(0, 0, 0);
  927. Point3F vel = mRigid.linVelocity;
  928. // Gravity
  929. force += gravForce;
  930. // Apply drag
  931. Point3F vDrag = mRigid.linVelocity;
  932. vDrag.convolve(Point3F(1, 1, mDataBlock->vertFactor));
  933. force -= vDrag * mDataBlock->dragForce;
  934. // Add in physical zone force
  935. force += mAppliedForce;
  936. // Container buoyancy & drag
  937. force += Point3F(0, 0,-mBuoyancy * sRigidShapeGravity * mRigid.mass * mGravityMod);
  938. force -= mRigid.linVelocity * mDrag;
  939. torque -= mRigid.angMomentum * mDrag;
  940. mRigid.force = force;
  941. mRigid.torque = torque;
  942. }
  943. //-----------------------------------------------------------------------------
  944. /** Update collision information
  945. Update the convex state and check for collisions. If the object is in
  946. collision, impact and contact forces are generated.
  947. */
  948. bool RigidShape::updateCollision(F32 dt)
  949. {
  950. // Update collision information
  951. MatrixF mat,cmat;
  952. mConvex.transform = &mat;
  953. mRigid.getTransform(&mat);
  954. cmat = mConvex.getTransform();
  955. mCollisionList.clear();
  956. CollisionState *state = mConvex.findClosestState(cmat, getScale(), mDataBlock->collisionTol);
  957. if (state && state->dist <= mDataBlock->collisionTol)
  958. {
  959. //resolveDisplacement(ns,state,dt);
  960. mConvex.getCollisionInfo(cmat, getScale(), &mCollisionList, mDataBlock->collisionTol);
  961. }
  962. // Resolve collisions
  963. bool collided = resolveCollision(mRigid,mCollisionList);
  964. resolveContacts(mRigid,mCollisionList,dt);
  965. return collided;
  966. }
  967. //----------------------------------------------------------------------------
  968. /** Resolve collision impacts
  969. Handle collision impacts, as opposed to contacts. Impulses are calculated based
  970. on standard collision resolution formulas.
  971. */
  972. bool RigidShape::resolveCollision(Rigid& ns,CollisionList& cList)
  973. {
  974. // Apply impulses to resolve collision
  975. bool colliding, collided = false;
  976. do
  977. {
  978. colliding = false;
  979. for (S32 i = 0; i < cList.getCount(); i++)
  980. {
  981. Collision& c = cList[i];
  982. if (c.distance < mDataBlock->collisionTol)
  983. {
  984. // Velocity into surface
  985. Point3F v,r;
  986. ns.getOriginVector(c.point,&r);
  987. ns.getVelocity(r,&v);
  988. F32 vn = mDot(v,c.normal);
  989. // Only interested in velocities greater than sContactTol,
  990. // velocities less than that will be dealt with as contacts
  991. // "constraints".
  992. if (vn < -mDataBlock->contactTol)
  993. {
  994. // Apply impulses to the rigid body to keep it from
  995. // penetrating the surface.
  996. ns.resolveCollision(cList[i].point,
  997. cList[i].normal);
  998. colliding = collided = true;
  999. // Keep track of objects we collide with
  1000. if (!isGhost() && c.object->getTypeMask() & ShapeBaseObjectType)
  1001. {
  1002. ShapeBase* col = static_cast<ShapeBase*>(c.object);
  1003. queueCollision(col,v - col->getVelocity());
  1004. }
  1005. }
  1006. }
  1007. }
  1008. } while (colliding);
  1009. return collided;
  1010. }
  1011. //----------------------------------------------------------------------------
  1012. /** Resolve contact forces
  1013. Resolve contact forces using the "penalty" method. Forces are generated based
  1014. on the depth of penetration and the moment of inertia at the point of contact.
  1015. */
  1016. bool RigidShape::resolveContacts(Rigid& ns,CollisionList& cList,F32 dt)
  1017. {
  1018. // Use spring forces to manage contact constraints.
  1019. bool collided = false;
  1020. Point3F t,p(0,0,0),l(0,0,0);
  1021. for (S32 i = 0; i < cList.getCount(); i++)
  1022. {
  1023. Collision& c = cList[i];
  1024. if (c.distance < mDataBlock->collisionTol)
  1025. {
  1026. // Velocity into the surface
  1027. Point3F v,r;
  1028. ns.getOriginVector(c.point,&r);
  1029. ns.getVelocity(r,&v);
  1030. F32 vn = mDot(v,c.normal);
  1031. // Only interested in velocities less than mDataBlock->contactTol,
  1032. // velocities greater than that are dealt with as collisions.
  1033. if (mFabs(vn) < mDataBlock->contactTol)
  1034. {
  1035. collided = true;
  1036. // Penetration force. This is actually a spring which
  1037. // will seperate the body from the collision surface.
  1038. F32 zi = 2 * mFabs(mRigid.getZeroImpulse(r,c.normal));
  1039. F32 s = (mDataBlock->collisionTol - c.distance) * zi - ((vn / mDataBlock->contactTol) * zi);
  1040. Point3F f = c.normal * s;
  1041. // Friction impulse, calculated as a function of the
  1042. // amount of force it would take to stop the motion
  1043. // perpendicular to the normal.
  1044. Point3F uv = v - (c.normal * vn);
  1045. F32 ul = uv.len();
  1046. if (s > 0 && ul)
  1047. {
  1048. uv /= -ul;
  1049. F32 u = ul * ns.getZeroImpulse(r,uv);
  1050. s *= mRigid.friction;
  1051. if (u > s)
  1052. u = s;
  1053. f += uv * u;
  1054. }
  1055. // Accumulate forces
  1056. p += f;
  1057. mCross(r,f,&t);
  1058. l += t;
  1059. }
  1060. }
  1061. }
  1062. // Contact constraint forces act over time...
  1063. ns.linMomentum += p * dt;
  1064. ns.angMomentum += l * dt;
  1065. ns.updateVelocity();
  1066. return true;
  1067. }
  1068. //----------------------------------------------------------------------------
  1069. bool RigidShape::resolveDisplacement(Rigid& ns,CollisionState *state, F32 dt)
  1070. {
  1071. SceneObject* obj = (state->a->getObject() == this)?
  1072. state->b->getObject(): state->a->getObject();
  1073. if (obj->isDisplacable() && ((obj->getTypeMask() & ShapeBaseObjectType) != 0))
  1074. {
  1075. // Try to displace the object by the amount we're trying to move
  1076. Point3F objNewMom = ns.linVelocity * obj->getMass() * 1.1f;
  1077. Point3F objOldMom = obj->getMomentum();
  1078. Point3F objNewVel = objNewMom / obj->getMass();
  1079. Point3F myCenter;
  1080. Point3F theirCenter;
  1081. getWorldBox().getCenter(&myCenter);
  1082. obj->getWorldBox().getCenter(&theirCenter);
  1083. if (mDot(myCenter - theirCenter, objNewMom) >= 0.0f || objNewVel.len() < 0.01)
  1084. {
  1085. objNewMom = (theirCenter - myCenter);
  1086. objNewMom.normalize();
  1087. objNewMom *= 1.0f * obj->getMass();
  1088. objNewVel = objNewMom / obj->getMass();
  1089. }
  1090. obj->setMomentum(objNewMom);
  1091. if (obj->displaceObject(objNewVel * 1.1f * dt) == true)
  1092. {
  1093. // Queue collision and change in velocity
  1094. VectorF dv = (objOldMom - objNewMom) / obj->getMass();
  1095. queueCollision(static_cast<ShapeBase*>(obj), dv);
  1096. return true;
  1097. }
  1098. }
  1099. return false;
  1100. }
  1101. //----------------------------------------------------------------------------
  1102. void RigidShape::updateWorkingCollisionSet(const U32 mask)
  1103. {
  1104. Box3F convexBox = mConvex.getBoundingBox(getTransform(), getScale());
  1105. F32 len = (mRigid.linVelocity.len() + 50) * TickSec;
  1106. F32 l = (len * 1.1) + 0.1; // fudge factor
  1107. convexBox.minExtents -= Point3F(l, l, l);
  1108. convexBox.maxExtents += Point3F(l, l, l);
  1109. disableCollision();
  1110. mConvex.updateWorkingList(convexBox, mask);
  1111. enableCollision();
  1112. }
  1113. //----------------------------------------------------------------------------
  1114. /** Check collisions with trigger and items
  1115. Perform a container search using the current bounding box
  1116. of the main body, wheels are not included. This method should
  1117. only be called on the server.
  1118. */
  1119. void RigidShape::checkTriggers()
  1120. {
  1121. Box3F bbox = mConvex.getBoundingBox(getTransform(), getScale());
  1122. gServerContainer.findObjects(bbox,sTriggerMask,findCallback,this);
  1123. }
  1124. /** The callback used in by the checkTriggers() method.
  1125. The checkTriggers method uses a container search which will
  1126. invoke this callback on each obj that matches.
  1127. */
  1128. void RigidShape::findCallback(SceneObject* obj,void *key)
  1129. {
  1130. RigidShape* shape = reinterpret_cast<RigidShape*>(key);
  1131. U32 objectMask = obj->getTypeMask();
  1132. // Check: triggers, corpses and items, basically the same things
  1133. // that the player class checks for
  1134. if (objectMask & TriggerObjectType) {
  1135. Trigger* pTrigger = static_cast<Trigger*>(obj);
  1136. pTrigger->potentialEnterObject(shape);
  1137. }
  1138. else if (objectMask & CorpseObjectType) {
  1139. ShapeBase* col = static_cast<ShapeBase*>(obj);
  1140. shape->queueCollision(col,shape->getVelocity() - col->getVelocity());
  1141. }
  1142. else if (objectMask & ItemObjectType) {
  1143. Item* item = static_cast<Item*>(obj);
  1144. if (shape != item->getCollisionObject())
  1145. shape->queueCollision(item,shape->getVelocity() - item->getVelocity());
  1146. }
  1147. }
  1148. //----------------------------------------------------------------------------
  1149. void RigidShape::writePacketData(GameConnection *connection, BitStream *stream)
  1150. {
  1151. Parent::writePacketData(connection, stream);
  1152. mathWrite(*stream, mRigid.linPosition);
  1153. mathWrite(*stream, mRigid.angPosition);
  1154. mathWrite(*stream, mRigid.linMomentum);
  1155. mathWrite(*stream, mRigid.angMomentum);
  1156. stream->writeFlag(mRigid.atRest);
  1157. stream->writeFlag(mContacts.getCount() == 0);
  1158. stream->writeFlag(mDisableMove);
  1159. stream->setCompressionPoint(mRigid.linPosition);
  1160. }
  1161. void RigidShape::readPacketData(GameConnection *connection, BitStream *stream)
  1162. {
  1163. Parent::readPacketData(connection, stream);
  1164. mathRead(*stream, &mRigid.linPosition);
  1165. mathRead(*stream, &mRigid.angPosition);
  1166. mathRead(*stream, &mRigid.linMomentum);
  1167. mathRead(*stream, &mRigid.angMomentum);
  1168. mRigid.atRest = stream->readFlag();
  1169. if (stream->readFlag())
  1170. mContacts.clear();
  1171. mRigid.updateInertialTensor();
  1172. mRigid.updateVelocity();
  1173. mDisableMove = stream->readFlag();
  1174. stream->setCompressionPoint(mRigid.linPosition);
  1175. }
  1176. //----------------------------------------------------------------------------
  1177. U32 RigidShape::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  1178. {
  1179. U32 retMask = Parent::packUpdate(con, mask, stream);
  1180. // The rest of the data is part of the control object packet update.
  1181. // If we're controlled by this client, we don't need to send it.
  1182. if (stream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask)))
  1183. return retMask;
  1184. mDelta.move.pack(stream);
  1185. if (stream->writeFlag(mask & PositionMask))
  1186. {
  1187. stream->writeFlag(mask & ForceMoveMask);
  1188. stream->writeCompressedPoint(mRigid.linPosition);
  1189. mathWrite(*stream, mRigid.angPosition);
  1190. mathWrite(*stream, mRigid.linMomentum);
  1191. mathWrite(*stream, mRigid.angMomentum);
  1192. stream->writeFlag(mRigid.atRest);
  1193. }
  1194. if(stream->writeFlag(mask & FreezeMask))
  1195. stream->writeFlag(mDisableMove);
  1196. return retMask;
  1197. }
  1198. void RigidShape::unpackUpdate(NetConnection *con, BitStream *stream)
  1199. {
  1200. Parent::unpackUpdate(con,stream);
  1201. if (stream->readFlag())
  1202. return;
  1203. mDelta.move.unpack(stream);
  1204. if (stream->readFlag())
  1205. {
  1206. // Check if we need to jump to the given transform
  1207. // rather than interpolate to it.
  1208. bool forceUpdate = stream->readFlag();
  1209. mPredictionCount = sMaxPredictionTicks;
  1210. F32 speed = mRigid.linVelocity.len();
  1211. mDelta.warpRot[0] = mRigid.angPosition;
  1212. // Read in new position and momentum values
  1213. stream->readCompressedPoint(&mRigid.linPosition);
  1214. mathRead(*stream, &mRigid.angPosition);
  1215. mathRead(*stream, &mRigid.linMomentum);
  1216. mathRead(*stream, &mRigid.angMomentum);
  1217. mRigid.atRest = stream->readFlag();
  1218. mRigid.updateVelocity();
  1219. if (!forceUpdate && isProperlyAdded())
  1220. {
  1221. // Determine number of ticks to warp based on the average
  1222. // of the client and server velocities.
  1223. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt;
  1224. mDelta.warpOffset = mRigid.linPosition - cp;
  1225. // Calc the distance covered in one tick as the average of
  1226. // the old speed and the new speed from the server.
  1227. F32 dt,as = (speed + mRigid.linVelocity.len()) * 0.5 * TickSec;
  1228. // Cal how many ticks it will take to cover the warp offset.
  1229. // If it's less than what's left in the current tick, we'll just
  1230. // warp in the remaining time.
  1231. if (!as || (dt = mDelta.warpOffset.len() / as) > sMaxWarpTicks)
  1232. dt = mDelta.dt + sMaxWarpTicks;
  1233. else
  1234. dt = (dt <= mDelta.dt)? mDelta.dt : mCeil(dt - mDelta.dt) + mDelta.dt;
  1235. // Adjust current frame interpolation
  1236. if (mDelta.dt)
  1237. {
  1238. mDelta.pos = cp + (mDelta.warpOffset * (mDelta.dt / dt));
  1239. mDelta.posVec = (cp - mDelta.pos) / mDelta.dt;
  1240. QuatF cr;
  1241. cr.interpolate(mDelta.rot[1],mDelta.rot[0],mDelta.dt);
  1242. mDelta.rot[1].interpolate(cr,mRigid.angPosition,mDelta.dt / dt);
  1243. mDelta.rot[0].extrapolate(mDelta.rot[1],cr,mDelta.dt);
  1244. }
  1245. // Calculated multi-tick warp
  1246. mDelta.warpCount = 0;
  1247. mDelta.warpTicks = (S32)(mFloor(dt));
  1248. if (mDelta.warpTicks)
  1249. {
  1250. mDelta.warpOffset = mRigid.linPosition - mDelta.pos;
  1251. mDelta.warpOffset /= mDelta.warpTicks;
  1252. mDelta.warpRot[0] = mDelta.rot[1];
  1253. mDelta.warpRot[1] = mRigid.angPosition;
  1254. }
  1255. }
  1256. else
  1257. {
  1258. // Set the shape to the server position
  1259. mDelta.dt = 0;
  1260. mDelta.pos = mRigid.linPosition;
  1261. mDelta.posVec.set(0,0,0);
  1262. mDelta.rot[1] = mDelta.rot[0] = mRigid.angPosition;
  1263. mDelta.warpCount = mDelta.warpTicks = 0;
  1264. setPosition(mRigid.linPosition, mRigid.angPosition);
  1265. }
  1266. }
  1267. if(stream->readFlag())
  1268. mDisableMove = stream->readFlag();
  1269. }
  1270. //----------------------------------------------------------------------------
  1271. void RigidShape::initPersistFields()
  1272. {
  1273. Parent::initPersistFields();
  1274. }
  1275. //----------------------------------------------------------------------------
  1276. void RigidShape::updateLiftoffDust( F32 dt )
  1277. {
  1278. Point3F offset( 0.0, 0.0, mDataBlock->dustHeight );
  1279. emitDust( mDustEmitterList[ 0 ], mDataBlock->triggerDustHeight, offset,
  1280. ( U32 )( dt * 1000 ) );
  1281. }
  1282. //--------------------------------------------------------------------------
  1283. void RigidShape::updateFroth( F32 dt )
  1284. {
  1285. // update bubbles
  1286. Point3F moveDir = getVelocity();
  1287. Point3F contactPoint;
  1288. F32 speed = moveDir.len();
  1289. if( speed < mDataBlock->splashVelEpsilon ) speed = 0.0;
  1290. U32 emitRate = (U32)(speed * mDataBlock->splashFreqMod * dt);
  1291. U32 i;
  1292. for( i=0; i<RigidShapeData::VC_NUM_SPLASH_EMITTERS; i++ )
  1293. {
  1294. if( mSplashEmitterList[i] )
  1295. {
  1296. mSplashEmitterList[i]->emitParticles( contactPoint, contactPoint, Point3F( 0.0, 0.0, 1.0 ),
  1297. moveDir, emitRate );
  1298. }
  1299. }
  1300. }
  1301. //--------------------------------------------------------------------------
  1302. // Returns true if shape is intersecting a water surface (roughly)
  1303. //--------------------------------------------------------------------------
  1304. bool RigidShape::collidingWithWater( Point3F &waterHeight )
  1305. {
  1306. Point3F curPos = getPosition();
  1307. F32 height = mFabs( mObjBox.maxExtents.z - mObjBox.minExtents.z );
  1308. RayInfo rInfo;
  1309. if( gClientContainer.castRay( curPos + Point3F(0.0, 0.0, height), curPos, WaterObjectType, &rInfo) )
  1310. {
  1311. waterHeight = rInfo.point;
  1312. return true;
  1313. }
  1314. return false;
  1315. }
  1316. void RigidShape::setEnergyLevel(F32 energy)
  1317. {
  1318. Parent::setEnergyLevel(energy);
  1319. setMaskBits(EnergyMask);
  1320. }
  1321. void RigidShape::prepBatchRender( SceneRenderState *state, S32 mountedImageIndex )
  1322. {
  1323. Parent::prepBatchRender( state, mountedImageIndex );
  1324. if ( !gShowBoundingBox )
  1325. return;
  1326. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1327. ri->renderDelegate.bind( this, &RigidShape::_renderMassAndContacts );
  1328. ri->type = RenderPassManager::RIT_Editor;
  1329. state->getRenderPass()->addInst( ri );
  1330. }
  1331. void RigidShape::_renderMassAndContacts( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  1332. {
  1333. // Box for the center of Mass
  1334. GFXStateBlockDesc desc;
  1335. desc.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1336. desc.setZReadWrite(false);
  1337. desc.fillMode = GFXFillWireframe;
  1338. GFX->getDrawUtil()->drawCube( desc, Point3F(0.1f,0.1f,0.1f), mDataBlock->massCenter, ColorI(255, 255, 255), &mRenderObjToWorld );
  1339. // Collision points...
  1340. for (S32 i = 0; i < mCollisionList.getCount(); i++)
  1341. {
  1342. const Collision& collision = mCollisionList[i];
  1343. GFX->getDrawUtil()->drawCube( desc, Point3F(0.05f,0.05f,0.05f), collision.point, ColorI(0, 0, 255) );
  1344. }
  1345. // Render the normals as one big batch...
  1346. PrimBuild::begin(GFXLineList, mCollisionList.getCount() * 2);
  1347. for (S32 i = 0; i < mCollisionList.getCount(); i++)
  1348. {
  1349. const Collision& collision = mCollisionList[i];
  1350. PrimBuild::color3f(1, 1, 1);
  1351. PrimBuild::vertex3fv(collision.point);
  1352. PrimBuild::vertex3fv(collision.point + collision.normal * 0.05f);
  1353. }
  1354. PrimBuild::end();
  1355. // Build and render the collision polylist which is returned
  1356. // in the server's world space.
  1357. ClippedPolyList polyList;
  1358. polyList.mPlaneList.setSize(6);
  1359. polyList.mPlaneList[0].set(getWorldBox().minExtents,VectorF(-1,0,0));
  1360. polyList.mPlaneList[1].set(getWorldBox().minExtents,VectorF(0,-1,0));
  1361. polyList.mPlaneList[2].set(getWorldBox().minExtents,VectorF(0,0,-1));
  1362. polyList.mPlaneList[3].set(getWorldBox().maxExtents,VectorF(1,0,0));
  1363. polyList.mPlaneList[4].set(getWorldBox().maxExtents,VectorF(0,1,0));
  1364. polyList.mPlaneList[5].set(getWorldBox().maxExtents,VectorF(0,0,1));
  1365. Box3F dummyBox;
  1366. SphereF dummySphere;
  1367. buildPolyList(PLC_Collision, &polyList, dummyBox, dummySphere);
  1368. //polyList.render();
  1369. }
  1370. void RigidShape::reset()
  1371. {
  1372. mRigid.clearForces();
  1373. mRigid.setAtRest();
  1374. }
  1375. void RigidShape::freezeSim(bool frozen)
  1376. {
  1377. mDisableMove = frozen;
  1378. setMaskBits(FreezeMask);
  1379. }
  1380. DefineEngineMethod( RigidShape, reset, void, (),,
  1381. "@brief Clears physic forces from the shape and sets it at rest.\n\n"
  1382. "@tsexample\n"
  1383. "// Inform the RigidShape object to reset.\n"
  1384. "%thisRigidShape.reset();\n"
  1385. "@endtsexample\n\n"
  1386. "@see ShapeBaseData")
  1387. {
  1388. object->reset();
  1389. }
  1390. DefineEngineMethod( RigidShape, freezeSim, void, (bool isFrozen),,
  1391. "@brief Enables or disables the physics simulation on the RigidShape object.\n\n"
  1392. "@param isFrozen Boolean frozen state to set the object.\n"
  1393. "@tsexample\n"
  1394. "// Define the frozen state.\n"
  1395. "%isFrozen = \"true\";\n\n"
  1396. "// Inform the object of the defined frozen state\n"
  1397. "%thisRigidShape.freezeSim(%isFrozen);\n"
  1398. "@endtsexample\n\n"
  1399. "@see ShapeBaseData")
  1400. {
  1401. object->freezeSim(isFrozen);
  1402. }
  1403. DefineEngineMethod( RigidShape, forceClientTransform, void, (),,
  1404. "@brief Forces the client to jump to the RigidShape's transform rather then warp to it.\n\n")
  1405. {
  1406. if(object->isServerObject())
  1407. {
  1408. object->forceClientTransform();
  1409. }
  1410. }