BsPhysX.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) override { /* Do nothing */ }
  118. void onWake(PxActor** actors, PxU32 count) override { /* Do nothing */ }
  119. void onSleep(PxActor** actors, PxU32 count) override { /* Do nothing */ }
  120. void onTrigger(PxTriggerPair* pairs, PxU32 count) override
  121. {
  122. for (PxU32 i = 0; i < count; i++)
  123. {
  124. const PxTriggerPair& pair = pairs[i];
  125. PhysX::ContactEventType type;
  126. bool ignoreContact = false;
  127. switch ((UINT32)pair.status)
  128. {
  129. case PxPairFlag::eNOTIFY_TOUCH_FOUND:
  130. type = PhysX::ContactEventType::ContactBegin;
  131. break;
  132. case PxPairFlag::eNOTIFY_TOUCH_PERSISTS:
  133. type = PhysX::ContactEventType::ContactStay;
  134. break;
  135. case PxPairFlag::eNOTIFY_TOUCH_LOST:
  136. type = PhysX::ContactEventType::ContactEnd;
  137. break;
  138. default:
  139. ignoreContact = true;
  140. break;
  141. }
  142. if (ignoreContact)
  143. continue;
  144. PhysX::TriggerEvent event;
  145. event.trigger = (Collider*)pair.triggerShape->userData;
  146. event.other = (Collider*)pair.otherShape->userData;
  147. event.type = type;
  148. gPhysX()._reportTriggerEvent(event);
  149. }
  150. }
  151. void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 count) override
  152. {
  153. for (PxU32 i = 0; i < count; i++)
  154. {
  155. const PxContactPair& pair = pairs[i];
  156. PhysX::ContactEventType type;
  157. bool ignoreContact = false;
  158. switch((UINT32)pair.events)
  159. {
  160. case PxPairFlag::eNOTIFY_TOUCH_FOUND:
  161. type = PhysX::ContactEventType::ContactBegin;
  162. break;
  163. case PxPairFlag::eNOTIFY_TOUCH_PERSISTS:
  164. type = PhysX::ContactEventType::ContactStay;
  165. break;
  166. case PxPairFlag::eNOTIFY_TOUCH_LOST:
  167. type = PhysX::ContactEventType::ContactEnd;
  168. break;
  169. default:
  170. ignoreContact = true;
  171. break;
  172. }
  173. if (ignoreContact)
  174. continue;
  175. PhysX::ContactEvent event;
  176. event.colliderA = (Collider*)pair.shapes[0]->userData;
  177. event.colliderB = (Collider*)pair.shapes[1]->userData;
  178. event.type = type;
  179. PxU32 contactCount = pair.contactCount;
  180. const PxU8* stream = pair.contactStream;
  181. PxU16 streamSize = pair.contactStreamSize;
  182. if (contactCount > 0 && streamSize > 0)
  183. {
  184. PxU32 contactIdx = 0;
  185. PxContactStreamIterator iter((PxU8*)stream, streamSize);
  186. stream += ((streamSize + 15) & ~15);
  187. const PxReal* impulses = reinterpret_cast<const PxReal*>(stream);
  188. PxU32 hasImpulses = (pair.flags & PxContactPairFlag::eINTERNAL_HAS_IMPULSES);
  189. while (iter.hasNextPatch())
  190. {
  191. iter.nextPatch();
  192. while (iter.hasNextContact())
  193. {
  194. iter.nextContact();
  195. ContactPoint point;
  196. point.position = fromPxVector(iter.getContactPoint());
  197. point.separation = iter.getSeparation();
  198. point.normal = fromPxVector(iter.getContactNormal());
  199. if (hasImpulses)
  200. point.impulse = impulses[contactIdx];
  201. else
  202. point.impulse = 0.0f;
  203. event.points.push_back(point);
  204. contactIdx++;
  205. }
  206. }
  207. }
  208. gPhysX()._reportContactEvent(event);
  209. }
  210. }
  211. };
  212. class PhysXCPUDispatcher : public PxCpuDispatcher
  213. {
  214. public:
  215. void submitTask(PxBaseTask& physxTask) override
  216. {
  217. // Note: Banshee's task scheduler is pretty low granularity. Consider a better task manager in case PhysX ends
  218. // up submitting many tasks.
  219. // - PhysX's task manager doesn't seem much lighter either. But perhaps I can at least create a task pool to
  220. // avoid allocating them constantly.
  221. auto runTask = [&]() { physxTask.run(); physxTask.release(); };
  222. TaskPtr task = Task::create("PhysX", runTask);
  223. TaskScheduler::instance().addTask(task);
  224. }
  225. PxU32 getWorkerCount() const override
  226. {
  227. return (PxU32)TaskScheduler::instance().getNumWorkers();
  228. }
  229. };
  230. PxFilterFlags PhysXFilterShader(PxFilterObjectAttributes attr0, PxFilterData data0, PxFilterObjectAttributes attr1,
  231. PxFilterData data1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)
  232. {
  233. if (PxFilterObjectIsTrigger(attr0) || PxFilterObjectIsTrigger(attr1))
  234. {
  235. pairFlags = PxPairFlag::eTRIGGER_DEFAULT;
  236. return PxFilterFlags();
  237. }
  238. UINT64 groupA = *(UINT64*)&data0.word0;
  239. UINT64 groupB = *(UINT64*)&data1.word0;
  240. bool canCollide = gPhysics().isCollisionEnabled(groupA, groupB);
  241. if (!canCollide)
  242. return PxFilterFlag::eSUPPRESS;
  243. pairFlags = PxPairFlag::eCONTACT_DEFAULT;
  244. return PxFilterFlags();
  245. }
  246. static PhysXAllocator gPhysXAllocator;
  247. static PhysXErrorCallback gPhysXErrorHandler;
  248. static PhysXCPUDispatcher gPhysXCPUDispatcher;
  249. static PhysXEventCallback gPhysXEventCallback;
  250. PhysX::PhysX()
  251. {
  252. PHYSICS_INIT_DESC input; // TODO - Make this an input parameter.
  253. mScale.length = input.typicalLength;
  254. mScale.speed = input.typicalSpeed;
  255. mFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gPhysXAllocator, gPhysXErrorHandler);
  256. mPhysics = PxCreateBasePhysics(PX_PHYSICS_VERSION, *mFoundation, mScale);
  257. PxRegisterArticulations(*mPhysics);
  258. if (input.initCooking)
  259. {
  260. // Note: PhysX supports cooking for specific platforms to make the generated results better. Consider
  261. // allowing the meshes to be re-cooked when target platform is changed. Right now we just use the default value.
  262. PxCookingParams cookingParams(mScale);
  263. mCooking = PxCreateCooking(PX_PHYSICS_VERSION, *mFoundation, cookingParams);
  264. }
  265. PxSceneDesc sceneDesc(mScale); // TODO - Test out various other parameters provided by scene desc
  266. sceneDesc.gravity = toPxVector(input.gravity);
  267. sceneDesc.cpuDispatcher = &gPhysXCPUDispatcher;
  268. sceneDesc.filterShader = PhysXFilterShader;
  269. sceneDesc.simulationEventCallback = &gPhysXEventCallback;
  270. sceneDesc.flags = PxSceneFlag::eENABLE_ACTIVETRANSFORMS;
  271. mScene = mPhysics->createScene(sceneDesc);
  272. mSimulationStep = input.timeStep;
  273. mDefaultMaterial = mPhysics->createMaterial(0.0f, 0.0f, 0.0f);
  274. }
  275. PhysX::~PhysX()
  276. {
  277. mScene->release();
  278. if (mCooking != nullptr)
  279. mCooking->release();
  280. mPhysics->release();
  281. mFoundation->release();
  282. }
  283. void PhysX::update()
  284. {
  285. mUpdateInProgress = true;
  286. float nextFrameTime = mLastSimulationTime + mSimulationStep;
  287. float curFrameTime = gTime().getTime();
  288. if(curFrameTime < nextFrameTime)
  289. {
  290. // TODO - Interpolate rigidbodies but perform no actual simulation
  291. return;
  292. }
  293. float simulationAmount = curFrameTime - mLastSimulationTime;
  294. while (simulationAmount >= mSimulationStep) // In case we're running really slow multiple updates might be needed
  295. {
  296. // Note: Consider delaying fetchResults one frame. This could improve performance because Physics update would be
  297. // able to run parallel to the simulation thread, but at a cost to input latency.
  298. // TODO - Provide a scratch buffer for the simulation (use the frame allocator, but I must extend it so it allocates
  299. // on a 16 byte boundary).
  300. mScene->simulate(mSimulationStep);
  301. mScene->fetchResults(true);
  302. // Update rigidbodies with new transforms
  303. PxU32 numActiveTransforms;
  304. const PxActiveTransform* activeTransforms = mScene->getActiveTransforms(numActiveTransforms);
  305. for (PxU32 i = 0; i < numActiveTransforms; i++)
  306. {
  307. Rigidbody* rigidbody = static_cast<Rigidbody*>(activeTransforms[i].userData);
  308. const PxTransform& transform = activeTransforms[i].actor2World;
  309. // Note: Make this faster, avoid dereferencing Rigidbody and attempt to access pos/rot destination directly,
  310. // use non-temporal writes
  311. rigidbody->_setTransform(fromPxVector(transform.p), fromPxQuaternion(transform.q));
  312. }
  313. simulationAmount -= mSimulationStep;
  314. }
  315. // TODO - Consider extrapolating for the remaining "simulationAmount" value
  316. mLastSimulationTime = curFrameTime;
  317. mUpdateInProgress = false;
  318. triggerEvents();
  319. }
  320. void PhysX::_reportContactEvent(const ContactEvent& event)
  321. {
  322. mContactEvents.push_back(event);
  323. }
  324. void PhysX::_reportTriggerEvent(const TriggerEvent& event)
  325. {
  326. mTriggerEvents.push_back(event);
  327. }
  328. void PhysX::triggerEvents()
  329. {
  330. CollisionData data;
  331. for(auto& entry : mTriggerEvents)
  332. {
  333. data.collider = entry.other;
  334. switch (entry.type)
  335. {
  336. case ContactEventType::ContactBegin:
  337. entry.trigger->onCollisionBegin(data);
  338. break;
  339. case ContactEventType::ContactStay:
  340. entry.trigger->onCollisionStay(data);
  341. break;
  342. case ContactEventType::ContactEnd:
  343. entry.trigger->onCollisionEnd(data);
  344. break;
  345. }
  346. }
  347. auto notifyContact = [&](Collider* obj, Collider* other, ContactEventType type,
  348. const Vector<ContactPoint>& points, bool flipNormals = false)
  349. {
  350. data.collider = other;
  351. data.contactPoints = points;
  352. if(flipNormals)
  353. {
  354. for (auto& point : data.contactPoints)
  355. point.normal = -point.normal;
  356. }
  357. SPtr<Rigidbody> rigidbody = obj->getRigidbody();
  358. if(rigidbody != nullptr)
  359. {
  360. switch (type)
  361. {
  362. case ContactEventType::ContactBegin:
  363. rigidbody->onCollisionBegin(data);
  364. break;
  365. case ContactEventType::ContactStay:
  366. rigidbody->onCollisionStay(data);
  367. break;
  368. case ContactEventType::ContactEnd:
  369. rigidbody->onCollisionEnd(data);
  370. break;
  371. }
  372. }
  373. else
  374. {
  375. switch (type)
  376. {
  377. case ContactEventType::ContactBegin:
  378. obj->onCollisionBegin(data);
  379. break;
  380. case ContactEventType::ContactStay:
  381. obj->onCollisionStay(data);
  382. break;
  383. case ContactEventType::ContactEnd:
  384. obj->onCollisionEnd(data);
  385. break;
  386. }
  387. }
  388. };
  389. for (auto& entry : mContactEvents)
  390. {
  391. notifyContact(entry.colliderA, entry.colliderB, entry.type, entry.points, true);
  392. notifyContact(entry.colliderB, entry.colliderA, entry.type, entry.points, false);
  393. }
  394. mTriggerEvents.clear();
  395. mContactEvents.clear();
  396. }
  397. SPtr<PhysicsMaterial> PhysX::createMaterial(float staticFriction, float dynamicFriction, float restitution)
  398. {
  399. return bs_shared_ptr_new<PhysXMaterial>(mPhysics, staticFriction, dynamicFriction, restitution);
  400. }
  401. SPtr<PhysicsMesh> PhysX::createMesh(const MeshDataPtr& meshData, PhysicsMeshType type)
  402. {
  403. return bs_shared_ptr_new<PhysXMesh>(meshData, type);
  404. }
  405. SPtr<Rigidbody> PhysX::createRigidbody(const HSceneObject& linkedSO)
  406. {
  407. return bs_shared_ptr_new<PhysXRigidbody>(mPhysics, mScene, linkedSO);
  408. }
  409. SPtr<BoxCollider> PhysX::createBoxCollider(const Vector3& extents, const Vector3& position,
  410. const Quaternion& rotation)
  411. {
  412. return bs_shared_ptr_new<PhysXBoxCollider>(mPhysics, position, rotation, extents);
  413. }
  414. SPtr<SphereCollider> PhysX::createSphereCollider(float radius, const Vector3& position, const Quaternion& rotation)
  415. {
  416. return bs_shared_ptr_new<PhysXSphereCollider>(mPhysics, position, rotation, radius);
  417. }
  418. SPtr<PlaneCollider> PhysX::createPlaneCollider(const Vector3& position, const Quaternion& rotation)
  419. {
  420. return bs_shared_ptr_new<PhysXPlaneCollider>(mPhysics, position, rotation);
  421. }
  422. SPtr<CapsuleCollider> PhysX::createCapsuleCollider(float radius, float halfHeight, const Vector3& position,
  423. const Quaternion& rotation)
  424. {
  425. return bs_shared_ptr_new<PhysXCapsuleCollider>(mPhysics, position, rotation, radius, halfHeight);
  426. }
  427. SPtr<MeshCollider> PhysX::createMeshCollider(const Vector3& position, const Quaternion& rotation)
  428. {
  429. return bs_shared_ptr_new<PhysXMeshCollider>(mPhysics, position, rotation);
  430. }
  431. SPtr<FixedJoint> PhysX::createFixedJoint()
  432. {
  433. return bs_shared_ptr_new<PhysXFixedJoint>(mPhysics);
  434. }
  435. SPtr<DistanceJoint> PhysX::createDistanceJoint()
  436. {
  437. return bs_shared_ptr_new<PhysXDistanceJoint>(mPhysics);
  438. }
  439. SPtr<HingeJoint> PhysX::createHingeJoint()
  440. {
  441. return bs_shared_ptr_new<PhysXHingeJoint>(mPhysics);
  442. }
  443. SPtr<SphericalJoint> PhysX::createSphericalJoint()
  444. {
  445. return bs_shared_ptr_new<PhysXSphericalJoint>(mPhysics);
  446. }
  447. SPtr<SliderJoint> PhysX::createSliderJoint()
  448. {
  449. return bs_shared_ptr_new<PhysXSliderJoint>(mPhysics);
  450. }
  451. SPtr<D6Joint> PhysX::createD6Joint()
  452. {
  453. return bs_shared_ptr_new<PhysXD6Joint>(mPhysics);
  454. }
  455. PhysX& gPhysX()
  456. {
  457. return static_cast<PhysX&>(PhysX::instance());
  458. }
  459. }