35PxDefaultAllocator& allocator() {
static PxDefaultAllocator a;
return a; }
36PxDefaultErrorCallback& errors() {
static PxDefaultErrorCallback e;
return e; }
37PxFoundation* gFoundation =
nullptr;
38PxPhysics* gPhysics =
nullptr;
43constexpr float CONTACT_OFFSET = 0.01f;
44constexpr float SLEEP_THRESHOLD = 0.005f;
46constexpr float MAX_ANGULAR_VELOCITY = 50.0f;
47constexpr float MAX_DEPENETRATION_VELOCITY = 10.0f;
48constexpr uint32_t POSITION_ITERATIONS = 6;
49constexpr uint32_t VELOCITY_ITERATIONS = 1;
51uint32_t gPositionIterations = POSITION_ITERATIONS;
52uint32_t gVelocityIterations = VELOCITY_ITERATIONS;
53bool gAllowSleep =
true;
54constexpr float BOUNCE_THRESHOLD = 2.0f;
57constexpr float DENSITY = 1000.0f;
60PxMaterial* material(
float friction,
float restitution) {
61 uint32_t f = 0, r = 0;
62 std::memcpy(&f, &friction, 4);
63 std::memcpy(&r, &restitution, 4);
64 const uint64_t key = (
static_cast<uint64_t
>(f) << 32) | r;
65 auto found = g().materials.find(key);
66 if (found != g().materials.end())
return found->second;
69 PxMaterial* m = gPhysics->createMaterial(friction, friction, restitution);
70 m->setFrictionCombineMode(PxCombineMode::eAVERAGE);
71 m->setRestitutionCombineMode(PxCombineMode::eAVERAGE);
72 g().materials[key] = m;
76PxFilterData filterData(uint32_t layer, uint32_t kind) {
89PxFilterFlags filterShader(PxFilterObjectAttributes a0, PxFilterData d0,
90 PxFilterObjectAttributes a1, PxFilterData d1,
91 PxPairFlags& flags,
const void*, PxU32) {
92 if (!g().collide(d0.word0, d1.word0))
return PxFilterFlag::eSUPPRESS;
93 if (PxFilterObjectIsTrigger(a0) || PxFilterObjectIsTrigger(a1)) {
94 flags = PxPairFlag::eTRIGGER_DEFAULT;
95 return PxFilterFlag::eDEFAULT;
97 flags = PxPairFlag::eCONTACT_DEFAULT | PxPairFlag::eDETECT_CCD_CONTACT;
99 flags |= PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_LOST
100 | PxPairFlag::eNOTIFY_CONTACT_POINTS | PxPairFlag::ePRE_SOLVER_VELOCITY;
102 return PxFilterFlag::eDEFAULT;
106PxVec3 pointVelocity(
const PxContactPairHeader& header,
int side,
const PxContactPairVelocity& v,
const PxVec3& at) {
107 const PxContactPairHeaderFlag::Enum removed = side == 0 ? PxContactPairHeaderFlag::eREMOVED_ACTOR_0 : PxContactPairHeaderFlag::eREMOVED_ACTOR_1;
108 PxVec3 velocity = v.linearVelocity[side];
109 const PxActor* actor = header.actors[side];
110 if (!(header.flags & removed) && actor) {
111 if (
const PxRigidBody* body = actor->is<PxRigidBody>()) {
112 const PxVec3 centre = (body->getGlobalPose() * body->getCMassLocalPose()).p;
113 velocity += v.angularVelocity[side].cross(at - centre);
120float inverseMass(
const PxContactPairHeader& header,
int side) {
121 const PxContactPairHeaderFlag::Enum removed = side == 0 ? PxContactPairHeaderFlag::eREMOVED_ACTOR_0 : PxContactPairHeaderFlag::eREMOVED_ACTOR_1;
122 const PxActor* actor = header.actors[side];
123 if ((header.flags & removed) || !actor)
return 0.0f;
124 const PxRigidDynamic* body = actor->is<PxRigidDynamic>();
125 if (!body || (body->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC))
return 0.0f;
126 return body->getInvMass();
130class ContactRecorder final :
public PxSimulationEventCallback {
132 void onContact(
const PxContactPairHeader& header,
const PxContactPair* pairs, PxU32 count)
override {
134 const uint32_t a = (header.flags & PxContactPairHeaderFlag::eREMOVED_ACTOR_0)
135 ? 0u : px3::
entityOf(header.actors[0]);
136 const uint32_t b = (header.flags & PxContactPairHeaderFlag::eREMOVED_ACTOR_1)
138 if (a == 0 && b == 0)
return;
141 const PxContactPairVelocity* before[16] = {};
142 PxContactPairExtraDataIterator extra(header.extraDataStream, header.extraDataStreamSize);
143 while (extra.nextItemSet()) {
144 if (extra.preSolverVelocity && extra.contactPairIndex < 16) before[extra.contactPairIndex] = extra.preSolverVelocity;
146 for (PxU32 i = 0; i < count; ++i) {
147 const PxContactPair& pair = pairs[i];
148 if (pair.events & PxPairFlag::eNOTIFY_TOUCH_FOUND) {
149 PxContactPairPoint point;
150 PxVec3 normal(0.0f), position(0.0f);
151 if (pair.contactCount > 0 && pair.extractContacts(&point, 1) > 0) {
154 normal = -point.normal;
155 position = point.position;
157 g().contactEnterBuffer.insert(g().contactEnterBuffer.end(), {
158 static_cast<float>(a), static_cast<float>(b),
159 normal.x, normal.y, normal.z, position.x, position.y, position.z,
162 float closing = 0.0f;
163 if (i < 16 && before[i]) {
164 const PxVec3 at[2] = { pointVelocity(header, 0, *before[i], position), pointVelocity(header, 1, *before[i], position) };
165 closing = (at[0] - at[1]).dot(normal);
167 g().contactEnterSpeedBuffer.push_back(closing);
168 const float both = inverseMass(header, 0) + inverseMass(header, 1);
169 g().contactEnterMassBuffer.push_back(both > 0.0f ? 1.0f / both : std::numeric_limits<float>::infinity());
171 if (pair.events & PxPairFlag::eNOTIFY_TOUCH_LOST) {
172 g().contactExitBuffer.push_back(
static_cast<float>(a));
173 g().contactExitBuffer.push_back(
static_cast<float>(b));
178 void onTrigger(PxTriggerPair* pairs, PxU32 count)
override {
179 for (PxU32 i = 0; i < count; ++i) {
180 const PxTriggerPair& pair = pairs[i];
181 const uint32_t sensor = (pair.flags & PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER)
182 ? 0u : px3::
entityOf(pair.triggerActor);
183 const uint32_t other = (pair.flags & PxTriggerPairFlag::eREMOVED_SHAPE_OTHER)
185 if (sensor == 0 && other == 0)
continue;
187 std::vector<float>& out = pair.status == PxPairFlag::eNOTIFY_TOUCH_FOUND
188 ? g().sensorEnterBuffer : g().sensorExitBuffer;
189 if (pair.status != PxPairFlag::eNOTIFY_TOUCH_FOUND
190 && pair.status != PxPairFlag::eNOTIFY_TOUCH_LOST)
continue;
191 out.push_back(
static_cast<float>(sensor));
192 out.push_back(
static_cast<float>(other));
196 void onConstraintBreak(PxConstraintInfo*, PxU32)
override {}
197 void onWake(PxActor**, PxU32)
override {}
198 void onSleep(PxActor**, PxU32)
override {}
199 void onAdvance(
const PxRigidBody*
const*,
const PxTransform*,
const PxU32)
override {}
202ContactRecorder& recorder() {
static ContactRecorder r;
return r; }
206 float gravityScale = 1.0f;
207 float linearDamping = 0.0f;
208 float angularDamping = 0.0f;
209 int fixedRotation = 0;
214PxQuat quat(
float qx,
float qy,
float qz,
float qw) {
215 PxQuat q(qx, qy, qz, qw);
216 return q.magnitudeSquared() > 0.0f ? q.getNormalized() : PxQuat(PxIdentity);
220uint32_t addBody(uint32_t entity,
const PxGeometry& geometry,
const PxTransform& local,
221 float px,
float py,
float pz,
float qx,
float qy,
float qz,
float qw,
222 const BodyMotion& how,
float friction,
float restitution,
int isSensor) {
223 if (!g().isValid())
return 0;
224 const PxTransform pose(PxVec3(px, py, pz), quat(qx, qy, qz, qw));
225 if (!pose.isValid())
return 0;
226 PxRigidActor* actor =
nullptr;
227 PxRigidDynamic* dynamic =
nullptr;
228 if (how.motion == 0) {
229 actor = gPhysics->createRigidStatic(pose);
231 dynamic = gPhysics->createRigidDynamic(pose);
234 if (actor ==
nullptr)
return 0;
237 const PxShapeFlags shapeFlags = isSensor != 0
238 ? PxShapeFlags(PxShapeFlag::eTRIGGER_SHAPE | PxShapeFlag::eSCENE_QUERY_SHAPE)
239 : PxShapeFlags(PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eSCENE_QUERY_SHAPE);
240 PxShape* shape = gPhysics->createShape(geometry, *material(friction, restitution),
true, shapeFlags);
241 if (shape ==
nullptr) { actor->release();
return 0; }
242 shape->setLocalPose(local);
243 shape->setContactOffset(CONTACT_OFFSET);
244 shape->setRestOffset(0.0f);
245 shape->setSimulationFilterData(filterData(how.layer, 0));
246 shape->setQueryFilterData(filterData(how.layer, 0));
247 actor->attachShape(*shape);
250 auto record = std::make_unique<Body>();
251 record->entity = entity;
252 record->layer = how.layer;
253 record->actor = actor;
254 record->sensor = isSensor != 0;
255 record->gravityScale = how.gravityScale;
257 if (dynamic !=
nullptr) {
258 if (how.motion == 1) dynamic->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC,
true);
261 dynamic->setMass(1.0f);
262 dynamic->setMassSpaceInertiaTensor(PxVec3(1.0f));
264 PxRigidBodyExt::updateMassAndInertia(*dynamic, DENSITY);
266 dynamic->setLinearDamping(how.linearDamping);
267 dynamic->setAngularDamping(how.angularDamping);
268 dynamic->setMaxAngularVelocity(MAX_ANGULAR_VELOCITY);
269 dynamic->setMaxDepenetrationVelocity(MAX_DEPENETRATION_VELOCITY);
271 dynamic->setSleepThreshold(gAllowSleep ? SLEEP_THRESHOLD : 0.0f);
272 dynamic->setSolverIterationCounts(gPositionIterations, gVelocityIterations);
273 if (how.fixedRotation != 0) {
274 dynamic->setRigidDynamicLockFlags(PxRigidDynamicLockFlag::eLOCK_ANGULAR_X
275 | PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y | PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z);
278 if (how.continuous != 0 && how.motion == 2) {
279 dynamic->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD,
true);
281 if (how.gravityScale != 1.0f) actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY,
true);
284 const uint32_t
id = g().nextBodyId++;
286 actor->userData = record.get();
287 g().scene->addActor(*actor);
288 g().bodies[id] = std::move(record);
294PxVec3 offset(
float cx,
float cy,
float cz) {
295 const PxVec3 v(cx, cy, cz);
296 return v.isFinite() ? v : PxVec3(0.0f);
300const PxQuat& capsuleUpright() {
301 static const PxQuat q(PxHalfPi, PxVec3(0.0f, 0.0f, 1.0f));
305PxRigidDynamic* dynamicOf(uint32_t bodyId) {
306 Body* body = g().body(bodyId);
307 return body ? body->
actor->is<PxRigidDynamic>() : nullptr;
310bool isKinematic(
const PxRigidDynamic* dynamic) {
311 return dynamic->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC;
316void beforeSubstep(
float h) {
317 const PxVec3 gravity = g().scene->getGravity();
318 for (
auto& entry : g().bodies) {
319 Body& body = *entry.second;
320 PxRigidDynamic* dynamic = body.
actor->is<PxRigidDynamic>();
321 if (dynamic ==
nullptr)
continue;
322 if (isKinematic(dynamic)) {
324 PxTransform target = dynamic->getGlobalPose();
326 dynamic->setKinematicTarget(target);
327 }
else if (body.
gravityScale != 1.0f && !dynamic->isSleeping()) {
328 dynamic->addForce(gravity * body.
gravityScale, PxForceMode::eACCELERATION,
false);
347 if (g().isValid())
return;
350 if (gFoundation ==
nullptr) {
351 gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, allocator(), errors());
352 if (gFoundation ==
nullptr)
return;
353 gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),
false,
nullptr);
354 if (gPhysics ==
nullptr)
return;
360 g().dispatcher = PxDefaultCpuDispatcherCreate(0);
361 PxSceneDesc desc(gPhysics->getTolerancesScale());
362 desc.gravity = PxVec3(gx, gy, gz);
363 desc.cpuDispatcher = g().dispatcher;
364 desc.filterShader = filterShader;
365 desc.simulationEventCallback = &recorder();
366 desc.flags |= PxSceneFlag::eENABLE_ACTIVE_ACTORS | PxSceneFlag::eENABLE_CCD | PxSceneFlag::eENABLE_PCM;
367 desc.frictionType = PxFrictionType::ePATCH;
368 desc.solverType = PxSolverType::ePGS;
369 desc.bounceThresholdVelocity = BOUNCE_THRESHOLD;
370 g().scene = gPhysics->createScene(desc);
371 if (g().scene ==
nullptr)
return;
372 g().controllers = PxCreateControllerManager(*g().scene);
377 if (!g().isValid())
return;
378 for (
auto& entry : g().joints) entry.second.joint->release();
380 g().characters.clear();
381 if (g().controllers) g().controllers->release();
382 g().controllers =
nullptr;
383 for (
auto& entry : g().bodies) entry.second->actor->release();
385 g().scene->release();
387 g().dispatcher->release();
388 g().dispatcher =
nullptr;
389 g().transformBuffer.clear();
390 g().queryBuffer.clear();
391 g().contactEnterBuffer.clear();
392 g().contactEnterSpeedBuffer.clear();
393 g().contactEnterMassBuffer.clear();
394 g().contactExitBuffer.clear();
395 g().sensorEnterBuffer.clear();
396 g().sensorExitBuffer.clear();
409 float bounceThreshold) {
410 gVelocityIterations = velocityIterations > 0 ?
static_cast<uint32_t
>(velocityIterations) : VELOCITY_ITERATIONS;
411 gPositionIterations = positionIterations > 0 ?
static_cast<uint32_t
>(positionIterations) : POSITION_ITERATIONS;
412 gAllowSleep = allowSleep != 0;
413 if (g().isValid()) g().scene->setBounceThresholdVelocity(bounceThreshold > 0.0f ? bounceThreshold : BOUNCE_THRESHOLD);
418 if (!g().isValid() || dt <= 0.0f)
return;
420 if (g().characterHitsStale) g().characterHitBuffer.clear();
421 g().contactEnterBuffer.clear();
422 g().contactEnterSpeedBuffer.clear();
423 g().contactEnterMassBuffer.clear();
424 g().contactExitBuffer.clear();
425 g().sensorEnterBuffer.clear();
426 g().sensorExitBuffer.clear();
427 const int steps = collisionSteps > 0 ? collisionSteps : 1;
428 const float h = dt /
static_cast<float>(steps);
429 for (
int i = 0; i < steps; ++i) {
431 g().scene->simulate(h);
432 g().scene->fetchResults(
true);
436 PxActor** active = g().scene->getActiveActors(count);
437 std::vector<float>& out = g().transformBuffer;
439 out.reserve(count * 8);
440 for (PxU32 i = 0; i < count; ++i) {
441 const PxRigidActor* actor = active[i]->is<PxRigidActor>();
442 if (actor ==
nullptr || actor->userData ==
nullptr)
continue;
443 const Body* body =
static_cast<const Body*
>(actor->userData);
445 const PxTransform pose = actor->getGlobalPose();
446 out.insert(out.end(), {
447 static_cast<float>(body->entity), pose.p.x, pose.p.y, pose.p.z,
448 pose.q.x, pose.q.y, pose.q.z, pose.q.w,
451 g().characterHitsStale =
true;
456 if (g().isValid()) g().scene->forceRebuildDynamicTree(PX_SCENE_PRUNER_STATIC);
463 float px,
float py,
float pz,
float qx,
float qy,
float qz,
float qw,
464 int motion,
float gravityScale,
float linearDamping,
float angularDamping,
465 int fixedRotation, uint32_t layer,
int continuous,
466 float friction,
float restitution,
int isSensor,
float mass) {
467 if (!g().isValid() || partsPtr == 0 || count == 0 || count > 16384)
return 0;
468 const float* parts =
reinterpret_cast<const float*
>(partsPtr);
469 for (uint32_t i = 0; i < count; ++i) {
470 const float* p = parts + i * 11;
471 for (uint32_t j = 0; j < 11; ++j)
if (!std::isfinite(p[j]))
return 0;
472 if (!(p[1] > 0) || (p[0] == 0 && !(p[2] > 0 && p[3] > 0))
473 || (p[0] == 2 && p[2] < 0) || (p[0] != 0 && p[0] != 1 && p[0] != 2)
474 || PxQuat(p[7], p[8], p[9], p[10]).magnitudeSquared() < 1.0e-12f)
return 0;
477 const PxShapeFlags flags = isSensor != 0
478 ? PxShapeFlags(PxShapeFlag::eTRIGGER_SHAPE | PxShapeFlag::eSCENE_QUERY_SHAPE)
479 : PxShapeFlags(PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eSCENE_QUERY_SHAPE);
480 for (uint32_t i = 0; i < count; ++i) {
481 const float* p = parts + i * 11;
482 PxGeometryHolder geometry;
483 PxQuat rotation = quat(p[7], p[8], p[9], p[10]);
484 if (p[0] == 0) geometry.storeAny(PxBoxGeometry(p[1], p[2], p[3]));
485 else if (p[0] == 1 || p[2] == 0) geometry.storeAny(PxSphereGeometry(p[1]));
486 else { geometry.storeAny(PxCapsuleGeometry(p[1], p[2])); rotation = rotation * capsuleUpright(); }
487 const PxTransform local(PxVec3(p[4], p[5], p[6]), rotation);
489 id = addBody(entity, geometry.any(), local, px, py, pz, qx, qy, qz, qw,
490 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer, continuous},
491 friction, restitution, isSensor);
492 if (
id == 0)
return 0;
494 PxShape* shape = gPhysics->createShape(geometry.any(), *material(friction, restitution),
true, flags);
496 shape->setLocalPose(local);
497 shape->setContactOffset(CONTACT_OFFSET);
498 shape->setRestOffset(0.0f);
499 shape->setSimulationFilterData(filterData(layer, 0));
500 shape->setQueryFilterData(filterData(layer, 0));
501 const bool attached = g().body(
id)->actor->attachShape(*shape);
506 if (
auto* dynamic = dynamicOf(
id)) {
508 if (mass > 0 && std::isfinite(mass)) PxRigidBodyExt::setMassAndUpdateInertia(*dynamic, mass);
509 else PxRigidBodyExt::updateMassAndInertia(*dynamic, DENSITY);
517 float px,
float py,
float pz,
518 float qx,
float qy,
float qz,
float qw,
519 int motion,
float gravityScale,
float linearDamping,
520 float angularDamping,
int fixedRotation, uint32_t layer,
521 int continuous,
float friction,
float restitution,
int isSensor,
522 float cx,
float cy,
float cz) {
523 if (!(hx > 0.0f && hy > 0.0f && hz > 0.0f))
return 0;
524 return addBody(entity, PxBoxGeometry(hx, hy, hz), PxTransform(offset(cx, cy, cz)),
525 px, py, pz, qx, qy, qz, qw,
526 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer, continuous},
527 friction, restitution, isSensor);
532 float px,
float py,
float pz,
533 float qx,
float qy,
float qz,
float qw,
534 int motion,
float gravityScale,
float linearDamping,
535 float angularDamping,
int fixedRotation, uint32_t layer,
536 int continuous,
float friction,
float restitution,
int isSensor,
537 float cx,
float cy,
float cz) {
538 if (!(radius > 0.0f))
return 0;
539 return addBody(entity, PxSphereGeometry(radius), PxTransform(offset(cx, cy, cz)),
540 px, py, pz, qx, qy, qz, qw,
541 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer, continuous},
542 friction, restitution, isSensor);
547 float px,
float py,
float pz,
548 float qx,
float qy,
float qz,
float qw,
549 int motion,
float gravityScale,
float linearDamping,
550 float angularDamping,
int fixedRotation, uint32_t layer,
551 int continuous,
float friction,
float restitution,
int isSensor,
552 float cx,
float cy,
float cz) {
553 if (!(radius > 0.0f) || !(halfHeight >= 0.0f))
return 0;
554 return addBody(entity, PxCapsuleGeometry(radius, halfHeight),
555 PxTransform(offset(cx, cy, cz), capsuleUpright()),
556 px, py, pz, qx, qy, qz, qw,
557 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer, continuous},
558 friction, restitution, isSensor);
563 uintptr_t indexPtr, uint32_t indexCount,
564 float px,
float py,
float pz,
565 float qx,
float qy,
float qz,
float qw,
566 uint32_t layer,
float friction,
float restitution) {
567 if (!g().isValid() || vertexCount == 0 || indexCount < 3 || indexCount % 3 != 0)
return 0;
568 const float* positions =
reinterpret_cast<const float*
>(vertexPtr);
569 const uint32_t* indices =
reinterpret_cast<const uint32_t*
>(indexPtr);
570 if (positions ==
nullptr || indices ==
nullptr)
return 0;
571 for (uint32_t i = 0; i < indexCount; ++i) {
572 if (indices[i] >= vertexCount)
return 0;
574 PxTriangleMeshDesc desc;
575 desc.points.count = vertexCount;
576 desc.points.stride =
sizeof(float) * 3;
577 desc.points.data = positions;
578 desc.triangles.count = indexCount / 3;
579 desc.triangles.stride =
sizeof(uint32_t) * 3;
580 desc.triangles.data = indices;
581 const PxCookingParams params(gPhysics->getTolerancesScale());
582 PxTriangleMesh* mesh = PxCreateTriangleMesh(params, desc, gPhysics->getPhysicsInsertionCallback());
583 if (mesh ==
nullptr)
return 0;
585 const uint32_t
id = addBody(entity, PxTriangleMeshGeometry(mesh), PxTransform(PxIdentity),
586 px, py, pz, qx, qy, qz, qw, {0, 1.0f, 0.0f, 0.0f, 0, layer},
587 friction, restitution, 0);
594 float px,
float py,
float pz,
595 float qx,
float qy,
float qz,
float qw,
596 int motion,
float gravityScale,
float linearDamping,
597 float angularDamping,
int fixedRotation, uint32_t layer,
598 int continuous,
float friction,
float restitution,
int isSensor) {
599 if (!g().isValid() || vertexCount < 4)
return 0;
600 const float* positions =
reinterpret_cast<const float*
>(vertexPtr);
601 if (positions ==
nullptr)
return 0;
602 PxConvexMeshDesc desc;
603 desc.points.count = vertexCount;
604 desc.points.stride =
sizeof(float) * 3;
605 desc.points.data = positions;
607 desc.flags = PxConvexFlag::eCOMPUTE_CONVEX;
608 const PxCookingParams params(gPhysics->getTolerancesScale());
609 PxConvexMesh* mesh = PxCreateConvexMesh(params, desc, gPhysics->getPhysicsInsertionCallback());
611 if (mesh ==
nullptr)
return 0;
612 const uint32_t
id = addBody(entity, PxConvexMeshGeometry(mesh), PxTransform(PxIdentity),
613 px, py, pz, qx, qy, qz, qw,
614 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer, continuous},
615 friction, restitution, isSensor);
622 auto found = g().bodies.find(bodyId);
623 if (!g().isValid() || found == g().bodies.end())
return;
624 PxRigidActor* actor = found->second->actor;
625 actor->userData =
nullptr;
627 g().bodies.erase(found);
632 float qx,
float qy,
float qz,
float qw) {
633 Body* body = g().body(bodyId);
634 if (!g().isValid() || body ==
nullptr)
return;
635 const PxTransform pose(PxVec3(px, py, pz), quat(qx, qy, qz, qw));
636 if (!pose.isValid())
return;
638 body->
actor->setGlobalPose(pose,
true);
639 if (PxRigidDynamic* dynamic = body->
actor->is<PxRigidDynamic>()) {
640 if (isKinematic(dynamic)) dynamic->setKinematicTarget(pose);
646 Body* body = g().body(bodyId);
647 if (!g().isValid() || body ==
nullptr || !(mass > 0.0f) || !std::isfinite(mass))
return;
648 PxRigidDynamic* dynamic = body->
actor->is<PxRigidDynamic>();
649 if (dynamic ==
nullptr || isKinematic(dynamic))
return;
650 PxRigidBodyExt::setMassAndUpdateInertia(*dynamic, mass);
655 Body* body = g().body(bodyId);
656 if (!g().isValid() || body ==
nullptr)
return;
657 PxRigidDynamic* dynamic = body->
actor->is<PxRigidDynamic>();
658 if (dynamic ==
nullptr)
return;
659 const PxVec3 v(vx, vy, vz);
660 if (!v.isFinite())
return;
661 if (isKinematic(dynamic)) {
665 dynamic->setLinearVelocity(v,
true);
671 Body* body = g().body(bodyId);
672 if (!g().isValid() || body ==
nullptr)
return 0;
673 const PxTransform pose = body->
actor->getGlobalPose();
675 if (
const PxRigidDynamic* dynamic = body->
actor->is<PxRigidDynamic>()) {
676 v = isKinematic(dynamic) ? body->
kinematicVelocity : dynamic->getLinearVelocity();
678 g().queryBuffer = {pose.p.x, pose.p.y, pose.p.z, pose.q.x, pose.q.y, pose.q.z, pose.q.w, v.x, v.y, v.z};
684 PxRigidDynamic* dynamic = dynamicOf(bodyId);
685 if (!g().isValid() || dynamic ==
nullptr || isKinematic(dynamic))
return 0;
686 const float mass = dynamic->getMass();
687 if (!(mass > 0.0f))
return 0;
688 const PxVec3 w = dynamic->getAngularVelocity();
689 g().queryBuffer = {mass, w.x, w.y, w.z};
695 PxRigidDynamic* dynamic = dynamicOf(bodyId);
696 if (!g().isValid() || dynamic ==
nullptr || isKinematic(dynamic))
return 0;
697 const float mass = dynamic->getMass();
698 if (!(mass > 0.0f))
return 0;
699 const PxVec3 centre = (dynamic->getGlobalPose() * dynamic->getCMassLocalPose()).p;
702 const PxVec3 inertia = dynamic->getMassSpaceInertiaTensor();
703 const PxQuat frame = dynamic->getCMassLocalPose().q;
704 const PxRigidDynamicLockFlags locked = dynamic->getRigidDynamicLockFlags();
705 const float inf = std::numeric_limits<float>::infinity();
706 const auto moment = [&](
const PxVec3& axis,
bool isLocked) {
707 if (isLocked)
return inf;
708 const PxVec3 a = frame.rotateInv(axis);
709 const auto inv = [](
float i) {
return i > 0.0f ? 1.0f / i : 0.0f; };
710 const float weighed = a.x * a.x * inv(inertia.x) + a.y * a.y * inv(inertia.y) + a.z * a.z * inv(inertia.z);
711 return weighed > 0.0f ? 1.0f / weighed : inf;
713 g().queryBuffer = {mass, centre.x, centre.y, centre.z,
714 moment(PxVec3(1, 0, 0),
static_cast<bool>(locked & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)),
715 moment(PxVec3(0, 1, 0),
static_cast<bool>(locked & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)),
716 moment(PxVec3(0, 0, 1),
static_cast<bool>(locked & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z))};
721void physics3d_addForce(uint32_t bodyId,
float fx,
float fy,
float fz,
float px,
float py,
float pz) {
722 PxRigidDynamic* dynamic = dynamicOf(bodyId);
723 if (!g().isValid() || dynamic ==
nullptr || isKinematic(dynamic))
return;
725 if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) PxRigidBodyExt::addForceAtPos(*dynamic, PxVec3(fx, fy, fz), PxVec3(px, py, pz), PxForceMode::eFORCE,
true);
726 else dynamic->addForce(PxVec3(fx, fy, fz), PxForceMode::eFORCE,
true);
731 PxRigidDynamic* dynamic = dynamicOf(bodyId);
732 if (!g().isValid() || dynamic ==
nullptr || isKinematic(dynamic))
return;
733 const PxVec3 impulse(ix, iy, iz);
734 if (!impulse.isFinite())
return;
735 if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) PxRigidBodyExt::addForceAtPos(*dynamic, impulse, PxVec3(px, py, pz), PxForceMode::eIMPULSE,
true);
736 else dynamic->addForce(impulse, PxForceMode::eIMPULSE,
true);
741 PxRigidDynamic* dynamic = dynamicOf(bodyId);
742 if (!g().isValid() || dynamic ==
nullptr || isKinematic(dynamic))
return;
743 dynamic->addTorque(PxVec3(ix, iy, iz), PxForceMode::eIMPULSE,
true);
748 PxRigidDynamic* dynamic = dynamicOf(bodyId);
749 if (!g().isValid() || dynamic ==
nullptr || isKinematic(dynamic))
return;
750 dynamic->setAngularVelocity(PxVec3(wx, wy, wz),
true);
755 if (!g().isValid())
return;
756 g().scene->setGravity(PxVec3(gx, gy, gz));
761 PxRigidDynamic* dynamic = dynamicOf(bodyId);
762 if (!g().isValid() || dynamic ==
nullptr || isKinematic(dynamic))
return;
763 if (awake) dynamic->wakeUp();
else dynamic->putToSleep();
768 const PxRigidDynamic* dynamic = dynamicOf(bodyId);
769 if (!g().isValid() || dynamic ==
nullptr || isKinematic(dynamic))
return 0;
770 return dynamic->isSleeping() ? 0 : 1;
775 PxRigidDynamic* dynamic = dynamicOf(bodyId);
776 if (!g().isValid() || dynamic ==
nullptr || isKinematic(dynamic))
return;
777 dynamic->addTorque(PxVec3(tx, ty, tz), PxForceMode::eFORCE,
true);
#define EMSCRIPTEN_KEEPALIVE
void physics3d_setSolver(int velocityIterations, int positionIterations, int allowSleep, float bounceThreshold)
uint32_t physics3d_addBox(uint32_t entity, float hx, float hy, float hz, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor, float cx, float cy, float cz)
uintptr_t physics3d_sensorEnters()
size_t physics3d_queryResultBytes()
size_t physics3d_sensorEntersBytes()
void physics3d_addImpulse(uint32_t bodyId, float ix, float iy, float iz, float px, float py, float pz)
uintptr_t physics3d_queryResult()
void physics3d_setAwake(uint32_t bodyId, int awake)
uint32_t physics3d_addCapsule(uint32_t entity, float radius, float halfHeight, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor, float cx, float cy, float cz)
uint32_t physics3d_addMeshBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount, uintptr_t indexPtr, uint32_t indexCount, float px, float py, float pz, float qx, float qy, float qz, float qw, uint32_t layer, float friction, float restitution)
Registers imported geometry as a collider.
size_t physics3d_sensorExitsBytes()
size_t physics3d_contactEnterMassesBytes()
uint32_t physics3d_addConvexBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor)
Registers the convex hull of imported geometry as a collider.
uintptr_t physics3d_characterHits()
void physics3d_setTransform(uint32_t bodyId, float px, float py, float pz, float qx, float qy, float qz, float qw)
void physics3d_setMass(uint32_t bodyId, float mass)
size_t physics3d_contactExitsBytes()
uint32_t physics3d_addCompound(uint32_t entity, uintptr_t partsPtr, uint32_t count, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor, float mass)
void physics3d_addForce(uint32_t bodyId, float fx, float fy, float fz, float px, float py, float pz)
void physics3d_shutdown()
size_t physics3d_contactEnterSpeedsBytes()
void physics3d_addTorque(uint32_t bodyId, float tx, float ty, float tz)
A torque of (tx, ty, tz) newton metres, over the next step.
void physics3d_step(float dt, int collisionSteps)
Advance the world, then refill the transform buffer with every active body.
void physics3d_init(float gx, float gy, float gz, uint32_t)
size_t physics3d_contactEntersBytes()
void physics3d_removeBody(uint32_t bodyId)
int physics3d_isAwake(uint32_t bodyId)
uint32_t physics3d_addSphere(uint32_t entity, float radius, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor, float cx, float cy, float cz)
int physics3d_getBodyDynamics(uint32_t bodyId)
uintptr_t physics3d_contactEnters()
uintptr_t physics3d_transforms()
int physics3d_getBodyMassData(uint32_t bodyId)
void physics3d_setAngularVelocity(uint32_t bodyId, float wx, float wy, float wz)
uintptr_t physics3d_sensorExits()
size_t physics3d_characterHitsBytes()
int physics3d_getBodyState(uint32_t bodyId)
uintptr_t physics3d_contactEnterSpeeds()
void physics3d_setLinearVelocity(uint32_t bodyId, float vx, float vy, float vz)
void physics3d_addAngularImpulse(uint32_t bodyId, float ix, float iy, float iz)
void physics3d_optimize()
void physics3d_setGravity(float gx, float gy, float gz)
uintptr_t physics3d_contactExits()
void physics3d_setLayerMask(uint32_t layer, uint32_t mask)
Declares which layers layer layer collides with.
uintptr_t physics3d_contactEnterMasses()
size_t physics3d_transformsBytes()
The one 3D world the PhysX backend steps.
The Jolt module's entry points, declared once for both platforms.
static constexpr int MAX_OVERLAP_HITS
constexpr uint32_t LAYER_COUNT
Sixteen layers, the same number the Jolt backend and the 2D world name.
constexpr uint32_t KIND_CHARACTER
kKindWord bits.
PxMaterial * defaultMaterial()
Friction 0.6, no bounce: the default physics material.
uint32_t entityOf(const physx::PxActor *actor)
The entity an actor speaks for, or 0.
What the module knows about a body beyond what PhysX holds.
physx::PxRigidActor * actor
physx::PxVec3 kinematicVelocity
bool hasKinematicVelocity