btWorld.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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/bullet/btWorld.h"
  24. #include "T3D/physics/bullet/btPlugin.h"
  25. #include "T3D/physics/bullet/btCasts.h"
  26. #include "T3D/physics/physicsUserData.h"
  27. #include "core/stream/bitStream.h"
  28. #include "platform/profiler.h"
  29. #include "sim/netConnection.h"
  30. #include "console/console.h"
  31. #include "console/consoleTypes.h"
  32. #include "scene/sceneRenderState.h"
  33. #include "T3D/gameBase/gameProcess.h"
  34. BtWorld::BtWorld() :
  35. mProcessList( NULL ),
  36. mIsSimulating( false ),
  37. mErrorReport( false ),
  38. mTickCount( 0 ),
  39. mIsEnabled( false ),
  40. mEditorTimeScale( 1.0f ),
  41. mDynamicsWorld( NULL ),
  42. mThreadSupportCollision( NULL )
  43. {
  44. }
  45. BtWorld::~BtWorld()
  46. {
  47. }
  48. bool BtWorld::initWorld( bool isServer, ProcessList *processList )
  49. {
  50. // Collision configuration contains default setup for memory, collision setup.
  51. mCollisionConfiguration = new btDefaultCollisionConfiguration();
  52. // TODO: There is something wrong with multithreading
  53. // and compound convex shapes... so disable it for now.
  54. static const U32 smMaxThreads = 1;
  55. // Different initialization with threading enabled.
  56. if ( smMaxThreads > 1 )
  57. {
  58. // TODO: ifdef assumes smMaxThread is always one at this point. MACOSX support to be decided
  59. #ifdef WIN32
  60. mThreadSupportCollision = new Win32ThreadSupport(
  61. Win32ThreadSupport::Win32ThreadConstructionInfo( isServer ? "bt_servercol" : "bt_clientcol",
  62. processCollisionTask,
  63. createCollisionLocalStoreMemory,
  64. smMaxThreads ) );
  65. mDispatcher = new SpuGatheringCollisionDispatcher( mThreadSupportCollision,
  66. smMaxThreads,
  67. mCollisionConfiguration );
  68. #endif // WIN32
  69. }
  70. else
  71. {
  72. mThreadSupportCollision = NULL;
  73. mDispatcher = new btCollisionDispatcher( mCollisionConfiguration );
  74. }
  75. btVector3 worldMin( -2000, -2000, -1000 );
  76. btVector3 worldMax( 2000, 2000, 1000 );
  77. btAxisSweep3 *sweepBP = new btAxisSweep3( worldMin, worldMax );
  78. mBroadphase = sweepBP;
  79. sweepBP->getOverlappingPairCache()->setInternalGhostPairCallback( new btGhostPairCallback() );
  80. // The default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded).
  81. mSolver = new btSequentialImpulseConstraintSolver;
  82. mDynamicsWorld = new btDiscreteDynamicsWorld( mDispatcher, mBroadphase, mSolver, mCollisionConfiguration );
  83. if ( !mDynamicsWorld )
  84. {
  85. Con::errorf( "BtWorld - %s failed to create dynamics world!", isServer ? "Server" : "Client" );
  86. return false;
  87. }
  88. // Removing the randomization in the solver is required
  89. // to make the simulation deterministic.
  90. mDynamicsWorld->getSolverInfo().m_solverMode &= ~SOLVER_RANDMIZE_ORDER;
  91. mDynamicsWorld->setGravity( btCast<btVector3>( mGravity ) );
  92. AssertFatal( processList, "BtWorld::init() - We need a process list to create the world!" );
  93. mProcessList = processList;
  94. mProcessList->preTickSignal().notify( this, &BtWorld::getPhysicsResults );
  95. mProcessList->postTickSignal().notify( this, &BtWorld::tickPhysics, 1000.0f );
  96. return true;
  97. }
  98. void BtWorld::_destroy()
  99. {
  100. // Release the tick processing signals.
  101. if ( mProcessList )
  102. {
  103. mProcessList->preTickSignal().remove( this, &BtWorld::getPhysicsResults );
  104. mProcessList->postTickSignal().remove( this, &BtWorld::tickPhysics );
  105. mProcessList = NULL;
  106. }
  107. // TODO: Release any remaining
  108. // orphaned rigid bodies here.
  109. SAFE_DELETE( mDynamicsWorld );
  110. SAFE_DELETE( mSolver );
  111. SAFE_DELETE( mBroadphase );
  112. SAFE_DELETE( mDispatcher );
  113. SAFE_DELETE( mThreadSupportCollision );
  114. SAFE_DELETE( mCollisionConfiguration );
  115. }
  116. void BtWorld::tickPhysics( U32 elapsedMs )
  117. {
  118. if ( !mDynamicsWorld || !mIsEnabled )
  119. return;
  120. // Did we forget to call getPhysicsResults somewhere?
  121. AssertFatal( !mIsSimulating, "PhysXWorld::tickPhysics() - Already simulating!" );
  122. // The elapsed time should be non-zero and
  123. // a multiple of TickMs!
  124. AssertFatal( elapsedMs != 0 &&
  125. ( elapsedMs % TickMs ) == 0 , "PhysXWorld::tickPhysics() - Got bad elapsed time!" );
  126. PROFILE_SCOPE(BtWorld_TickPhysics);
  127. // Convert it to seconds.
  128. const F32 elapsedSec = (F32)elapsedMs * 0.001f;
  129. // Simulate... it is recommended to always use Bullet's default fixed timestep/
  130. mDynamicsWorld->stepSimulation( elapsedSec * mEditorTimeScale );
  131. mIsSimulating = true;
  132. //Con::printf( "%s BtWorld::tickPhysics!", this == smClientWorld ? "Client" : "Server" );
  133. }
  134. void BtWorld::getPhysicsResults()
  135. {
  136. if ( !mDynamicsWorld || !mIsSimulating )
  137. return;
  138. PROFILE_SCOPE(BtWorld_GetPhysicsResults);
  139. // Get results from scene.
  140. // mScene->fetchResults( NX_RIGID_BODY_FINISHED, true );
  141. mIsSimulating = false;
  142. mTickCount++;
  143. }
  144. void BtWorld::setEnabled( bool enabled )
  145. {
  146. mIsEnabled = enabled;
  147. if ( !mIsEnabled )
  148. getPhysicsResults();
  149. }
  150. void BtWorld::destroyWorld()
  151. {
  152. _destroy();
  153. }
  154. bool BtWorld::castRay( const Point3F &startPnt, const Point3F &endPnt, RayInfo *ri, const Point3F &impulse )
  155. {
  156. btCollisionWorld::ClosestRayResultCallback result( btCast<btVector3>( startPnt ), btCast<btVector3>( endPnt ) );
  157. mDynamicsWorld->rayTest( btCast<btVector3>( startPnt ), btCast<btVector3>( endPnt ), result );
  158. if ( !result.hasHit() || !result.m_collisionObject )
  159. return false;
  160. if ( ri )
  161. {
  162. ri->object = PhysicsUserData::getObject( result.m_collisionObject->getUserPointer() );
  163. // If we were passed a RayInfo, we can only return true signifying a collision
  164. // if we hit an object that actually has a torque object associated with it.
  165. //
  166. // In some ways this could be considered an error, either a physx object
  167. // has raycast-collision enabled that shouldn't or someone did not set
  168. // an object in this actor's userData.
  169. //
  170. if ( ri->object == NULL )
  171. return false;
  172. ri->distance = ( endPnt - startPnt ).len() * result.m_closestHitFraction;
  173. ri->normal = btCast<Point3F>( result.m_hitNormalWorld );
  174. ri->point = btCast<Point3F>( result.m_hitPointWorld );
  175. ri->t = result.m_closestHitFraction;
  176. }
  177. /*
  178. if ( impulse.isZero() ||
  179. !actor.isDynamic() ||
  180. actor.readBodyFlag( NX_BF_KINEMATIC ) )
  181. return true;
  182. NxVec3 force = pxCast<NxVec3>( impulse );//worldRay.dir * forceAmt;
  183. actor.addForceAtPos( force, hitInfo.worldImpact, NX_IMPULSE );
  184. */
  185. return true;
  186. }
  187. PhysicsBody* BtWorld::castRay( const Point3F &start, const Point3F &end, U32 bodyTypes )
  188. {
  189. btVector3 startPt = btCast<btVector3>( start );
  190. btVector3 endPt = btCast<btVector3>( end );
  191. btCollisionWorld::ClosestRayResultCallback result( startPt, endPt );
  192. mDynamicsWorld->rayTest( startPt, endPt, result );
  193. if ( !result.hasHit() || !result.m_collisionObject )
  194. return NULL;
  195. PhysicsUserData *userData = PhysicsUserData::cast( result.m_collisionObject->getUserPointer() );
  196. if ( !userData )
  197. return NULL;
  198. return userData->getBody();
  199. }
  200. void BtWorld::explosion( const Point3F &pos, F32 radius, F32 forceMagnitude )
  201. {
  202. /*
  203. // Find Actors at the position within the radius
  204. // and apply force to them.
  205. NxVec3 nxPos = pxCast<NxVec3>( pos );
  206. NxShape **shapes = (NxShape**)NxAlloca(10*sizeof(NxShape*));
  207. NxSphere worldSphere( nxPos, radius );
  208. NxU32 numHits = mScene->overlapSphereShapes( worldSphere, NX_ALL_SHAPES, 10, shapes, NULL );
  209. for ( NxU32 i = 0; i < numHits; i++ )
  210. {
  211. NxActor &actor = shapes[i]->getActor();
  212. bool dynamic = actor.isDynamic();
  213. if ( !dynamic )
  214. continue;
  215. bool kinematic = actor.readBodyFlag( NX_BF_KINEMATIC );
  216. if ( kinematic )
  217. continue;
  218. NxVec3 force = actor.getGlobalPosition() - nxPos;
  219. force.normalize();
  220. force *= forceMagnitude;
  221. actor.addForceAtPos( force, nxPos, NX_IMPULSE, true );
  222. }
  223. */
  224. }
  225. void BtWorld::onDebugDraw( const SceneRenderState *state )
  226. {
  227. mDebugDraw.setCuller( &state->getFrustum() );
  228. mDynamicsWorld->setDebugDrawer( &mDebugDraw );
  229. mDynamicsWorld->debugDrawWorld();
  230. mDynamicsWorld->setDebugDrawer( NULL );
  231. mDebugDraw.flush();
  232. }
  233. void BtWorld::reset()
  234. {
  235. if ( !mDynamicsWorld )
  236. return;
  237. ///create a copy of the array, not a reference!
  238. btCollisionObjectArray copyArray = mDynamicsWorld->getCollisionObjectArray();
  239. S32 numObjects = mDynamicsWorld->getNumCollisionObjects();
  240. for ( S32 i=0; i < numObjects; i++ )
  241. {
  242. btCollisionObject* colObj = copyArray[i];
  243. btRigidBody* body = btRigidBody::upcast(colObj);
  244. if (body)
  245. {
  246. if (body->getMotionState())
  247. {
  248. //btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState();
  249. //myMotionState->m_graphicsWorldTrans = myMotionState->m_startWorldTrans;
  250. //body->setCenterOfMassTransform( myMotionState->m_graphicsWorldTrans );
  251. //colObj->setInterpolationWorldTransform( myMotionState->m_startWorldTrans );
  252. colObj->forceActivationState(ACTIVE_TAG);
  253. colObj->activate();
  254. colObj->setDeactivationTime(0);
  255. //colObj->setActivationState(WANTS_DEACTIVATION);
  256. }
  257. //removed cached contact points (this is not necessary if all objects have been removed from the dynamics world)
  258. //m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(colObj->getBroadphaseHandle(),getDynamicsWorld()->getDispatcher());
  259. btRigidBody* body = btRigidBody::upcast(colObj);
  260. if (body && !body->isStaticObject())
  261. {
  262. btRigidBody::upcast(colObj)->setLinearVelocity(btVector3(0,0,0));
  263. btRigidBody::upcast(colObj)->setAngularVelocity(btVector3(0,0,0));
  264. }
  265. }
  266. }
  267. // reset some internal cached data in the broadphase
  268. mDynamicsWorld->getBroadphase()->resetPool( mDynamicsWorld->getDispatcher() );
  269. mDynamicsWorld->getConstraintSolver()->reset();
  270. }
  271. /*
  272. ConsoleFunction( castForceRay, const char*, 4, 4, "( Point3F startPnt, Point3F endPnt, VectorF impulseVec )" )
  273. {
  274. PhysicsWorld *world = PHYSICSPLUGIN->getWorld( "server" );
  275. if ( !world )
  276. return NULL;
  277. char *returnBuffer = Con::getReturnBuffer(256);
  278. Point3F impulse;
  279. Point3F startPnt, endPnt;
  280. dSscanf( argv[1], "%f %f %f", &startPnt.x, &startPnt.y, &startPnt.z );
  281. dSscanf( argv[2], "%f %f %f", &endPnt.x, &endPnt.y, &endPnt.z );
  282. dSscanf( argv[3], "%f %f %f", &impulse.x, &impulse.y, &impulse.z );
  283. Point3F hitPoint;
  284. RayInfo rinfo;
  285. bool hit = world->castRay( startPnt, endPnt, &rinfo, impulse );
  286. DebugDrawer *ddraw = DebugDrawer::get();
  287. if ( ddraw )
  288. {
  289. ddraw->drawLine( startPnt, endPnt, hit ? ColorF::RED : ColorF::GREEN );
  290. ddraw->setLastTTL( 3000 );
  291. }
  292. if ( hit )
  293. {
  294. dSprintf(returnBuffer, 256, "%g %g %g",
  295. rinfo.point.x, rinfo.point.y, rinfo.point.z );
  296. return returnBuffer;
  297. }
  298. else
  299. return NULL;
  300. }
  301. */