rigidShape.cpp 61 KB

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