BsPhysX.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. #include "BsPhysX.h"
  2. #include "PxPhysicsAPI.h"
  3. #include "BsPhysXMaterial.h"
  4. #include "BsPhysXMesh.h"
  5. #include "BsPhysXRigidbody.h"
  6. #include "BsPhysXBoxCollider.h"
  7. #include "BsPhysXSphereCollider.h"
  8. #include "BsPhysXPlaneCollider.h"
  9. #include "BsPhysXCapsuleCollider.h"
  10. #include "BsPhysXMeshCollider.h"
  11. #include "BsPhysXFixedJoint.h"
  12. #include "BsPhysXDistanceJoint.h"
  13. #include "BsPhysXHingeJoint.h"
  14. #include "BsPhysXSphericalJoint.h"
  15. #include "BsPhysXSliderJoint.h"
  16. #include "BsPhysXD6Joint.h"
  17. #include "BsTaskScheduler.h"
  18. #include "BsTime.h"
  19. #include "Bsvector3.h"
  20. using namespace physx;
  21. namespace BansheeEngine
  22. {
  23. struct PHYSICS_INIT_DESC
  24. {
  25. float typicalLength = 1.0f;
  26. float typicalSpeed = 9.81f;
  27. Vector3 gravity = Vector3(0.0f, -9.81f, 0.0f);
  28. bool initCooking = true; // TODO: Disable this for Game build
  29. float timeStep = 1.0f / 60.0f;
  30. };
  31. class PhysXAllocator : public PxAllocatorCallback
  32. {
  33. public:
  34. void* allocate(size_t size, const char*, const char*, int) override
  35. {
  36. void* ptr = bs_alloc_aligned16((UINT32)size);
  37. PX_ASSERT((reinterpret_cast<size_t>(ptr) & 15) == 0);
  38. return ptr;
  39. }
  40. void deallocate(void* ptr) override
  41. {
  42. bs_free_aligned16(ptr);
  43. }
  44. };
  45. class PhysXErrorCallback : public PxErrorCallback
  46. {
  47. public:
  48. void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line) override
  49. {
  50. {
  51. const char* errorCode = nullptr;
  52. UINT32 severity = 0;
  53. switch (code)
  54. {
  55. case PxErrorCode::eNO_ERROR:
  56. errorCode = "No error";
  57. break;
  58. case PxErrorCode::eINVALID_PARAMETER:
  59. errorCode = "Invalid parameter";
  60. severity = 2;
  61. break;
  62. case PxErrorCode::eINVALID_OPERATION:
  63. errorCode = "Invalid operation";
  64. severity = 2;
  65. break;
  66. case PxErrorCode::eOUT_OF_MEMORY:
  67. errorCode = "Out of memory";
  68. severity = 2;
  69. break;
  70. case PxErrorCode::eDEBUG_INFO:
  71. errorCode = "Info";
  72. break;
  73. case PxErrorCode::eDEBUG_WARNING:
  74. errorCode = "Warning";
  75. severity = 1;
  76. break;
  77. case PxErrorCode::ePERF_WARNING:
  78. errorCode = "Performance warning";
  79. severity = 1;
  80. break;
  81. case PxErrorCode::eABORT:
  82. errorCode = "Abort";
  83. severity = 2;
  84. break;
  85. case PxErrorCode::eINTERNAL_ERROR:
  86. errorCode = "Internal error";
  87. severity = 2;
  88. break;
  89. case PxErrorCode::eMASK_ALL:
  90. default:
  91. errorCode = "Unknown error";
  92. severity = 2;
  93. break;
  94. }
  95. StringStream ss;
  96. switch(severity)
  97. {
  98. case 0:
  99. ss << "PhysX info (" << errorCode << "): " << message << " at " << file << ":" << line;
  100. LOGDBG(ss.str());
  101. break;
  102. case 1:
  103. ss << "PhysX warning (" << errorCode << "): " << message << " at " << file << ":" << line;
  104. LOGWRN(ss.str());
  105. break;
  106. case 2:
  107. ss << "PhysX error (" << errorCode << "): " << message << " at " << file << ":" << line;
  108. LOGERR(ss.str());
  109. BS_ASSERT(false); // Halt execution on debug builds when error occurrs
  110. break;
  111. }
  112. }
  113. }
  114. };
  115. class PhysXEventCallback : public PxSimulationEventCallback
  116. {
  117. void onWake(PxActor** actors, PxU32 count) override { /* Do nothing */ }
  118. void onSleep(PxActor** actors, PxU32 count) override { /* Do nothing */ }
  119. void onTrigger(PxTriggerPair* pairs, PxU32 count) override
  120. {
  121. for (PxU32 i = 0; i < count; i++)
  122. {
  123. const PxTriggerPair& pair = pairs[i];
  124. PhysX::ContactEventType type;
  125. bool ignoreContact = false;
  126. switch ((UINT32)pair.status)
  127. {
  128. case PxPairFlag::eNOTIFY_TOUCH_FOUND:
  129. type = PhysX::ContactEventType::ContactBegin;
  130. break;
  131. case PxPairFlag::eNOTIFY_TOUCH_PERSISTS:
  132. type = PhysX::ContactEventType::ContactStay;
  133. break;
  134. case PxPairFlag::eNOTIFY_TOUCH_LOST:
  135. type = PhysX::ContactEventType::ContactEnd;
  136. break;
  137. default:
  138. ignoreContact = true;
  139. break;
  140. }
  141. if (ignoreContact)
  142. continue;
  143. PhysX::TriggerEvent event;
  144. event.trigger = (Collider*)pair.triggerShape->userData;
  145. event.other = (Collider*)pair.otherShape->userData;
  146. event.type = type;
  147. gPhysX()._reportTriggerEvent(event);
  148. }
  149. }
  150. void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 count) override
  151. {
  152. for (PxU32 i = 0; i < count; i++)
  153. {
  154. const PxContactPair& pair = pairs[i];
  155. PhysX::ContactEventType type;
  156. bool ignoreContact = false;
  157. switch((UINT32)pair.events)
  158. {
  159. case PxPairFlag::eNOTIFY_TOUCH_FOUND:
  160. type = PhysX::ContactEventType::ContactBegin;
  161. break;
  162. case PxPairFlag::eNOTIFY_TOUCH_PERSISTS:
  163. type = PhysX::ContactEventType::ContactStay;
  164. break;
  165. case PxPairFlag::eNOTIFY_TOUCH_LOST:
  166. type = PhysX::ContactEventType::ContactEnd;
  167. break;
  168. default:
  169. ignoreContact = true;
  170. break;
  171. }
  172. if (ignoreContact)
  173. continue;
  174. PhysX::ContactEvent event;
  175. event.colliderA = (Collider*)pair.shapes[0]->userData;
  176. event.colliderB = (Collider*)pair.shapes[1]->userData;
  177. event.type = type;
  178. PxU32 contactCount = pair.contactCount;
  179. const PxU8* stream = pair.contactStream;
  180. PxU16 streamSize = pair.contactStreamSize;
  181. if (contactCount > 0 && streamSize > 0)
  182. {
  183. PxU32 contactIdx = 0;
  184. PxContactStreamIterator iter((PxU8*)stream, streamSize);
  185. stream += ((streamSize + 15) & ~15);
  186. const PxReal* impulses = reinterpret_cast<const PxReal*>(stream);
  187. PxU32 hasImpulses = (pair.flags & PxContactPairFlag::eINTERNAL_HAS_IMPULSES);
  188. while (iter.hasNextPatch())
  189. {
  190. iter.nextPatch();
  191. while (iter.hasNextContact())
  192. {
  193. iter.nextContact();
  194. ContactPoint point;
  195. point.position = fromPxVector(iter.getContactPoint());
  196. point.separation = iter.getSeparation();
  197. point.normal = fromPxVector(iter.getContactNormal());
  198. if (hasImpulses)
  199. point.impulse = impulses[contactIdx];
  200. else
  201. point.impulse = 0.0f;
  202. event.points.push_back(point);
  203. contactIdx++;
  204. }
  205. }
  206. }
  207. gPhysX()._reportContactEvent(event);
  208. }
  209. }
  210. void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) override
  211. {
  212. for (UINT32 i = 0; i < count; i++)
  213. {
  214. PxConstraintInfo& constraintInfo = constraints[i];
  215. if (constraintInfo.type != PxConstraintExtIDs::eJOINT)
  216. continue;
  217. PxJoint* pxJoint = (PxJoint*)constraintInfo.externalReference;
  218. Joint* joint = (Joint*)pxJoint->userData;
  219. }
  220. }
  221. };
  222. class PhysXCPUDispatcher : public PxCpuDispatcher
  223. {
  224. public:
  225. void submitTask(PxBaseTask& physxTask) override
  226. {
  227. // Note: Banshee's task scheduler is pretty low granularity. Consider a better task manager in case PhysX ends
  228. // up submitting many tasks.
  229. // - PhysX's task manager doesn't seem much lighter either. But perhaps I can at least create a task pool to
  230. // avoid allocating them constantly.
  231. auto runTask = [&]() { physxTask.run(); physxTask.release(); };
  232. TaskPtr task = Task::create("PhysX", runTask);
  233. TaskScheduler::instance().addTask(task);
  234. }
  235. PxU32 getWorkerCount() const override
  236. {
  237. return (PxU32)TaskScheduler::instance().getNumWorkers();
  238. }
  239. };
  240. PxFilterFlags PhysXFilterShader(PxFilterObjectAttributes attr0, PxFilterData data0, PxFilterObjectAttributes attr1,
  241. PxFilterData data1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)
  242. {
  243. if (PxFilterObjectIsTrigger(attr0) || PxFilterObjectIsTrigger(attr1))
  244. {
  245. pairFlags = PxPairFlag::eTRIGGER_DEFAULT;
  246. return PxFilterFlags();
  247. }
  248. UINT64 groupA = *(UINT64*)&data0.word0;
  249. UINT64 groupB = *(UINT64*)&data1.word0;
  250. bool canCollide = gPhysics().isCollisionEnabled(groupA, groupB);
  251. if (!canCollide)
  252. return PxFilterFlag::eSUPPRESS;
  253. pairFlags = PxPairFlag::eCONTACT_DEFAULT;
  254. return PxFilterFlags();
  255. }
  256. static PhysXAllocator gPhysXAllocator;
  257. static PhysXErrorCallback gPhysXErrorHandler;
  258. static PhysXCPUDispatcher gPhysXCPUDispatcher;
  259. static PhysXEventCallback gPhysXEventCallback;
  260. PhysX::PhysX()
  261. {
  262. PHYSICS_INIT_DESC input; // TODO - Make this an input parameter.
  263. mScale.length = input.typicalLength;
  264. mScale.speed = input.typicalSpeed;
  265. mFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gPhysXAllocator, gPhysXErrorHandler);
  266. mPhysics = PxCreateBasePhysics(PX_PHYSICS_VERSION, *mFoundation, mScale);
  267. PxRegisterArticulations(*mPhysics);
  268. if (input.initCooking)
  269. {
  270. // Note: PhysX supports cooking for specific platforms to make the generated results better. Consider
  271. // allowing the meshes to be re-cooked when target platform is changed. Right now we just use the default value.
  272. PxCookingParams cookingParams(mScale);
  273. mCooking = PxCreateCooking(PX_PHYSICS_VERSION, *mFoundation, cookingParams);
  274. }
  275. PxSceneDesc sceneDesc(mScale); // TODO - Test out various other parameters provided by scene desc
  276. sceneDesc.gravity = toPxVector(input.gravity);
  277. sceneDesc.cpuDispatcher = &gPhysXCPUDispatcher;
  278. sceneDesc.filterShader = PhysXFilterShader;
  279. sceneDesc.simulationEventCallback = &gPhysXEventCallback;
  280. sceneDesc.flags = PxSceneFlag::eENABLE_ACTIVETRANSFORMS;
  281. mScene = mPhysics->createScene(sceneDesc);
  282. mSimulationStep = input.timeStep;
  283. mDefaultMaterial = mPhysics->createMaterial(0.0f, 0.0f, 0.0f);
  284. }
  285. PhysX::~PhysX()
  286. {
  287. mScene->release();
  288. if (mCooking != nullptr)
  289. mCooking->release();
  290. mPhysics->release();
  291. mFoundation->release();
  292. }
  293. void PhysX::update()
  294. {
  295. mUpdateInProgress = true;
  296. float nextFrameTime = mLastSimulationTime + mSimulationStep;
  297. float curFrameTime = gTime().getTime();
  298. if(curFrameTime < nextFrameTime)
  299. {
  300. // TODO - Interpolate rigidbodies but perform no actual simulation
  301. return;
  302. }
  303. float simulationAmount = curFrameTime - mLastSimulationTime;
  304. while (simulationAmount >= mSimulationStep) // In case we're running really slow multiple updates might be needed
  305. {
  306. // Note: Consider delaying fetchResults one frame. This could improve performance because Physics update would be
  307. // able to run parallel to the simulation thread, but at a cost to input latency.
  308. // TODO - Provide a scratch buffer for the simulation (use the frame allocator, but I must extend it so it allocates
  309. // on a 16 byte boundary).
  310. mScene->simulate(mSimulationStep);
  311. mScene->fetchResults(true);
  312. // Update rigidbodies with new transforms
  313. PxU32 numActiveTransforms;
  314. const PxActiveTransform* activeTransforms = mScene->getActiveTransforms(numActiveTransforms);
  315. for (PxU32 i = 0; i < numActiveTransforms; i++)
  316. {
  317. Rigidbody* rigidbody = static_cast<Rigidbody*>(activeTransforms[i].userData);
  318. const PxTransform& transform = activeTransforms[i].actor2World;
  319. // Note: Make this faster, avoid dereferencing Rigidbody and attempt to access pos/rot destination directly,
  320. // use non-temporal writes
  321. rigidbody->_setTransform(fromPxVector(transform.p), fromPxQuaternion(transform.q));
  322. }
  323. simulationAmount -= mSimulationStep;
  324. }
  325. // TODO - Consider extrapolating for the remaining "simulationAmount" value
  326. mLastSimulationTime = curFrameTime;
  327. mUpdateInProgress = false;
  328. triggerEvents();
  329. }
  330. void PhysX::_reportContactEvent(const ContactEvent& event)
  331. {
  332. mContactEvents.push_back(event);
  333. }
  334. void PhysX::_reportTriggerEvent(const TriggerEvent& event)
  335. {
  336. mTriggerEvents.push_back(event);
  337. }
  338. void PhysX::_reportJointBreakEvent(const JointBreakEvent& event)
  339. {
  340. mJointBreakEvents.push_back(event);
  341. }
  342. void PhysX::triggerEvents()
  343. {
  344. CollisionData data;
  345. for(auto& entry : mTriggerEvents)
  346. {
  347. data.collider = entry.other;
  348. switch (entry.type)
  349. {
  350. case ContactEventType::ContactBegin:
  351. entry.trigger->onCollisionBegin(data);
  352. break;
  353. case ContactEventType::ContactStay:
  354. entry.trigger->onCollisionStay(data);
  355. break;
  356. case ContactEventType::ContactEnd:
  357. entry.trigger->onCollisionEnd(data);
  358. break;
  359. }
  360. }
  361. auto notifyContact = [&](Collider* obj, Collider* other, ContactEventType type,
  362. const Vector<ContactPoint>& points, bool flipNormals = false)
  363. {
  364. data.collider = other;
  365. data.contactPoints = points;
  366. if(flipNormals)
  367. {
  368. for (auto& point : data.contactPoints)
  369. point.normal = -point.normal;
  370. }
  371. SPtr<Rigidbody> rigidbody = obj->getRigidbody();
  372. if(rigidbody != nullptr)
  373. {
  374. switch (type)
  375. {
  376. case ContactEventType::ContactBegin:
  377. rigidbody->onCollisionBegin(data);
  378. break;
  379. case ContactEventType::ContactStay:
  380. rigidbody->onCollisionStay(data);
  381. break;
  382. case ContactEventType::ContactEnd:
  383. rigidbody->onCollisionEnd(data);
  384. break;
  385. }
  386. }
  387. else
  388. {
  389. switch (type)
  390. {
  391. case ContactEventType::ContactBegin:
  392. obj->onCollisionBegin(data);
  393. break;
  394. case ContactEventType::ContactStay:
  395. obj->onCollisionStay(data);
  396. break;
  397. case ContactEventType::ContactEnd:
  398. obj->onCollisionEnd(data);
  399. break;
  400. }
  401. }
  402. };
  403. for (auto& entry : mContactEvents)
  404. {
  405. notifyContact(entry.colliderA, entry.colliderB, entry.type, entry.points, true);
  406. notifyContact(entry.colliderB, entry.colliderA, entry.type, entry.points, false);
  407. }
  408. for(auto& entry : mJointBreakEvents)
  409. {
  410. entry.joint->onJointBreak();
  411. }
  412. mTriggerEvents.clear();
  413. mContactEvents.clear();
  414. mJointBreakEvents.clear();
  415. }
  416. SPtr<PhysicsMaterial> PhysX::createMaterial(float staticFriction, float dynamicFriction, float restitution)
  417. {
  418. return bs_shared_ptr_new<PhysXMaterial>(mPhysics, staticFriction, dynamicFriction, restitution);
  419. }
  420. SPtr<PhysicsMesh> PhysX::createMesh(const MeshDataPtr& meshData, PhysicsMeshType type)
  421. {
  422. return bs_shared_ptr_new<PhysXMesh>(meshData, type);
  423. }
  424. SPtr<Rigidbody> PhysX::createRigidbody(const HSceneObject& linkedSO)
  425. {
  426. return bs_shared_ptr_new<PhysXRigidbody>(mPhysics, mScene, linkedSO);
  427. }
  428. SPtr<BoxCollider> PhysX::createBoxCollider(const Vector3& extents, const Vector3& position,
  429. const Quaternion& rotation)
  430. {
  431. return bs_shared_ptr_new<PhysXBoxCollider>(mPhysics, position, rotation, extents);
  432. }
  433. SPtr<SphereCollider> PhysX::createSphereCollider(float radius, const Vector3& position, const Quaternion& rotation)
  434. {
  435. return bs_shared_ptr_new<PhysXSphereCollider>(mPhysics, position, rotation, radius);
  436. }
  437. SPtr<PlaneCollider> PhysX::createPlaneCollider(const Vector3& position, const Quaternion& rotation)
  438. {
  439. return bs_shared_ptr_new<PhysXPlaneCollider>(mPhysics, position, rotation);
  440. }
  441. SPtr<CapsuleCollider> PhysX::createCapsuleCollider(float radius, float halfHeight, const Vector3& position,
  442. const Quaternion& rotation)
  443. {
  444. return bs_shared_ptr_new<PhysXCapsuleCollider>(mPhysics, position, rotation, radius, halfHeight);
  445. }
  446. SPtr<MeshCollider> PhysX::createMeshCollider(const Vector3& position, const Quaternion& rotation)
  447. {
  448. return bs_shared_ptr_new<PhysXMeshCollider>(mPhysics, position, rotation);
  449. }
  450. SPtr<FixedJoint> PhysX::createFixedJoint()
  451. {
  452. return bs_shared_ptr_new<PhysXFixedJoint>(mPhysics);
  453. }
  454. SPtr<DistanceJoint> PhysX::createDistanceJoint()
  455. {
  456. return bs_shared_ptr_new<PhysXDistanceJoint>(mPhysics);
  457. }
  458. SPtr<HingeJoint> PhysX::createHingeJoint()
  459. {
  460. return bs_shared_ptr_new<PhysXHingeJoint>(mPhysics);
  461. }
  462. SPtr<SphericalJoint> PhysX::createSphericalJoint()
  463. {
  464. return bs_shared_ptr_new<PhysXSphericalJoint>(mPhysics);
  465. }
  466. SPtr<SliderJoint> PhysX::createSliderJoint()
  467. {
  468. return bs_shared_ptr_new<PhysXSliderJoint>(mPhysics);
  469. }
  470. SPtr<D6Joint> PhysX::createD6Joint()
  471. {
  472. return bs_shared_ptr_new<PhysXD6Joint>(mPhysics);
  473. }
  474. PhysX& gPhysX()
  475. {
  476. return static_cast<PhysX&>(PhysX::instance());
  477. }
  478. }