physicsShape.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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/physics/physicsShape.h"
  24. #include "console/consoleTypes.h"
  25. #include "core/stream/bitStream.h"
  26. #include "core/resourceManager.h"
  27. #include "math/mathIO.h"
  28. #include "T3D/physics/physicsPlugin.h"
  29. #include "T3D/physics/physicsBody.h"
  30. #include "T3D/physics/physicsWorld.h"
  31. #include "T3D/physics/physicsCollision.h"
  32. #include "T3D/gameBase/gameConnection.h"
  33. #include "collision/concretePolyList.h"
  34. #include "ts/tsShapeInstance.h"
  35. #include "scene/sceneRenderState.h"
  36. #include "gfx/gfxTransformSaver.h"
  37. #include "T3D/physics/physicsDebris.h"
  38. #include "T3D/fx/explosion.h"
  39. #include "T3D/containerQuery.h"
  40. #include "lighting/lightQuery.h"
  41. #include "console/engineAPI.h"
  42. using namespace Torque;
  43. bool PhysicsShape::smNoCorrections = false;
  44. bool PhysicsShape::smNoSmoothing = false;
  45. ImplementEnumType( PhysicsSimType,
  46. "How to handle the physics simulation with the client's and server.\n"
  47. "@ingroup Physics\n\n")
  48. { PhysicsShapeData::SimType_ClientOnly, "ClientOnly", "Only handle physics on the client.\n" },
  49. { PhysicsShapeData::SimType_ServerOnly, "ServerOnly", "Only handle physics on the server.\n" },
  50. { PhysicsShapeData::SimType_ClientServer, "ClientServer", "Handle physics on both the client and server.\n" }
  51. EndImplementEnumType;
  52. IMPLEMENT_CO_DATABLOCK_V1( PhysicsShapeData );
  53. ConsoleDocClass( PhysicsShapeData,
  54. "@brief Defines the properties of a PhysicsShape.\n\n"
  55. "@see PhysicsShape.\n"
  56. "@ingroup Physics"
  57. );
  58. PhysicsShapeData::PhysicsShapeData()
  59. : mass( 1.0f ),
  60. dynamicFriction( 0.0f ),
  61. staticFriction( 0.0f ),
  62. restitution( 0.0f ),
  63. linearDamping( 0.0f ),
  64. angularDamping( 0.0f ),
  65. linearSleepThreshold( 1.0f ),
  66. angularSleepThreshold( 1.0f ),
  67. waterDampingScale( 1.0f ),
  68. buoyancyDensity( 0.0f ),
  69. simType( SimType_ClientServer )
  70. {
  71. INIT_ASSET(Shape);
  72. }
  73. PhysicsShapeData::~PhysicsShapeData()
  74. {
  75. }
  76. void PhysicsShapeData::initPersistFields()
  77. {
  78. Parent::initPersistFields();
  79. addGroup("Media");
  80. INITPERSISTFIELD_SHAPEASSET(Shape, PhysicsShapeData, "@brief Shape asset to be used with this physics object.\n\n"
  81. "Compatable with Live-Asset Reloading. ")
  82. addField( "debris", TYPEID< SimObjectRef<PhysicsDebrisData> >(), Offset( debris, PhysicsShapeData ),
  83. "@brief Name of a PhysicsDebrisData to spawn when this shape is destroyed (optional)." );
  84. addField( "explosion", TYPEID< SimObjectRef<ExplosionData> >(), Offset( explosion, PhysicsShapeData ),
  85. "@brief Name of an ExplosionData to spawn when this shape is destroyed (optional)." );
  86. addField( "destroyedShape", TYPEID< SimObjectRef<PhysicsShapeData> >(), Offset( destroyedShape, PhysicsShapeData ),
  87. "@brief Name of a PhysicsShapeData to spawn when this shape is destroyed (optional)." );
  88. endGroup("Media");
  89. addGroup( "Physics" );
  90. addField( "mass", TypeF32, Offset( mass, PhysicsShapeData ),
  91. "@brief Value representing the mass of the shape.\n\n"
  92. "A shape's mass influences the magnitude of any force exerted on it. "
  93. "For example, a PhysicsShape with a large mass requires a much larger force to move than "
  94. "the same shape with a smaller mass.\n"
  95. "@note A mass of zero will create a kinematic shape while anything greater will create a dynamic shape.");
  96. addField( "friction", TypeF32, Offset( dynamicFriction, PhysicsShapeData ),
  97. "@brief Coefficient of kinetic %friction to be applied to the shape.\n\n"
  98. "Kinetic %friction reduces the velocity of a moving object while it is in contact with a surface. "
  99. "A higher coefficient will result in a larger velocity reduction. "
  100. "A shape's friction should be lower than it's staticFriction, but larger than 0.\n\n"
  101. "@note This value is only applied while an object is in motion. For an object starting at rest, see PhysicsShape::staticFriction");
  102. addField( "staticFriction", TypeF32, Offset( staticFriction, PhysicsShapeData ),
  103. "@brief Coefficient of static %friction to be applied to the shape.\n\n"
  104. "Static %friction determines the force needed to start moving an at-rest object in contact with a surface. "
  105. "If the force applied onto shape cannot overcome the force of static %friction, the shape will remain at rest. "
  106. "A larger coefficient will require a larger force to start motion. "
  107. "This value should be larger than zero and the physicsShape's friction.\n\n"
  108. "@note This value is only applied while an object is at rest. For an object in motion, see PhysicsShape::friction");
  109. addField( "restitution", TypeF32, Offset( restitution, PhysicsShapeData ),
  110. "@brief Coeffecient of a bounce applied to the shape in response to a collision.\n\n"
  111. "Restitution is a ratio of a shape's velocity before and after a collision. "
  112. "A value of 0 will zero out a shape's post-collision velocity, making it stop on contact. "
  113. "Larger values will remove less velocity after a collision, making it \'bounce\' with a greater force. "
  114. "Normal %restitution values range between 0 and 1.0."
  115. "@note Values near or equaling 1.0 are likely to cause undesirable results in the physics simulation."
  116. " Because of this it is reccomended to avoid values close to 1.0");
  117. addField( "linearDamping", TypeF32, Offset( linearDamping, PhysicsShapeData ),
  118. "@brief Value that reduces an object's linear velocity over time.\n\n"
  119. "Larger values will cause velocity to decay quicker.\n\n" );
  120. addField( "angularDamping", TypeF32, Offset( angularDamping, PhysicsShapeData ),
  121. "@brief Value that reduces an object's rotational velocity over time.\n\n"
  122. "Larger values will cause velocity to decay quicker.\n\n" );
  123. addField( "linearSleepThreshold", TypeF32, Offset( linearSleepThreshold, PhysicsShapeData ),
  124. "@brief Minimum linear velocity before the shape can be put to sleep.\n\n"
  125. "This should be a positive value. Shapes put to sleep will not be simulated in order to save system resources.\n\n"
  126. "@note The shape must be dynamic.");
  127. addField( "angularSleepThreshold", TypeF32, Offset( angularSleepThreshold, PhysicsShapeData ),
  128. "@brief Minimum rotational velocity before the shape can be put to sleep.\n\n"
  129. "This should be a positive value. Shapes put to sleep will not be simulated in order to save system resources.\n\n"
  130. "@note The shape must be dynamic.");
  131. addField( "waterDampingScale", TypeF32, Offset( waterDampingScale, PhysicsShapeData ),
  132. "@brief Scale to apply to linear and angular dampening while underwater.\n\n "
  133. "Used with the waterViscosity of the "
  134. "@see angularDamping linearDamping" );
  135. addField( "buoyancyDensity", TypeF32, Offset( buoyancyDensity, PhysicsShapeData ),
  136. "@brief The density of the shape for calculating buoyant forces.\n\n"
  137. "The result of the calculated buoyancy is relative to the density of the WaterObject the PhysicsShape is within.\n\n"
  138. "@see WaterObject::density");
  139. endGroup( "Physics" );
  140. addGroup( "Networking" );
  141. addField( "simType", TYPEID< PhysicsShapeData::SimType >(), Offset( simType, PhysicsShapeData ),
  142. "@brief Controls whether this shape is simulated on the server, client, or both physics simulations.\n\n" );
  143. endGroup( "Networking" );
  144. }
  145. void PhysicsShapeData::packData( BitStream *stream )
  146. {
  147. Parent::packData( stream );
  148. PACKDATA_ASSET(Shape);
  149. stream->write( mass );
  150. stream->write( dynamicFriction );
  151. stream->write( staticFriction );
  152. stream->write( restitution );
  153. stream->write( linearDamping );
  154. stream->write( angularDamping );
  155. stream->write( linearSleepThreshold );
  156. stream->write( angularSleepThreshold );
  157. stream->write( waterDampingScale );
  158. stream->write( buoyancyDensity );
  159. stream->writeInt( simType, SimType_Bits );
  160. stream->writeRangedU32( debris ? debris->getId() : 0, 0, DataBlockObjectIdLast );
  161. stream->writeRangedU32( explosion ? explosion->getId() : 0, 0, DataBlockObjectIdLast );
  162. stream->writeRangedU32( destroyedShape ? destroyedShape->getId() : 0, 0, DataBlockObjectIdLast );
  163. }
  164. void PhysicsShapeData::unpackData( BitStream *stream )
  165. {
  166. Parent::unpackData(stream);
  167. UNPACKDATA_ASSET(Shape);
  168. stream->read( &mass );
  169. stream->read( &dynamicFriction );
  170. stream->read( &staticFriction );
  171. stream->read( &restitution );
  172. stream->read( &linearDamping );
  173. stream->read( &angularDamping );
  174. stream->read( &linearSleepThreshold );
  175. stream->read( &angularSleepThreshold );
  176. stream->read( &waterDampingScale );
  177. stream->read( &buoyancyDensity );
  178. simType = (SimType)stream->readInt( SimType_Bits );
  179. debris = stream->readRangedU32( 0, DataBlockObjectIdLast );
  180. explosion = stream->readRangedU32( 0, DataBlockObjectIdLast );
  181. destroyedShape = stream->readRangedU32( 0, DataBlockObjectIdLast );
  182. }
  183. bool PhysicsShapeData::onAdd()
  184. {
  185. if ( !Parent::onAdd() )
  186. return false;
  187. ResourceManager::get().getChangedSignal().notify( this, &PhysicsShapeData::_onResourceChanged );
  188. return true;
  189. }
  190. void PhysicsShapeData::onRemove()
  191. {
  192. ResourceManager::get().getChangedSignal().remove( this, &PhysicsShapeData::_onResourceChanged );
  193. Parent::onRemove();
  194. }
  195. void PhysicsShapeData::_onResourceChanged( const Torque::Path &path )
  196. {
  197. if (mShapeAsset.isNull())
  198. return;
  199. if ( path != Path(mShapeAsset->getShapeFilePath()) )
  200. return;
  201. _setShape(getShape());
  202. // Reload the changed shape.
  203. PhysicsCollisionRef reloadcolShape;
  204. if ( !mShape )
  205. {
  206. Con::warnf( ConsoleLogEntry::General, "PhysicsShapeData::_onResourceChanged: Could not reload %s.", path.getFileName().c_str() );
  207. return;
  208. }
  209. // Reload the collision shape.
  210. reloadcolShape = mShape->buildColShape( false, Point3F::One );
  211. if ( bool(reloadcolShape))
  212. colShape = reloadcolShape;
  213. mReloadSignal.trigger();
  214. }
  215. bool PhysicsShapeData::preload( bool server, String &errorBuffer )
  216. {
  217. if ( !Parent::preload( server, errorBuffer ) )
  218. return false;
  219. // If we don't have a physics plugin active then
  220. // we have to fail completely.
  221. if ( !PHYSICSMGR )
  222. {
  223. errorBuffer = "PhysicsShapeData::preload - No physics plugin is active!";
  224. return false;
  225. }
  226. bool shapeError = false;
  227. if (mShapeAsset.notNull())
  228. {
  229. if (bool(mShape) == false)
  230. {
  231. errorBuffer = String::ToString("PhysicsShapeData: Couldn't load shape \"%s\"", mShapeAssetId);
  232. return false;
  233. }
  234. if (!server && !mShape->preloadMaterialList(mShape.getPath()) && NetConnection::filesWereDownloaded())
  235. shapeError = true;
  236. }
  237. // Prepare the shared physics collision shape.
  238. if ( !colShape && mShape)
  239. {
  240. colShape = mShape->buildColShape( false, Point3F::One );
  241. // If we got here and didn't get a collision shape then
  242. // we need to fail... can't have a shape without collision.
  243. if ( !colShape )
  244. {
  245. //no collision so we create a simple box collision shape from the shapes bounds and alert the user
  246. Con::warnf( "PhysicsShapeData::preload - No collision found for shape '%s', auto-creating one", mShapeAssetId);
  247. Point3F halfWidth = mShape->mBounds.getExtents() * 0.5f;
  248. colShape = PHYSICSMGR->createCollision();
  249. MatrixF centerXfm(true);
  250. centerXfm.setPosition(mShape->mBounds.getCenter());
  251. colShape->addBox(halfWidth, centerXfm);
  252. return true;
  253. }
  254. }
  255. // My convex demcomposion test
  256. /*
  257. // Get the verts and triangles for the first visible detail.
  258. ConcretePolyList polyList;
  259. polyList.setTransform( &MatrixF::Identity, Point3F::One );
  260. TSShapeInstance shapeInst( shape, false );
  261. shapeInst.animate(0);
  262. if ( !shapeInst.buildPolyList( &polyList, 0 ) )
  263. return false;
  264. // Gah... Ratcliff's lib works on doubles... why, oh why?
  265. Vector<F64> doubleVerts;
  266. doubleVerts.setSize( polyList.mVertexList.size() * 3 );
  267. for ( U32 i=0; i < polyList.mVertexList.size(); i++ )
  268. {
  269. doubleVerts[ ( i * 3 ) + 0 ] = (F64)polyList.mVertexList[i].x;
  270. doubleVerts[ ( i * 3 ) + 1 ] = (F64)polyList.mVertexList[i].y;
  271. doubleVerts[ ( i * 3 ) + 2 ] = (F64)polyList.mVertexList[i].z;
  272. }
  273. using namespace ConvexDecomposition;
  274. class ConvexBuilder : public ConvexDecompInterface
  275. {
  276. public:
  277. ConvexBuilder() { }
  278. ~ConvexBuilder()
  279. {
  280. for ( U32 i=0; i < mHulls.size(); i++ )
  281. delete mHulls[i];
  282. }
  283. virtual void ConvexDecompResult( ConvexResult &result )
  284. {
  285. FConvexResult *hull = new FConvexResult( result );
  286. mHulls.push_back( hull );
  287. }
  288. Vector<FConvexResult*> mHulls;
  289. };
  290. DecompDesc d;
  291. d.mVcount = polyList.mVertexList.size();
  292. d.mVertices = doubleVerts.address();
  293. d.mTcount = polyList.mIndexList.size() / 3;
  294. d.mIndices = polyList.mIndexList.address();
  295. d.mDepth = 3;
  296. d.mCpercent = 20.0f;
  297. d.mPpercent = 30.0f;
  298. d.mMaxVertices = 32;
  299. d.mSkinWidth = 0.05f; // Need to expose this!
  300. ConvexBuilder builder;
  301. d.mCallback = &builder;
  302. if ( performConvexDecomposition( d ) < 1 || builder.mHulls.empty() )
  303. return false;
  304. // Add all the convex hull results into the collision shape.
  305. colShape = PHYSICSMGR->createCollision();
  306. for ( U32 i=0; i < builder.mHulls.size(); i++ )
  307. colShape->addConvex( (const Point3F*)builder.mHulls[i]->mHullVertices,
  308. builder.mHulls[i]->mHullVcount,
  309. MatrixF::Identity );
  310. */
  311. return !shapeError;
  312. }
  313. IMPLEMENT_CO_NETOBJECT_V1(PhysicsShape);
  314. ConsoleDocClass( PhysicsShape,
  315. "@brief Represents a destructible physical object simulated through the plugin system.\n\n"
  316. "@see PhysicsShapeData.\n"
  317. "@ingroup Physics"
  318. );
  319. PhysicsShape::PhysicsShape()
  320. : mPhysicsRep( NULL ),
  321. mWorld( NULL ),
  322. mResetPos( MatrixF::Identity ),
  323. mShapeInst( NULL ),
  324. mDestroyed( false ),
  325. mPlayAmbient( false ),
  326. mAmbientSeq( -1 ),
  327. mAmbientThread( NULL )
  328. {
  329. mNetFlags.set( Ghostable | ScopeAlways );
  330. mTypeMask |= DynamicShapeObjectType;
  331. }
  332. PhysicsShape::~PhysicsShape()
  333. {
  334. }
  335. void PhysicsShape::consoleInit()
  336. {
  337. Con::addVariable( "$PhysicsShape::noCorrections", TypeBool, &PhysicsShape::smNoCorrections,
  338. "@brief Determines if the shape will recieve corrections from the server or "
  339. "will instead be allowed to diverge.\n\n"
  340. "In the event that the client and server object positions/orientations "
  341. "differ and if this variable is true, the server will attempt to \'correct\' "
  342. "the client object to keep it in sync. Otherwise, client and server objects may fall out of sync.\n\n");
  343. Con::addVariable( "$PhysicsShape::noSmoothing", TypeBool, &PhysicsShape::smNoSmoothing,
  344. "@brief Determines if client-side shapes will attempt to smoothly transition to "
  345. "their new position after reciving a correction.\n\n"
  346. "If true, shapes will immediately render at the position they are corrected to.\n\n");
  347. Parent::consoleInit();
  348. }
  349. void PhysicsShape::initPersistFields()
  350. {
  351. addGroup( "PhysicsShape" );
  352. addField( "playAmbient", TypeBool, Offset( mPlayAmbient, PhysicsShape ),
  353. "@brief Enables or disables playing of an ambient animation upon loading the shape.\n\n"
  354. "@note The ambient animation must be named \"ambient\"." );
  355. endGroup( "PhysicsShape" );
  356. Parent::initPersistFields();
  357. removeField( "scale" );
  358. }
  359. void PhysicsShape::inspectPostApply()
  360. {
  361. Parent::inspectPostApply();
  362. setMaskBits( InitialUpdateMask );
  363. }
  364. U32 PhysicsShape::packUpdate( NetConnection *con, U32 mask, BitStream *stream )
  365. {
  366. U32 retMask = Parent::packUpdate( con, mask, stream );
  367. if ( stream->writeFlag( mask & InitialUpdateMask ) )
  368. {
  369. stream->writeAffineTransform( getTransform() );
  370. stream->writeFlag( mPlayAmbient );
  371. stream->writeFlag( mDestroyed );
  372. return retMask;
  373. }
  374. // If we got here its not an initial update. So only send
  375. // the least amount of data possible.
  376. if ( stream->writeFlag( mask & StateMask ) )
  377. {
  378. // This will encode the position relative to the control
  379. // object position.
  380. //
  381. // This will compress the position to as little as 6.25
  382. // bytes if the position is within about 30 meters of the
  383. // control object.
  384. //
  385. // Worst case its a full 12 bytes + 2 bits if the position
  386. // is more than 500 meters from the control object.
  387. //
  388. stream->writeCompressedPoint( mState.position );
  389. // Use only 3.5 bytes to send the orientation.
  390. stream->writeQuat( mState.orientation, 9 );
  391. // If the server object has been set to sleep then
  392. // we don't need to send any velocity.
  393. if ( !stream->writeFlag( mState.sleeping ) )
  394. {
  395. // This gives me ~0.015f resolution in velocity magnitude
  396. // while only costing me 1 bit of the velocity is zero length,
  397. // <5 bytes in normal cases, and <8 bytes if the velocity is
  398. // greater than 1000.
  399. AssertWarn( mState.linVelocity.len() < 1000.0f,
  400. "PhysicsShape::packUpdate - The linVelocity is out of range!" );
  401. stream->writeVector( mState.linVelocity, 1000.0f, 16, 9 );
  402. // For angular velocity we get < 0.01f resolution in magnitude
  403. // with the most common case being under 4 bytes.
  404. AssertWarn( mState.angVelocity.len() < 10.0f,
  405. "PhysicsShape::packUpdate - The angVelocity is out of range!" );
  406. stream->writeVector( mState.angVelocity, 10.0f, 10, 9 );
  407. }
  408. }
  409. if ( stream->writeFlag( mask & DamageMask ) )
  410. stream->writeFlag( mDestroyed );
  411. return retMask;
  412. }
  413. void PhysicsShape::unpackUpdate( NetConnection *con, BitStream *stream )
  414. {
  415. Parent::unpackUpdate( con, stream );
  416. if ( stream->readFlag() ) // InitialUpdateMask
  417. {
  418. MatrixF mat;
  419. stream->readAffineTransform( &mat );
  420. setTransform( mat );
  421. mPlayAmbient = stream->readFlag();
  422. if ( isProperlyAdded() )
  423. _initAmbient();
  424. if ( stream->readFlag() )
  425. {
  426. if ( isProperlyAdded() )
  427. {
  428. // Destroy immediately if we've already been added
  429. // to the scene.
  430. destroy();
  431. }
  432. else
  433. {
  434. // Indicate the shape should be destroyed when the
  435. // shape is added.
  436. mDestroyed = true;
  437. }
  438. }
  439. return;
  440. }
  441. if ( stream->readFlag() ) // StateMask
  442. {
  443. PhysicsState state;
  444. // Read the encoded and compressed position... commonly only 6.25 bytes.
  445. stream->readCompressedPoint( &state.position );
  446. // Read the compressed quaternion... 3.5 bytes.
  447. stream->readQuat( &state.orientation, 9 );
  448. state.sleeping = stream->readFlag();
  449. if ( !state.sleeping )
  450. {
  451. stream->readVector( &state.linVelocity, 1000.0f, 16, 9 );
  452. stream->readVector( &state.angVelocity, 10.0f, 10, 9 );
  453. }
  454. if ( !smNoCorrections && mPhysicsRep && mPhysicsRep->isDynamic() && !mDestroyed )
  455. {
  456. // Set the new state on the physics object immediately.
  457. mPhysicsRep->applyCorrection( state.getTransform() );
  458. mPhysicsRep->setSleeping( state.sleeping );
  459. if ( !state.sleeping )
  460. {
  461. mPhysicsRep->setLinVelocity( state.linVelocity );
  462. mPhysicsRep->setAngVelocity( state.angVelocity );
  463. }
  464. mPhysicsRep->getState( &mState );
  465. }
  466. // If there is no physics object then just set the
  467. // new state... the tick will take care of the
  468. // interpolation and extrapolation.
  469. if ( !mPhysicsRep || !mPhysicsRep->isDynamic() )
  470. mState = state;
  471. }
  472. if ( stream->readFlag() ) // DamageMask
  473. {
  474. if ( stream->readFlag() )
  475. destroy();
  476. else
  477. restore();
  478. }
  479. }
  480. bool PhysicsShape::onAdd()
  481. {
  482. if ( !Parent::onAdd() )
  483. return false;
  484. // If we don't have a physics plugin active then
  485. // we have to fail completely.
  486. if ( !PHYSICSMGR )
  487. {
  488. Con::errorf( "PhysicsShape::onAdd - No physics plugin is active!" );
  489. return false;
  490. }
  491. //
  492. if ( !mPhysicsRep && !_createShape() )
  493. {
  494. Con::errorf( "PhysicsShape::onAdd() - Shape creation failed!" );
  495. return false;
  496. }
  497. // The reset position is the transform on the server
  498. // at creation time... its not used on the client.
  499. if ( isServerObject() )
  500. {
  501. storeRestorePos();
  502. PhysicsPlugin::getPhysicsResetSignal().notify( this, &PhysicsShape::_onPhysicsReset );
  503. }
  504. // Register for the resource change signal.
  505. //ResourceManager::get().getChangedSignal().notify( this, &PhysicsShape::_onResourceChanged );
  506. // Only add server objects and non-destroyed client objects to the scene.
  507. if ( isServerObject() || !mDestroyed)
  508. addToScene();
  509. if ( isClientObject() && mDestroyed )
  510. {
  511. // Disable all simulation of the body... no collision or dynamics.
  512. if ( mPhysicsRep )
  513. mPhysicsRep->setSimulationEnabled( false );
  514. // Stop doing tick processing for this SceneObject.
  515. setProcessTick( false );
  516. }
  517. return true;
  518. }
  519. void PhysicsShape::onRemove()
  520. {
  521. removeFromScene();
  522. SAFE_DELETE( mPhysicsRep );
  523. SAFE_DELETE( mShapeInst );
  524. mAmbientThread = NULL;
  525. mAmbientSeq = -1;
  526. mWorld = NULL;
  527. if ( isServerObject() )
  528. {
  529. PhysicsPlugin::getPhysicsResetSignal().remove( this, &PhysicsShape::_onPhysicsReset );
  530. if ( mDestroyedShape )
  531. mDestroyedShape->deleteObject();
  532. }
  533. // Remove the resource change signal.
  534. //ResourceManager::get().getChangedSignal().remove( this, &PhysicsShape::_onResourceChanged );
  535. Parent::onRemove();
  536. }
  537. bool PhysicsShape::onNewDataBlock( GameBaseData *dptr, bool reload )
  538. {
  539. if ( !Parent::onNewDataBlock( dptr, reload ) )
  540. return false;
  541. if ( !isProperlyAdded() )
  542. return true;
  543. // If we don't have a physics plugin active then
  544. // we have to fail completely.
  545. if ( !PHYSICSMGR )
  546. {
  547. Con::errorf( "PhysicsShape::onNewDataBlock - No physics plugin is active!" );
  548. return false;
  549. }
  550. //
  551. if ( !_createShape() )
  552. {
  553. Con::errorf( "PhysicsShape::onNewDataBlock() - Shape creation failed!" );
  554. return false;
  555. }
  556. return true;
  557. }
  558. bool PhysicsShape::_createShape()
  559. {
  560. SAFE_DELETE( mPhysicsRep );
  561. SAFE_DELETE( mShapeInst );
  562. mAmbientThread = NULL;
  563. mWorld = NULL;
  564. mAmbientSeq = -1;
  565. PhysicsShapeData *db = getDataBlock();
  566. if ( !db || !db->mShape)
  567. return false;
  568. // Set the world box.
  569. mObjBox = db->mShape->mBounds;
  570. resetWorldBox();
  571. // If this is the server and its a client only simulation
  572. // object then disable our tick... the server doesn't do
  573. // any work for this shape.
  574. if ( isServerObject() &&
  575. db->simType == PhysicsShapeData::SimType_ClientOnly )
  576. {
  577. setProcessTick( false );
  578. return true;
  579. }
  580. // Create the shape instance.
  581. mShapeInst = new TSShapeInstance( db->mShape, isClientObject() );
  582. if ( isClientObject() )
  583. {
  584. mAmbientSeq = db->mShape->findSequence( "ambient" );
  585. _initAmbient();
  586. }
  587. // If the shape has a mass then its dynamic... else
  588. // its a kinematic shape.
  589. //
  590. // While a kinematic is less optimal than a static body
  591. // it allows for us to enable/disable collision and having
  592. // all dynamic actors react correctly... waking up.
  593. //
  594. const bool isDynamic = db->mass > 0.0f;
  595. // If we aren't dynamic we don't need to tick.
  596. setProcessTick( isDynamic || mPlayAmbient );
  597. // If this is the client and we're a server only object then
  598. // we don't need any physics representation... we're done.
  599. if ( isClientObject() &&
  600. db->simType == PhysicsShapeData::SimType_ServerOnly )
  601. return true;
  602. mWorld = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  603. mPhysicsRep = PHYSICSMGR->createBody();
  604. mPhysicsRep->init( db->colShape,
  605. db->mass,
  606. isDynamic ? 0 : PhysicsBody::BF_KINEMATIC,
  607. this,
  608. mWorld );
  609. mPhysicsRep->setMaterial( db->restitution, db->dynamicFriction, db->staticFriction );
  610. if ( isDynamic )
  611. {
  612. mPhysicsRep->setDamping( db->linearDamping, db->angularDamping );
  613. mPhysicsRep->setSleepThreshold( db->linearSleepThreshold, db->angularSleepThreshold );
  614. }
  615. mPhysicsRep->setTransform( getTransform() );
  616. return true;
  617. }
  618. void PhysicsShape::_initAmbient()
  619. {
  620. if ( isServerObject() )
  621. return;
  622. bool willPlay = mPlayAmbient && mAmbientSeq != -1;
  623. if ( willPlay )
  624. {
  625. // Create thread if we dont already have.
  626. if ( mAmbientThread == NULL )
  627. mAmbientThread = mShapeInst->addThread();
  628. // Play the sequence.
  629. mShapeInst->setSequence( mAmbientThread, mAmbientSeq, 0);
  630. setProcessTick(true);
  631. }
  632. else
  633. {
  634. if ( mAmbientThread != NULL )
  635. {
  636. mShapeInst->destroyThread( mAmbientThread );
  637. mAmbientThread = NULL;
  638. }
  639. }
  640. }
  641. void PhysicsShape::_onPhysicsReset( PhysicsResetEvent reset )
  642. {
  643. if ( reset == PhysicsResetEvent_Store )
  644. mResetPos = getTransform();
  645. else if ( reset == PhysicsResetEvent_Restore )
  646. {
  647. setTransform( mResetPos );
  648. // Restore to un-destroyed state.
  649. restore();
  650. // Cheat and reset the client from here.
  651. if ( getClientObject() )
  652. {
  653. PhysicsShape *clientObj = (PhysicsShape*)getClientObject();
  654. clientObj->setTransform( mResetPos );
  655. clientObj->restore();
  656. }
  657. }
  658. }
  659. void PhysicsShape::setTransform( const MatrixF &newMat )
  660. {
  661. Parent::setTransform( newMat );
  662. // This is only called to set an absolute position
  663. // so we discard the delta state.
  664. mState.position = getPosition();
  665. mState.orientation.set( newMat );
  666. mRenderState[0] = mRenderState[1] = mState;
  667. setMaskBits( StateMask );
  668. if ( mPhysicsRep )
  669. mPhysicsRep->setTransform( newMat );
  670. }
  671. void PhysicsShape::setScale( const VectorF &scale )
  672. {
  673. // Cannot scale PhysicsShape.
  674. return;
  675. }
  676. void PhysicsShape::storeRestorePos()
  677. {
  678. mResetPos = getTransform();
  679. }
  680. F32 PhysicsShape::getMass() const
  681. {
  682. const PhysicsShapeData *db = const_cast<PhysicsShape*>( this )->getDataBlock();
  683. return db->mass;
  684. }
  685. void PhysicsShape::applyImpulse( const Point3F &pos, const VectorF &vec )
  686. {
  687. if ( mPhysicsRep && mPhysicsRep->isDynamic() )
  688. mPhysicsRep->applyImpulse( pos, vec );
  689. }
  690. void PhysicsShape::applyTorque( const Point3F &torque )
  691. {
  692. if (mPhysicsRep && mPhysicsRep->isDynamic())
  693. mPhysicsRep->applyTorque( torque );
  694. }
  695. void PhysicsShape::applyForce( const Point3F &force )
  696. {
  697. if (mPhysicsRep && mPhysicsRep->isDynamic())
  698. mPhysicsRep->applyForce( force );
  699. }
  700. void PhysicsShape::applyRadialImpulse( const Point3F &origin, F32 radius, F32 magnitude )
  701. {
  702. if ( !mPhysicsRep || !mPhysicsRep->isDynamic() )
  703. return;
  704. // TODO: Find a better approximation of the
  705. // force vector using the object box.
  706. VectorF force = getWorldBox().getCenter() - origin;
  707. F32 dist = force.magnitudeSafe();
  708. force.normalize();
  709. if ( dist == 0.0f )
  710. force *= magnitude;
  711. else
  712. force *= mClampF( radius / dist, 0.0f, 1.0f ) * magnitude;
  713. mPhysicsRep->applyImpulse( origin, force );
  714. // TODO: There is no simple way to really sync this sort of an
  715. // event with the client.
  716. //
  717. // The best is to send the current physics snapshot, calculate the
  718. // time difference from when this event occured and the time when the
  719. // client recieves it, and then extrapolate where it should be.
  720. //
  721. // Even then its impossible to be absolutely sure its synced.
  722. //
  723. // Bottom line... you shouldn't use physics over the network like this.
  724. //
  725. // Cheat for single player.
  726. //if ( getClientObject() )
  727. //((PhysicsShape*)getClientObject())->mPhysicsRep->applyImpulse( origin, force );
  728. }
  729. void PhysicsShape::interpolateTick( F32 delta )
  730. {
  731. AssertFatal( !mDestroyed, "PhysicsShape::interpolateTick - Shouldn't be processing a destroyed shape!" );
  732. if ( !mPhysicsRep->isDynamic() )
  733. return;
  734. // Interpolate the position and rotation based on the delta.
  735. PhysicsState state;
  736. state.interpolate( mRenderState[1], mRenderState[0], delta );
  737. // Set the transform to the interpolated transform.
  738. setRenderTransform( state.getTransform() );
  739. }
  740. void PhysicsShape::processTick( const Move *move )
  741. {
  742. AssertFatal( mPhysicsRep && !mDestroyed, "PhysicsShape::processTick - Shouldn't be processing a destroyed shape!" );
  743. // Note that unlike TSStatic, the serverside PhysicsShape does not
  744. // need to play the ambient animation because even if the animation were
  745. // to move collision shapes it would not affect the physx representation.
  746. if ( !mPhysicsRep->isDynamic() )
  747. return;
  748. // SINGLE PLAYER HACK!!!!
  749. if ( PHYSICSMGR->isSinglePlayer() && isClientObject() && getServerObject() )
  750. {
  751. PhysicsShape *servObj = (PhysicsShape*)getServerObject();
  752. setTransform( servObj->mState.getTransform() );
  753. mRenderState[0] = servObj->mRenderState[0];
  754. mRenderState[1] = servObj->mRenderState[1];
  755. return;
  756. }
  757. // Store the last render state.
  758. mRenderState[0] = mRenderState[1];
  759. // If the last render state doesn't match the last simulation
  760. // state then we got a correction and need to
  761. Point3F errorDelta = mRenderState[1].position - mState.position;
  762. const bool doSmoothing = !errorDelta.isZero() && !smNoSmoothing;
  763. const bool wasSleeping = mState.sleeping;
  764. // Get the new physics state.
  765. if ( mPhysicsRep )
  766. {
  767. mPhysicsRep->getState( &mState );
  768. _updateContainerForces();
  769. }
  770. else
  771. {
  772. // This is where we could extrapolate.
  773. }
  774. // Smooth the correction back into the render state.
  775. mRenderState[1] = mState;
  776. if ( doSmoothing )
  777. {
  778. F32 correction = mClampF( errorDelta.len() / 20.0f, 0.1f, 0.9f );
  779. mRenderState[1].position.interpolate( mState.position, mRenderState[0].position, correction );
  780. mRenderState[1].orientation.interpolate( mState.orientation, mRenderState[0].orientation, correction );
  781. }
  782. // If we haven't been sleeping then update our transform
  783. // and set ourselves as dirty for the next client update.
  784. if ( !wasSleeping || !mState.sleeping )
  785. {
  786. // Set the transform on the parent so that
  787. // the physics object isn't moved.
  788. Parent::setTransform( mState.getTransform() );
  789. // If we're doing server simulation then we need
  790. // to send the client a state update.
  791. if ( isServerObject() && mPhysicsRep && !smNoCorrections &&
  792. !PHYSICSMGR->isSinglePlayer() // SINGLE PLAYER HACK!!!!
  793. )
  794. setMaskBits( StateMask );
  795. }
  796. }
  797. void PhysicsShape::advanceTime( F32 timeDelta )
  798. {
  799. if ( isClientObject() && mPlayAmbient && mAmbientThread != NULL )
  800. mShapeInst->advanceTime( timeDelta, mAmbientThread );
  801. }
  802. void PhysicsShape::_updateContainerForces()
  803. {
  804. PROFILE_SCOPE( PhysicsShape_updateContainerForces );
  805. // If we're not simulating don't update forces.
  806. if ( !mWorld->isEnabled() )
  807. return;
  808. ContainerQueryInfo info;
  809. info.box = getWorldBox();
  810. info.mass = getDataBlock()->mass;
  811. // Find and retreive physics info from intersecting WaterObject(s)
  812. getContainer()->findObjects( getWorldBox(), WaterObjectType|PhysicalZoneObjectType, findRouter, &info );
  813. // Calculate buoyancy and drag
  814. F32 angDrag = getDataBlock()->angularDamping;
  815. F32 linDrag = getDataBlock()->linearDamping;
  816. F32 buoyancy = 0.0f;
  817. Point3F cmass = mPhysicsRep->getCMassPosition();
  818. F32 density = getDataBlock()->buoyancyDensity;
  819. if ( density > 0.0f )
  820. {
  821. if ( info.waterCoverage > 0.0f )
  822. {
  823. F32 waterDragScale = info.waterViscosity * getDataBlock()->waterDampingScale;
  824. F32 powCoverage = mPow( info.waterCoverage, 0.25f );
  825. angDrag = mLerp( angDrag, angDrag * waterDragScale, powCoverage );
  826. linDrag = mLerp( linDrag, linDrag * waterDragScale, powCoverage );
  827. }
  828. buoyancy = ( info.waterDensity / density ) * mPow( info.waterCoverage, 2.0f );
  829. // A little hackery to prevent oscillation
  830. // Based on this blog post:
  831. // (http://reinot.blogspot.com/2005/11/oh-yes-they-float-georgie-they-all.html)
  832. // JCF: disabled!
  833. Point3F buoyancyForce = buoyancy * -mWorld->getGravity() * TickSec * getDataBlock()->mass;
  834. mPhysicsRep->applyImpulse( cmass, buoyancyForce );
  835. }
  836. // Update the dampening as the container might have changed.
  837. mPhysicsRep->setDamping( linDrag, angDrag );
  838. // Apply physical zone forces.
  839. if ( !info.appliedForce.isZero() )
  840. mPhysicsRep->applyImpulse( cmass, info.appliedForce );
  841. }
  842. void PhysicsShape::prepRenderImage( SceneRenderState *state )
  843. {
  844. AssertFatal( !mDestroyed, "PhysicsShape::prepRenderImage - Shouldn't be processing a destroyed shape!" );
  845. PROFILE_SCOPE( PhysicsShape_prepRenderImage );
  846. if( !mShapeInst )
  847. return;
  848. Point3F cameraOffset;
  849. getRenderTransform().getColumn(3,&cameraOffset);
  850. cameraOffset -= state->getDiffuseCameraPosition();
  851. F32 dist = cameraOffset.len();
  852. if (dist < 0.01f)
  853. dist = 0.01f;
  854. F32 invScale = (1.0f/getMax(getMax(mObjScale.x,mObjScale.y),mObjScale.z));
  855. if ( mShapeInst->setDetailFromDistance( state, dist * invScale ) < 0 )
  856. return;
  857. GFXTransformSaver saver;
  858. // Set up our TS render state.
  859. TSRenderState rdata;
  860. rdata.setSceneState( state );
  861. rdata.setFadeOverride( 1.0f );
  862. // We might have some forward lit materials
  863. // so pass down a query to gather lights.
  864. LightQuery query;
  865. query.init( getWorldSphere() );
  866. rdata.setLightQuery( &query );
  867. MatrixF mat = getRenderTransform();
  868. mat.scale( mObjScale );
  869. GFX->setWorldMatrix( mat );
  870. mShapeInst->animate();
  871. mShapeInst->render( rdata );
  872. }
  873. void PhysicsShape::destroy()
  874. {
  875. if ( mDestroyed )
  876. return;
  877. mDestroyed = true;
  878. setMaskBits( DamageMask );
  879. const Point3F lastLinVel = mPhysicsRep->isDynamic() ? mPhysicsRep->getLinVelocity() : Point3F::Zero;
  880. // Disable all simulation of the body... no collision or dynamics.
  881. mPhysicsRep->setSimulationEnabled( false );
  882. // On the client side we remove it from the scene graph
  883. // to disable rendering and volume queries.
  884. if ( isClientObject() )
  885. removeFromScene();
  886. // Stop doing tick processing for this SceneObject.
  887. setProcessTick( false );
  888. PhysicsShapeData *db = getDataBlock();
  889. if ( !db )
  890. return;
  891. const MatrixF &mat = getTransform();
  892. if ( isServerObject() )
  893. {
  894. // We only create the destroyed object on the server
  895. // and let ghosting deal with updating the client.
  896. if ( db->destroyedShape )
  897. {
  898. mDestroyedShape = new PhysicsShape();
  899. mDestroyedShape->setDataBlock( db->destroyedShape );
  900. mDestroyedShape->setTransform( mat );
  901. if ( !mDestroyedShape->registerObject() )
  902. delete mDestroyedShape.getObject();
  903. }
  904. return;
  905. }
  906. // Let the physics debris create itself.
  907. PhysicsDebris::create( db->debris, mat, lastLinVel );
  908. if ( db->explosion )
  909. {
  910. Explosion *splod = new Explosion();
  911. splod->setDataBlock( db->explosion );
  912. splod->setTransform( mat );
  913. splod->setInitialState( getPosition(), mat.getUpVector(), 1.0f );
  914. if ( !splod->registerObject() )
  915. delete splod;
  916. }
  917. }
  918. void PhysicsShape::restore()
  919. {
  920. if ( !mDestroyed )
  921. return;
  922. PhysicsShapeData *db = getDataBlock();
  923. const bool isDynamic = db && db->mass > 0.0f;
  924. if ( mDestroyedShape )
  925. mDestroyedShape->deleteObject();
  926. // Restore tick processing, add it back to
  927. // the scene, and enable collision and simulation.
  928. setProcessTick( isDynamic || mPlayAmbient );
  929. if ( isClientObject() )
  930. addToScene();
  931. mPhysicsRep->setSimulationEnabled( true );
  932. mDestroyed = false;
  933. setMaskBits( DamageMask );
  934. }
  935. DefineEngineMethod( PhysicsShape, isDestroyed, bool, (),,
  936. "@brief Returns if a PhysicsShape has been destroyed or not.\n\n" )
  937. {
  938. return object->isDestroyed();
  939. }
  940. DefineEngineMethod( PhysicsShape, destroy, void, (),,
  941. "@brief Disables rendering and physical simulation.\n\n"
  942. "Calling destroy() will also spawn any explosions, debris, and/or destroyedShape "
  943. "defined for it, as well as remove it from the scene graph.\n\n"
  944. "Destroyed objects are only created on the server. Ghosting will later update the client.\n\n"
  945. "@note This does not actually delete the PhysicsShape." )
  946. {
  947. object->destroy();
  948. }
  949. DefineEngineMethod( PhysicsShape, restore, void, (),,
  950. "@brief Restores the shape to its state before being destroyed.\n\n"
  951. "Re-enables rendering and physical simulation on the object and "
  952. "adds it to the client's scene graph. "
  953. "Has no effect if the shape is not destroyed.\n\n")
  954. {
  955. object->restore();
  956. }
  957. DefineEngineMethod( PhysicsShape, applyTorque, void, (Point3F torque), ,
  958. "@brief Add a torque to a dynamic physics shape.\n\n"
  959. "@param torque to apply to the dynamic physics shape\n"
  960. "@note This value is ignored on physics shapes that are not dynamic. Wakes up the dynamic physics shape if it is sleeping.\n")
  961. {
  962. object->applyTorque( torque );
  963. }
  964. DefineEngineMethod(PhysicsShape, applyForce, void, (Point3F force), ,
  965. "@brief Add a force to a dynamic physics shape.\n\n"
  966. "@param force to apply to the dynamic physics shape\n"
  967. "@note This value is ignored on physics shapes that are not dynamic. Wakes up the dynamic physics shape if it is sleeping.\n")
  968. {
  969. object->applyForce( force );
  970. }