BsPhysX.cpp 16 KB

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