rigidShape.cpp 55 KB

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