Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
PhysXModuleEntry.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
19#include "./PhysXWorld.hpp"
21
22#include <algorithm>
23#include <cmath>
24#include <cstring>
25#include <limits>
26
27using namespace physx;
32
33namespace {
34
35PxDefaultAllocator& allocator() { static PxDefaultAllocator a; return a; }
36PxDefaultErrorCallback& errors() { static PxDefaultErrorCallback e; return e; }
37PxFoundation* gFoundation = nullptr;
38PxPhysics* gPhysics = nullptr;
39
40World& g() { return px3::world(); }
41
42// The usual defaults for this solver (world settings and per body).
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;
58constexpr PxU32 MAX_OVERLAP_HITS = 256;
59
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;
67 // One friction for both, as the SDK authors one; Average is the usual default
68 // combine for both friction and bounce.
69 PxMaterial* m = gPhysics->createMaterial(friction, friction, restitution);
70 m->setFrictionCombineMode(PxCombineMode::eAVERAGE);
71 m->setRestitutionCombineMode(PxCombineMode::eAVERAGE);
72 g().materials[key] = m;
73 return m;
74}
75
76PxFilterData filterData(uint32_t layer, uint32_t kind) {
77 PxFilterData d;
78 d.word0 = layer;
79 d.word1 = kind;
80 return d;
81}
82
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;
96 }
97 flags = PxPairFlag::eCONTACT_DEFAULT | PxPairFlag::eDETECT_CCD_CONTACT;
98 if (((d0.word1 | d1.word1) & px3::KIND_CHARACTER) == 0) {
99 flags |= PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_LOST
100 | PxPairFlag::eNOTIFY_CONTACT_POINTS | PxPairFlag::ePRE_SOLVER_VELOCITY;
101 }
102 return PxFilterFlag::eDEFAULT;
103}
104
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);
114 }
115 }
116 return velocity;
117}
118
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();
127}
128
130class ContactRecorder final : public PxSimulationEventCallback {
131public:
132 void onContact(const PxContactPairHeader& header, const PxContactPair* pairs, PxU32 count) override {
133 // A removed actor's pointer is not to be read; its side is nobody.
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)
137 ? 0u : px3::entityOf(header.actors[1]);
138 if (a == 0 && b == 0) return;
139 // This callback comes after the solver: the velocities the two had as they met are in the extra data, one set
140 // for each pair, asked for with ePRE_SOLVER_VELOCITY.
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;
145 }
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) {
152 // PhysX points from the second shape to the first; the
153 // buffer, like Jolt's, points from A to B.
154 normal = -point.normal;
155 position = point.position;
156 }
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,
160 });
161 // How fast A closed on B at the point, along the normal from A to B; 0 where PhysX gave no velocities.
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);
166 }
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());
170 }
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));
174 }
175 }
176 }
177
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)
184 ? 0u : px3::entityOf(pair.otherActor);
185 if (sensor == 0 && other == 0) continue;
186 // The sensor first, as the Jolt module writes it.
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));
193 }
194 }
195
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 {}
200};
201
202ContactRecorder& recorder() { static ContactRecorder r; return r; }
203
204struct BodyMotion {
205 int motion = 0;
206 float gravityScale = 1.0f;
207 float linearDamping = 0.0f;
208 float angularDamping = 0.0f;
209 int fixedRotation = 0;
210 uint32_t layer = 0;
211 int continuous = 0;
212};
213
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);
217}
218
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);
230 } else {
231 dynamic = gPhysics->createRigidDynamic(pose);
232 actor = dynamic;
233 }
234 if (actor == nullptr) return 0;
235
236 // A trigger is still found by queries: queries hit triggers by default.
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);
248 shape->release();
249
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;
256
257 if (dynamic != nullptr) {
258 if (how.motion == 1) dynamic->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true);
259 if (isSensor != 0) {
260 // A trigger has no volume to weigh; it needs a mass all the same.
261 dynamic->setMass(1.0f);
262 dynamic->setMassSpaceInertiaTensor(PxVec3(1.0f));
263 } else {
264 PxRigidBodyExt::updateMassAndInertia(*dynamic, DENSITY);
265 }
266 dynamic->setLinearDamping(how.linearDamping);
267 dynamic->setAngularDamping(how.angularDamping);
268 dynamic->setMaxAngularVelocity(MAX_ANGULAR_VELOCITY);
269 dynamic->setMaxDepenetrationVelocity(MAX_DEPENETRATION_VELOCITY);
270 // A threshold of 0 is energy no body falls below: it never sleeps.
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);
276 }
277 // A kinematic body follows its target exactly; sweeping it is an error in PhysX.
278 if (how.continuous != 0 && how.motion == 2) {
279 dynamic->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true);
280 }
281 if (how.gravityScale != 1.0f) actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true);
282 }
283
284 const uint32_t id = g().nextBodyId++;
285 record->id = id;
286 actor->userData = record.get();
287 g().scene->addActor(*actor);
288 g().bodies[id] = std::move(record);
289 return id;
290}
291
294PxVec3 offset(float cx, float cy, float cz) {
295 const PxVec3 v(cx, cy, cz);
296 return v.isFinite() ? v : PxVec3(0.0f);
297}
298
300const PxQuat& capsuleUpright() {
301 static const PxQuat q(PxHalfPi, PxVec3(0.0f, 0.0f, 1.0f));
302 return q;
303}
304
305PxRigidDynamic* dynamicOf(uint32_t bodyId) {
306 Body* body = g().body(bodyId);
307 return body ? body->actor->is<PxRigidDynamic>() : nullptr;
308}
309
310bool isKinematic(const PxRigidDynamic* dynamic) {
311 return dynamic->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC;
312}
313
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)) {
323 if (!body.hasKinematicVelocity) continue;
324 PxTransform target = dynamic->getGlobalPose();
325 target.p += body.kinematicVelocity * h;
326 dynamic->setKinematicTarget(target);
327 } else if (body.gravityScale != 1.0f && !dynamic->isSleeping()) {
328 dynamic->addForce(gravity * body.gravityScale, PxForceMode::eACCELERATION, false);
329 }
330 }
331}
332
333} // namespace
334
336World& world() { static World instance; return instance; }
337PxPhysics& physics() { return *gPhysics; }
338PxMaterial* defaultMaterial() { return material(0.6f, 0.0f); }
339} // namespace esengine::physics3d_physx
340
341extern "C" {
342
343// World lifecycle
344
346void physics3d_init(float gx, float gy, float gz, uint32_t) {
347 if (g().isValid()) return;
348 // Foundation and SDK are process-wide, and PhysX allows one foundation: a
349 // world built after a shutdown reuses them.
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;
355 // No PxInitExtensions: it registers the serializers (and with them the
356 // metadata of every PhysX type), and joints need neither without PVD.
357 }
358 // No worker threads: a wasm module has none, and the tasks run on the
359 // thread that steps.
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);
373}
374
377 if (!g().isValid()) return;
378 for (auto& entry : g().joints) entry.second.joint->release();
379 g().joints.clear();
380 g().characters.clear();
381 if (g().controllers) g().controllers->release(); // releases every controller
382 g().controllers = nullptr;
383 for (auto& entry : g().bodies) entry.second->actor->release();
384 g().bodies.clear();
385 g().scene->release();
386 g().scene = nullptr;
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();
397}
398
400int physics3d_isReady() { return g().isValid() ? 1 : 0; }
401
403void physics3d_setLayerMask(uint32_t layer, uint32_t mask) {
404 if (layer < px3::LAYER_COUNT) g().masks[layer] = mask;
405}
406
408void physics3d_setSolver(int velocityIterations, int positionIterations, int allowSleep,
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);
414}
415
417void physics3d_step(float dt, int collisionSteps) {
418 if (!g().isValid() || dt <= 0.0f) return;
419 // No character moved this step: what the last one met has been read, and is not told again.
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) {
430 beforeSubstep(h);
431 g().scene->simulate(h);
432 g().scene->fetchResults(true);
433 }
434
435 PxU32 count = 0;
436 PxActor** active = g().scene->getActiveActors(count);
437 std::vector<float>& out = g().transformBuffer;
438 out.clear();
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);
444 if (body->character) continue; // its pose comes back from moveCharacter
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,
449 });
450 }
451 g().characterHitsStale = true;
452}
453
456 if (g().isValid()) g().scene->forceRebuildDynamicTree(PX_SCENE_PRUNER_STATIC);
457}
458
459// Bodies
460
462uint32_t physics3d_addCompound(uint32_t entity, uintptr_t partsPtr, uint32_t count,
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;
475 }
476 uint32_t id = 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);
488 if (i == 0) {
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;
493 } else {
494 PxShape* shape = gPhysics->createShape(geometry.any(), *material(friction, restitution), true, flags);
495 if (!shape) { physics3d_removeBody(id); return 0; }
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);
502 shape->release();
503 if (!attached) { physics3d_removeBody(id); return 0; }
504 }
505 }
506 if (auto* dynamic = dynamicOf(id)) {
507 if (!isSensor) {
508 if (mass > 0 && std::isfinite(mass)) PxRigidBodyExt::setMassAndUpdateInertia(*dynamic, mass);
509 else PxRigidBodyExt::updateMassAndInertia(*dynamic, DENSITY);
510 }
511 }
512 return id;
513}
514
516uint32_t physics3d_addBox(uint32_t entity, float hx, float hy, float hz,
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);
528}
529
531uint32_t physics3d_addSphere(uint32_t entity, float radius,
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);
543}
544
546uint32_t physics3d_addCapsule(uint32_t entity, float radius, float halfHeight,
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);
559}
560
562uint32_t physics3d_addMeshBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount,
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; // would read past the vertices
573 }
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;
584 // A triangle soup has no inside, so no mass: always static, as in the Jolt backend.
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);
588 mesh->release(); // the shape holds its own reference
589 return id;
590}
591
593uint32_t physics3d_addConvexBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount,
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;
606 // PhysX keeps at most 255 hull vertices.
607 desc.flags = PxConvexFlag::eCOMPUTE_CONVEX;
608 const PxCookingParams params(gPhysics->getTolerancesScale());
609 PxConvexMesh* mesh = PxCreateConvexMesh(params, desc, gPhysics->getPhysicsInsertionCallback());
610 // Every point on a plane, or all the same, has no hull.
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);
616 mesh->release();
617 return id;
618}
619
621void physics3d_removeBody(uint32_t bodyId) {
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;
626 actor->release(); // leaves the scene as it goes
627 g().bodies.erase(found);
628}
629
631void physics3d_setTransform(uint32_t bodyId, float px, float py, float pz,
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;
637 // A teleport, as SetPositionAndRotation is in Jolt; it wakes the body too.
638 body->actor->setGlobalPose(pose, true);
639 if (PxRigidDynamic* dynamic = body->actor->is<PxRigidDynamic>()) {
640 if (isKinematic(dynamic)) dynamic->setKinematicTarget(pose);
641 }
642}
643
645void physics3d_setMass(uint32_t bodyId, float mass) {
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);
651}
652
654void physics3d_setLinearVelocity(uint32_t bodyId, float vx, float vy, float vz) {
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)) {
662 body->kinematicVelocity = v;
663 body->hasKinematicVelocity = !v.isZero();
664 } else {
665 dynamic->setLinearVelocity(v, true);
666 }
667}
668
670int physics3d_getBodyState(uint32_t bodyId) {
671 Body* body = g().body(bodyId);
672 if (!g().isValid() || body == nullptr) return 0;
673 const PxTransform pose = body->actor->getGlobalPose();
674 PxVec3 v(0.0f);
675 if (const PxRigidDynamic* dynamic = body->actor->is<PxRigidDynamic>()) {
676 v = isKinematic(dynamic) ? body->kinematicVelocity : dynamic->getLinearVelocity();
677 }
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};
679 return 1;
680}
681
683int physics3d_getBodyDynamics(uint32_t bodyId) {
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};
690 return 1;
691}
692
694int physics3d_getBodyMassData(uint32_t bodyId) {
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;
700 // About the body's own axes, as the Jolt world answers: the mass frame may be turned from them, so each axis is
701 // taken into it, its inverse moments weighed along it, and the moment is the inverse of that.
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;
712 };
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))};
717 return 1;
718}
719
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;
724 // A point that is not a number is its centre of mass: pushed there, it turns nothing.
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);
727}
728
730void physics3d_addImpulse(uint32_t bodyId, float ix, float iy, float iz, float px, float py, float pz) {
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);
737}
738
740void physics3d_addAngularImpulse(uint32_t bodyId, float ix, float iy, float iz) {
741 PxRigidDynamic* dynamic = dynamicOf(bodyId);
742 if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return;
743 dynamic->addTorque(PxVec3(ix, iy, iz), PxForceMode::eIMPULSE, true);
744}
745
747void physics3d_setAngularVelocity(uint32_t bodyId, float wx, float wy, float wz) {
748 PxRigidDynamic* dynamic = dynamicOf(bodyId);
749 if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return;
750 dynamic->setAngularVelocity(PxVec3(wx, wy, wz), true);
751}
752
754void physics3d_setGravity(float gx, float gy, float gz) {
755 if (!g().isValid()) return;
756 g().scene->setGravity(PxVec3(gx, gy, gz));
757}
758
760void physics3d_setAwake(uint32_t bodyId, int awake) {
761 PxRigidDynamic* dynamic = dynamicOf(bodyId);
762 if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return;
763 if (awake) dynamic->wakeUp(); else dynamic->putToSleep();
764}
765
767int physics3d_isAwake(uint32_t bodyId) {
768 const PxRigidDynamic* dynamic = dynamicOf(bodyId);
769 if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return 0;
770 return dynamic->isSleeping() ? 0 : 1;
771}
772
774void physics3d_addTorque(uint32_t bodyId, float tx, float ty, float tz) {
775 PxRigidDynamic* dynamic = dynamicOf(bodyId);
776 if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return;
777 dynamic->addTorque(PxVec3(tx, ty, tz), PxForceMode::eFORCE, true);
778}
779
780// Readback
781
783uintptr_t physics3d_transforms() { return reinterpret_cast<uintptr_t>(g().transformBuffer.data()); }
785size_t physics3d_transformsBytes() { return g().transformBuffer.size() * sizeof(float); }
787uintptr_t physics3d_characterHits() { return reinterpret_cast<uintptr_t>(g().characterHitBuffer.data()); }
789size_t physics3d_characterHitsBytes() { return g().characterHitBuffer.size() * sizeof(float); }
791uintptr_t physics3d_contactEnterMasses() { return reinterpret_cast<uintptr_t>(g().contactEnterMassBuffer.data()); }
793size_t physics3d_contactEnterMassesBytes() { return g().contactEnterMassBuffer.size() * sizeof(float); }
795uintptr_t physics3d_contactEnterSpeeds() { return reinterpret_cast<uintptr_t>(g().contactEnterSpeedBuffer.data()); }
797size_t physics3d_contactEnterSpeedsBytes() { return g().contactEnterSpeedBuffer.size() * sizeof(float); }
799uintptr_t physics3d_contactEnters() { return reinterpret_cast<uintptr_t>(g().contactEnterBuffer.data()); }
801size_t physics3d_contactEntersBytes() { return g().contactEnterBuffer.size() * sizeof(float); }
803uintptr_t physics3d_contactExits() { return reinterpret_cast<uintptr_t>(g().contactExitBuffer.data()); }
805size_t physics3d_contactExitsBytes() { return g().contactExitBuffer.size() * sizeof(float); }
807uintptr_t physics3d_sensorEnters() { return reinterpret_cast<uintptr_t>(g().sensorEnterBuffer.data()); }
809size_t physics3d_sensorEntersBytes() { return g().sensorEnterBuffer.size() * sizeof(float); }
811uintptr_t physics3d_sensorExits() { return reinterpret_cast<uintptr_t>(g().sensorExitBuffer.data()); }
813size_t physics3d_sensorExitsBytes() { return g().sensorExitBuffer.size() * sizeof(float); }
815uintptr_t physics3d_queryResult() { return reinterpret_cast<uintptr_t>(g().queryBuffer.data()); }
817size_t physics3d_queryResultBytes() { return g().queryBuffer.size() * sizeof(float); }
818
819} // extern "C"
#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_isReady()
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