Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
PhysXQueries.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
16#include "./PhysXWorld.hpp"
18
19#include <algorithm>
20#include <limits>
21#include <cmath>
22
23using namespace physx;
28
29namespace {
30
31World& g() { return px3::world(); }
32
36class LayerFilter final : public PxQueryFilterCallback {
37public:
38 LayerFilter(uint32_t mask, bool characters, const PxRigidActor* ignore = nullptr, bool touch = false)
39 : mask_(mask == 0 ? 0xFFFFFFFFu : mask), characters_(characters), ignore_(ignore), touch_(touch) {}
40 PxQueryHitType::Enum preFilter(const PxFilterData&, const PxShape* shape, const PxRigidActor* actor,
41 PxHitFlags&) override {
42 if (actor == ignore_) return PxQueryHitType::eNONE;
43 const PxFilterData data = shape->getQueryFilterData();
44 if ((mask_ & (1u << data.word0)) == 0) return PxQueryHitType::eNONE;
45 if (!characters_ && (data.word1 & px3::KIND_CHARACTER) != 0) return PxQueryHitType::eNONE;
46 return touch_ ? PxQueryHitType::eTOUCH : PxQueryHitType::eBLOCK;
47 }
48 PxQueryHitType::Enum postFilter(const PxFilterData&, const PxQueryHit&, const PxShape*,
49 const PxRigidActor*) override {
50 return touch_ ? PxQueryHitType::eTOUCH : PxQueryHitType::eBLOCK;
51 }
52private:
53 uint32_t mask_;
54 bool characters_;
55 const PxRigidActor* ignore_;
56 bool touch_;
57};
58
59PxQueryFilterData queryData(bool touch = false) {
60 PxQueryFilterData data;
61 data.flags = PxQueryFlag::eSTATIC | PxQueryFlag::eDYNAMIC | PxQueryFlag::ePREFILTER;
62 if (touch) data.flags |= PxQueryFlag::eNO_BLOCK;
63 return data;
64}
65
66PxVec3 toVec(const PxExtendedVec3& v) {
67 return PxVec3(static_cast<float>(v.x), static_cast<float>(v.y), static_cast<float>(v.z));
68}
69
72class CharacterFilter final : public PxQueryFilterCallback {
73public:
74 CharacterFilter(uint32_t layer, const PxRigidActor* self) : layer_(layer), self_(self) {}
75 PxQueryHitType::Enum preFilter(const PxFilterData&, const PxShape* shape, const PxRigidActor* actor,
76 PxHitFlags&) override {
77 if (actor == self_) return PxQueryHitType::eNONE;
78 if (shape->getFlags() & PxShapeFlag::eTRIGGER_SHAPE) return PxQueryHitType::eNONE;
79 if (!g().collide(layer_, shape->getQueryFilterData().word0)) return PxQueryHitType::eNONE;
80 return PxQueryHitType::eBLOCK;
81 }
82 PxQueryHitType::Enum postFilter(const PxFilterData&, const PxQueryHit&, const PxShape*,
83 const PxRigidActor*) override {
84 return PxQueryHitType::eBLOCK;
85 }
86private:
87 uint32_t layer_;
88 const PxRigidActor* self_;
89};
90
94class HitReport final : public PxUserControllerHitReport {
95public:
96 Character* moving = nullptr;
97 float dt = 0.0f;
98 float bestUp = -2.0f;
99 PxVec3 bestNormal{0.0f};
100
102 struct Met { const PxRigidActor* actor; PxVec3 at; PxVec3 normal; };
103 std::vector<Met> met;
104
105 void onShapeHit(const PxControllerShapeHit& hit) override {
106 if (hit.actor != nullptr && std::none_of(met.begin(), met.end(), [&](const Met& m) { return m.actor == hit.actor; })) {
107 met.push_back({hit.actor, PxVec3(static_cast<float>(hit.worldPos.x), static_cast<float>(hit.worldPos.y), static_cast<float>(hit.worldPos.z)), hit.worldNormal});
108 }
109 const float up = hit.worldNormal.y;
110 if (up > bestUp) { bestUp = up; bestNormal = hit.worldNormal; }
111 if (moving == nullptr || !(moving->pushForce > 0.0f) || hit.actor == nullptr) return;
112 PxRigidDynamic* dynamic = hit.actor->is<PxRigidDynamic>();
113 if (dynamic == nullptr || (dynamic->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC)) return;
114 PxVec3 push(-hit.worldNormal.x, 0.0f, -hit.worldNormal.z); // never into the floor
115 if (push.normalizeSafe() <= 0.0f || !(dt > 0.0f)) return;
116 // What it takes for the body to keep pace with the character along the
117 // push, and no more than the push strength gives over one step: the
118 // contact Jolt's character solves, with its mMaxStrength as the cap.
119 const float walking = hit.dir.dot(push) * hit.length / dt;
120 const float need = walking - dynamic->getLinearVelocity().dot(push);
121 const float mass = dynamic->getMass();
122 if (!(need > 0.0f) || !(mass > 0.0f)) return;
123 const float dv = std::min(need, moving->pushForce * dt / mass);
124 const PxVec3 at(static_cast<float>(hit.worldPos.x), static_cast<float>(hit.worldPos.y),
125 static_cast<float>(hit.worldPos.z));
126 PxRigidBodyExt::addForceAtPos(*dynamic, push * (dv * mass), at, PxForceMode::eIMPULSE, true);
127 }
128 void onControllerHit(const PxControllersHit& hit) override {
129 if (hit.worldNormal.y > bestUp) { bestUp = hit.worldNormal.y; bestNormal = hit.worldNormal; }
130 }
131 void onObstacleHit(const PxControllerObstacleHit&) override {}
132};
133
134HitReport& hitReport() { static HitReport r; return r; }
135
138void noteCharacterMeetings(Character& c, const std::vector<HitReport::Met>& met, const PxVec3& velocity) {
139 if (g().characterHitsStale) { g().characterHitBuffer.clear(); g().characterHitsStale = false; }
140 std::vector<const PxRigidActor*> now;
141 const float own = c.mass > 0.0f ? 1.0f / c.mass : 0.0f;
142 for (const HitReport::Met& m : met) {
143 now.push_back(m.actor);
144 if (std::find(c.touching.begin(), c.touching.end(), m.actor) != c.touching.end()) continue;
145 float other = 0.0f;
146 PxVec3 moving(0.0f);
147 if (const PxRigidDynamic* d = m.actor->is<PxRigidDynamic>()) {
148 if (!(d->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC)) { other = d->getInvMass(); moving = d->getLinearVelocity(); }
149 }
150 const float both = own + other;
151 const float closing = -(velocity - moving).dot(m.normal);
152 g().characterHitBuffer.insert(g().characterHitBuffer.end(), {
153 static_cast<float>(c.entity), static_cast<float>(px3::entityOf(m.actor)),
154 m.at.x, m.at.y, m.at.z, m.normal.x, m.normal.y, m.normal.z,
155 std::max(closing, 0.0f), both > 0.0f ? 1.0f / both : std::numeric_limits<float>::infinity(),
156 });
157 }
158 c.touching.swap(now);
159}
160
162class MovableFilter final : public PxQueryFilterCallback {
163public:
164 MovableFilter(uint32_t layer, const PxRigidActor* self) : layer_(layer), self_(self) {}
165 PxQueryHitType::Enum preFilter(const PxFilterData&, const PxShape* shape, const PxRigidActor* actor,
166 PxHitFlags&) override {
167 if (actor == self_ || (shape->getFlags() & PxShapeFlag::eTRIGGER_SHAPE)) return PxQueryHitType::eNONE;
168 const PxRigidDynamic* dynamic = actor->is<PxRigidDynamic>();
169 if (dynamic == nullptr || (dynamic->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC)) {
170 return PxQueryHitType::eNONE;
171 }
172 const PxFilterData data = shape->getQueryFilterData();
173 if ((data.word1 & px3::KIND_CHARACTER) != 0 || !g().collide(layer_, data.word0)) return PxQueryHitType::eNONE;
174 return PxQueryHitType::eBLOCK;
175 }
176 PxQueryHitType::Enum postFilter(const PxFilterData&, const PxQueryHit&, const PxShape*,
177 const PxRigidActor*) override {
178 return PxQueryHitType::eBLOCK;
179 }
180private:
181 uint32_t layer_;
182 const PxRigidActor* self_;
183};
184
189bool movableAhead(PxController& controller, uint32_t layer, const PxVec3& horizontal) {
190 PxVec3 dir = horizontal;
191 const float length = dir.normalizeSafe();
192 if (!(length > 0.0f)) return false;
193 auto& capsule = static_cast<PxCapsuleController&>(controller);
194 const PxCapsuleGeometry geometry(capsule.getRadius() + capsule.getContactOffset(), 0.5f * capsule.getHeight());
195 const PxTransform pose(toVec(controller.getPosition()), PxQuat(PxHalfPi, PxVec3(0.0f, 0.0f, 1.0f)));
196 PxSweepBuffer hit;
197 MovableFilter filter(layer, controller.getActor());
198 PxQueryFilterData data;
199 data.flags = PxQueryFlag::eDYNAMIC | PxQueryFlag::ePREFILTER;
200 return g().scene->sweep(geometry, pose, dir, length + capsule.getContactOffset(), hit,
201 PxHitFlag::eDEFAULT, data, &filter) && hit.hasBlock;
202}
203
206class Behavior final : public PxControllerBehaviorCallback {
207public:
208 PxControllerBehaviorFlags getBehaviorFlags(const PxShape&, const PxActor& actor) override {
209 const PxRigidDynamic* dynamic = actor.is<PxRigidDynamic>();
210 if (dynamic && !(dynamic->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC)) {
211 return PxControllerBehaviorFlag::eCCT_SLIDE;
212 }
213 return PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT;
214 }
215 PxControllerBehaviorFlags getBehaviorFlags(const PxController&) override {
216 return PxControllerBehaviorFlags(0);
217 }
218 PxControllerBehaviorFlags getBehaviorFlags(const PxObstacle&) override {
219 return PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT;
220 }
221};
222
223Behavior& behavior() { static Behavior b; return b; }
224
225void pushHit(uint32_t entity, const PxVec3& point) {
226 g().queryBuffer.insert(g().queryBuffer.end(), {static_cast<float>(entity), point.x, point.y, point.z});
227}
228
230int overlap(const PxGeometry& geometry, const PxVec3& center, uint32_t layerMask) {
231 g().queryBuffer.clear();
232 if (!g().isValid()) return 0;
233 PxOverlapHit hits[256];
234 PxOverlapBuffer buffer(hits, 256);
235 LayerFilter filter(layerMask, true, nullptr, true);
236 if (!g().scene->overlap(geometry, PxTransform(center), buffer, queryData(true), &filter)) return 0;
237 const PxU32 count = buffer.getNbTouches();
238 for (PxU32 i = 0; i < count; ++i) {
239 const PxOverlapHit& hit = buffer.getTouch(i);
240 // The point on the hit shape nearest the query, as Jolt reports the
241 // contact point on the body it found; the centre when it is inside.
242 PxVec3 closest = center;
243 const PxTransform pose = PxShapeExt::getGlobalPose(*hit.shape, *hit.actor);
244 if (PxGeometryQuery::pointDistance(center, hit.shape->getGeometry(), pose, &closest) <= 0.0f) {
245 closest = center;
246 }
247 pushHit(px3::entityOf(hit.actor), closest);
248 }
249 return static_cast<int>(count);
250}
251
252} // namespace
253
254extern "C" {
255
256// Characters
257
259uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,
260 float px, float py, float pz, float maxSlope, float mass,
261 uint32_t layer, float pushForce) {
262 if (!g().isValid() || g().controllers == nullptr || !(radius > 0.0f)) return 0;
263 PxCapsuleControllerDesc desc;
264 desc.radius = radius;
265 desc.height = std::max(2.0f * halfHeight, 1.0e-3f);
266 desc.position = PxExtendedVec3(px, py, pz);
267 desc.upDirection = PxVec3(0.0f, 1.0f, 0.0f);
268 desc.slopeLimit = std::cos(std::clamp(maxSlope, 0.0f, PxHalfPi));
269 desc.stepOffset = 0.0f; // set per move, from the caller's step height
270 // Skin width: a tenth of the radius.
271 desc.contactOffset = std::max(0.1f * radius, 1.0e-3f);
272 desc.material = px3::defaultMaterial();
273 desc.climbingMode = PxCapsuleClimbingMode::eCONSTRAINED;
274 desc.reportCallback = &hitReport();
275 desc.behaviorCallback = &behavior();
276 if (!desc.isValid()) return 0;
277 PxController* controller = g().controllers->createController(desc);
278 if (controller == nullptr) return 0;
279
280 auto character = std::make_unique<Character>();
281 character->controller = controller;
282 character->entity = entity;
283 character->layer = layer;
284 character->pushForce = pushForce;
285 character->mass = mass > 0.0f ? mass : 70.0f;
286 character->body = std::make_unique<Body>();
287 character->body->entity = entity;
288 character->body->layer = layer;
289 character->body->character = true;
290 PxRigidDynamic* actor = controller->getActor();
291 character->body->actor = actor;
292 actor->userData = character->body.get();
293 PxShape* shape = nullptr;
294 if (actor->getShapes(&shape, 1) == 1 && shape != nullptr) {
295 PxFilterData data;
296 data.word0 = layer;
297 data.word1 = px3::KIND_CHARACTER;
298 shape->setSimulationFilterData(data);
299 shape->setQueryFilterData(data);
300 }
301 const uint32_t id = g().nextCharacterId++;
302 g().characters[id] = std::move(character);
303 return id;
304}
305
307void physics3d_removeCharacter(uint32_t characterId) {
308 auto found = g().characters.find(characterId);
309 if (found == g().characters.end()) return;
310 found->second->controller->getActor()->userData = nullptr;
311 found->second->controller->release();
312 g().characters.erase(found);
313}
314
316void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,
317 float dt, float stepUp, float stepDown) {
318 g().queryBuffer.clear();
319 auto found = g().characters.find(characterId);
320 if (!g().isValid() || found == g().characters.end()) return;
321 Character& c = *found->second;
322 PxController& controller = *c.controller;
323
324 // The vertical speed is the caller's, carried between moves: `vy = 0` walks.
325 float vertical = c.verticalSpeed;
326 if (vy != 0.0f) vertical = vy;
327 else if (c.grounded) vertical = 0.0f;
328 else vertical += g().scene->getGravity().y * dt;
329
330 const bool pushing = movableAhead(controller, c.layer, PxVec3(vx, 0.0f, vz) * dt);
331 controller.setStepOffset(pushing ? 0.0f : std::max(stepUp, 0.0f));
332 CharacterFilter filter(c.layer, controller.getActor());
333 const PxControllerFilters filters(nullptr, &filter, nullptr);
334 HitReport& report = hitReport();
335 report.moving = &c;
336 report.dt = dt;
337 report.bestUp = -2.0f;
338 report.bestNormal = PxVec3(0.0f);
339 report.met.clear();
340
341 const PxVec3 startedAt = toVec(controller.getPosition());
342 PxControllerCollisionFlags flags = controller.move(PxVec3(vx, vertical, vz) * dt, 1.0e-4f, dt, filters);
343 bool grounded = flags & PxControllerCollisionFlag::eCOLLISION_DOWN;
344 // Stick to the floor walking down a slope or off a step, as Jolt's
345 // ExtendedUpdate does; give the probe back if there is no floor in reach.
346 if (!grounded && c.grounded && vertical <= 0.0f && stepDown > 0.0f) {
347 const PxExtendedVec3 before = controller.getPosition();
348 const PxControllerCollisionFlags probe =
349 controller.move(PxVec3(0.0f, -stepDown, 0.0f), 1.0e-4f, dt, filters);
350 if (probe & PxControllerCollisionFlag::eCOLLISION_DOWN) grounded = true;
351 else controller.setPosition(before);
352 }
353 // A ceiling ends a jump.
354 if ((flags & PxControllerCollisionFlag::eCOLLISION_UP) && vertical > 0.0f) vertical = 0.0f;
355 report.moving = nullptr;
356 noteCharacterMeetings(c, report.met, PxVec3(vx, vertical, vz));
357
358 c.grounded = grounded;
359 c.verticalSpeed = vertical;
360 const PxVec3 position = toVec(controller.getPosition());
361 // Jolt's ground states: 0 on ground, 1 on ground too steep, 3 in the air.
362 const float slopeLimit = controller.getSlopeLimit();
363 float state = 3.0f;
364 PxVec3 normal(0.0f);
365 if (grounded) {
366 state = 0.0f;
367 normal = report.bestUp > 0.0f ? report.bestNormal : PxVec3(0.0f, 1.0f, 0.0f);
368 } else if (report.bestUp > 0.0f && report.bestUp < slopeLimit) {
369 state = 1.0f;
370 normal = report.bestNormal;
371 }
372 // The velocity it reached, not the one it asked for.
373 const PxVec3 velocity = dt > 0.0f ? (position - startedAt) / dt : PxVec3(0.0f);
374 g().queryBuffer = {position.x, position.y, position.z, state, normal.x, normal.y, normal.z,
375 velocity.x, velocity.y, velocity.z};
376}
377
379void physics3d_setCharacterPosition(uint32_t characterId, float px, float py, float pz) {
380 auto found = g().characters.find(characterId);
381 if (found == g().characters.end()) return;
382 found->second->controller->setPosition(PxExtendedVec3(px, py, pz));
383 found->second->verticalSpeed = 0.0f;
384 found->second->grounded = false;
385}
386
387// Queries
388
390int physics3d_overlapSphere(float px, float py, float pz, float radius, uint32_t layerMask) {
391 if (!(radius > 0.0f)) { g().queryBuffer.clear(); return 0; }
392 return overlap(PxSphereGeometry(radius), PxVec3(px, py, pz), layerMask);
393}
394
396int physics3d_overlapBox(float px, float py, float pz, float hx, float hy, float hz, uint32_t layerMask) {
397 if (!(hx > 0.0f && hy > 0.0f && hz > 0.0f)) { g().queryBuffer.clear(); return 0; }
398 return overlap(PxBoxGeometry(hx, hy, hz), PxVec3(px, py, pz), layerMask);
399}
400
402int physics3d_sphereCast(float px, float py, float pz, float radius,
403 float dx, float dy, float dz, uint32_t layerMask) {
404 g().queryBuffer.clear();
405 if (!g().isValid() || !(radius > 0.0f)) return 0;
406 PxVec3 dir(dx, dy, dz);
407 const float length = dir.normalizeSafe();
408 if (!(length > 0.0f)) return 0;
409 PxSweepBuffer hit;
410 LayerFilter filter(layerMask, false);
411 if (!g().scene->sweep(PxSphereGeometry(radius), PxTransform(PxVec3(px, py, pz)), dir, length, hit,
412 PxHitFlag::ePOSITION | PxHitFlag::eNORMAL, queryData(), &filter)
413 || !hit.hasBlock) return 0;
414 const PxSweepHit& b = hit.block;
415 g().queryBuffer = {static_cast<float>(px3::entityOf(b.actor)), b.distance / length,
416 b.position.x, b.position.y, b.position.z, b.normal.x, b.normal.y, b.normal.z};
417 return 1;
418}
419
420namespace {
422static PxQuat turnOf(float qx, float qy, float qz, float qw) {
423 const PxQuat q(qx, qy, qz, qw);
424 const float length = q.magnitude();
425 return std::isfinite(length) && length > 1e-6f ? q * (1.0f / length) : PxQuat(PxIdentity);
426}
427
429static int sweepQuery(const PxGeometry& shape, const PxTransform& pose, float dx, float dy, float dz, uint32_t layerMask) {
430 PxVec3 dir(dx, dy, dz);
431 const float length = dir.normalizeSafe();
432 if (!(length > 0.0f)) return 0;
433 PxSweepBuffer hit;
434 LayerFilter filter(layerMask, false);
435 if (!g().scene->sweep(shape, pose, dir, length, hit, PxHitFlag::ePOSITION | PxHitFlag::eNORMAL, queryData(), &filter)
436 || !hit.hasBlock) return 0;
437 const PxSweepHit& b = hit.block;
438 g().queryBuffer = {static_cast<float>(px3::entityOf(b.actor)), b.distance / length,
439 b.position.x, b.position.y, b.position.z, b.normal.x, b.normal.y, b.normal.z};
440 return 1;
441}
442} // namespace
443
445int physics3d_raycastAll(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t maxHits) {
446 g().queryBuffer.clear();
447 if (!g().isValid() || maxHits == 0) return 0;
448 PxVec3 dir(dx, dy, dz);
449 const float length = dir.normalizeSafe();
450 if (!(length > 0.0f)) return 0;
451 const PxVec3 origin(ox, oy, oz);
452 // Where the line goes into each actor, from its start; and where it comes out, by going in from its end.
453 PxRaycastHit forwardHits[64], backwardHits[64];
454 PxRaycastBuffer forward(forwardHits, 64), backward(backwardHits, 64);
455 LayerFilter filter(layerMask, false, nullptr, true);
456 const PxHitFlags wanted = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL;
457 g().scene->raycast(origin, dir, length, forward, wanted, queryData(true), &filter);
458 g().scene->raycast(origin + dir * length, -dir, length, backward, wanted, queryData(true), &filter);
459 struct Crossing { const PxRigidActor* actor; float entry; float exit; PxVec3 normal; };
460 std::vector<Crossing> crossings;
461 for (PxU32 i = 0; i < forward.getNbTouches(); ++i) {
462 const PxRaycastHit& hit = forward.getTouch(i);
463 const float f = hit.distance / length;
464 auto same = std::find_if(crossings.begin(), crossings.end(), [&](const Crossing& c) { return c.actor == hit.actor; });
465 if (same == crossings.end()) crossings.push_back({hit.actor, f, 1.0f, hit.normal});
466 else if (f < same->entry) { same->entry = f; same->normal = hit.normal; }
467 }
468 for (Crossing& c : crossings) {
469 float exit = 1.0f;
470 for (PxU32 i = 0; i < backward.getNbTouches(); ++i) {
471 const PxRaycastHit& hit = backward.getTouch(i);
472 if (hit.actor == c.actor) exit = std::min(exit, 1.0f - hit.distance / length);
473 }
474 c.exit = std::max(exit, c.entry);
475 }
476 std::sort(crossings.begin(), crossings.end(), [](const Crossing& a, const Crossing& b) { return a.entry < b.entry; });
477 if (crossings.size() > maxHits) crossings.resize(maxHits);
478 for (const Crossing& c : crossings) {
479 const PxVec3 point = origin + dir * (c.entry * length);
480 g().queryBuffer.insert(g().queryBuffer.end(), {
481 static_cast<float>(px3::entityOf(c.actor)), c.entry, c.exit, point.x, point.y, point.z,
482 c.normal.x, c.normal.y, c.normal.z,
483 });
484 }
485 return static_cast<int>(crossings.size());
486}
487
489int physics3d_boxCast(float px, float py, float pz, float hx, float hy, float hz,
490 float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {
491 g().queryBuffer.clear();
492 if (!g().isValid() || !(hx > 0.0f) || !(hy > 0.0f) || !(hz > 0.0f)) return 0;
493 return sweepQuery(PxBoxGeometry(hx, hy, hz), PxTransform(PxVec3(px, py, pz), turnOf(qx, qy, qz, qw)), dx, dy, dz, layerMask);
494}
495
497int physics3d_capsuleCast(float px, float py, float pz, float radius, float halfHeight,
498 float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {
499 g().queryBuffer.clear();
500 if (!g().isValid() || !(radius > 0.0f) || !(halfHeight >= 0.0f)) return 0;
501 if (halfHeight == 0.0f) return physics3d_sphereCast(px, py, pz, radius, dx, dy, dz, layerMask);
502 // A PhysX capsule lies along its x; turned a quarter about z it stands along y, as the Jolt world's and a
503 // character's do.
504 const PxQuat upright(PxHalfPi, PxVec3(0.0f, 0.0f, 1.0f));
505 return sweepQuery(PxCapsuleGeometry(radius, halfHeight), PxTransform(PxVec3(px, py, pz), turnOf(qx, qy, qz, qw) * upright),
506 dx, dy, dz, layerMask);
507}
508
510int physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask) {
511 return physics3d_raycastWith(ox, oy, oz, dx, dy, dz, layerMask, 0);
512}
513
515int physics3d_raycastWith(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask,
516 uint32_t flags) {
517 g().queryBuffer.clear();
518 if (!g().isValid()) return 0;
519 PxVec3 dir(dx, dy, dz);
520 const float length = dir.normalizeSafe();
521 if (!(length > 0.0f)) return 0;
522 const PxVec3 origin(ox, oy, oz);
523 float best = length;
524 PxVec3 point(0.0f), normal(0.0f);
525 uint32_t entity = 0;
526 bool found = false;
527 PxRaycastBuffer hit;
528 LayerFilter filter(layerMask, false);
529 if (g().scene->raycast(origin, dir, length, hit, PxHitFlag::ePOSITION | PxHitFlag::eNORMAL, queryData(), &filter)
530 && hit.hasBlock) {
531 best = hit.block.distance;
532 point = origin + dir * best;
533 normal = hit.block.normal;
534 entity = px3::entityOf(hit.block.actor);
535 found = true;
536 }
537 // Characters where they are NOW: a controller's actor reaches the pose a move gave it only at the next simulate, so
538 // the scene would answer with last step's capsule. Cast against each one directly, as the Jolt backend does.
539 if ((flags & 1u) != 0) {
540 const PxQuat upright(PxHalfPi, PxVec3(0.0f, 0.0f, 1.0f));
541 const uint32_t mask = layerMask == 0 ? 0xFFFFFFFFu : layerMask;
542 for (const auto& entry : g().characters) {
543 const Character& c = *entry.second;
544 if ((mask & (1u << c.layer)) == 0) continue;
545 auto& capsule = static_cast<PxCapsuleController&>(*c.controller);
546 const PxCapsuleGeometry geometry(capsule.getRadius(), 0.5f * capsule.getHeight());
547 const PxTransform pose(toVec(c.controller->getPosition()), upright);
548 PxRaycastHit h;
549 if (PxGeometryQuery::raycast(origin, dir, geometry, pose, best, PxHitFlag::ePOSITION | PxHitFlag::eNORMAL, 1, &h) == 0) continue;
550 if (h.distance >= best && found) continue;
551 best = h.distance;
552 point = origin + dir * best;
553 normal = h.normal;
554 entity = c.entity;
555 found = true;
556 }
557 }
558 if (!found) return 0;
559 g().queryBuffer = {static_cast<float>(entity), best / length, point.x, point.y, point.z, normal.x, normal.y, normal.z};
560 return 1;
561}
562
563} // extern "C"
#define EMSCRIPTEN_KEEPALIVE
int physics3d_overlapBox(float px, float py, float pz, float hx, float hy, float hz, uint32_t layerMask)
The same for a box, given its half-extents.
int physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask)
void physics3d_removeCharacter(uint32_t characterId)
int physics3d_raycastAll(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t maxHits)
int physics3d_boxCast(float px, float py, float pz, float hx, float hy, float hz, float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask)
void physics3d_setCharacterPosition(uint32_t characterId, float px, float py, float pz)
Puts a character somewhere, rather than moving it there.
void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz, float dt, float stepUp, float stepDown)
int physics3d_overlapSphere(float px, float py, float pz, float radius, uint32_t layerMask)
Everything a sphere at this position overlaps.
int physics3d_raycastWith(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t flags)
The world's nearest hit, or a character's when one is nearer and flags bit 0 asks for them.
int physics3d_sphereCast(float px, float py, float pz, float radius, float dx, float dy, float dz, uint32_t layerMask)
int physics3d_capsuleCast(float px, float py, float pz, float radius, float halfHeight, float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask)
uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight, float px, float py, float pz, float maxSlope, float mass, uint32_t layer, float pushForce)
Registers a character: an upright capsule swept against the world.
The one 3D world the PhysX backend steps.
The Jolt module's entry points, declared once for both platforms.
static void noteCharacterMeetings(uint32_t characterId, const CharacterVirtual &character, Vec3Arg velocity)
Moves a character by its velocity for one step.
static Quat turnOf(float qx, float qy, float qz, float qw)
A turn that is not one - zero, or not a number - is no turn.
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.
std::vector< const physx::PxRigidActor * > touching
float verticalSpeed
The vertical speed between moves; a controller does not fall on its own.