Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qphysxcharactercontroller.cpp
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#include "PxRigidDynamic.h"
8#include "PxShape.h"
9#include "characterkinematic/PxController.h"
10#include "characterkinematic/PxControllerManager.h"
11#include "characterkinematic/PxCapsuleController.h"
12
14#include "qfilterdata_p.h"
18
19#define PHYSX_RELEASE(x)
20 if (x != nullptr) {
21 x->release();
22 x = nullptr;
23 }
24
26
27static physx::PxControllerNonWalkableMode::Enum toPhysXNonWalkableMode(bool slideOnSteepSlopes)
28{
29 return slideOnSteepSlopes
30 ? physx::PxControllerNonWalkableMode::ePREVENT_CLIMBING_AND_FORCE_SLIDING
31 : physx::PxControllerNonWalkableMode::ePREVENT_CLIMBING;
32}
33
34// PhysX takes the cosine of the angle, and 0 there turns the slope limit off
35// for good: it can't be turned back on at runtime. Keep it just above 0.
36static float toPhysXSlopeLimit(float degrees)
37{
38 return std::max(std::cos(qDegreesToRadians(degrees)),
39 std::numeric_limits<float>::epsilon());
40}
41
42// The step offset for PhysX: 0 turns stepping off, a negative value lets the
43// controller pick one from the capsule's size. PhysX won't create a controller
44// whose offset is more than height + 2 * radius, so clamp it below that.
45// sync() calls this every frame with the offset in use as current, so only
46// warn when the clamped offset changes.
47static float resolveStepOffset(float maximumStepHeight, float height, float radius,
48 float current = -1.f)
49{
50 float stepOffset = maximumStepHeight < 0.f ? 0.25f * height : maximumStepHeight;
51 const float limit = height + 2.f * radius;
52 if (stepOffset >= limit) {
53 stepOffset = std::nextafter(limit, 0.f);
54 if (stepOffset != current) {
55 qWarning() << "CharacterController: maximumStepHeight of" << maximumStepHeight
56 << "is at or above the PhysX limit of" << limit
57 << "for a capsule of height" << height << "and radius" << radius
58 << "; clamping the step offset.";
59 }
60 }
61 return stepOffset;
62}
63
65{
66public:
67 ControllerCallback(QPhysicsWorld *worldIn) : world(worldIn) { }
68
69 void onShapeHit(const physx::PxControllerShapeHit &hit) override
70 {
71 QAbstractPhysicsNode *other = static_cast<QAbstractPhysicsNode *>(hit.actor->userData);
72 QCharacterController *trigger =
73 static_cast<QCharacterController *>(hit.controller->getUserData());
74
75 if (!trigger || !other)
76 return;
77
78 // Before either is read: one PxController::move() reports every shape
79 // it hits, and the handler for the first is free to delete a node the
80 // second one points at.
81 if (world->isNodeRemoved(other) || world->isNodeRemoved(trigger))
82 return;
83
84 // A slope too steep to stand on: the normal points up, but less than the
85 // slope limit allows. Walls and ceilings don't count, and like PhysX, only
86 // static bodies that aren't spheres or capsules have a slope limit.
87 if (hit.controller->getNonWalkableMode()
88 == physx::PxControllerNonWalkableMode::ePREVENT_CLIMBING_AND_FORCE_SLIDING
89 && hit.actor->getConcreteType() == physx::PxConcreteType::eRIGID_STATIC) {
90 const auto type = hit.shape->getGeometry().getType();
91 const float upness = hit.worldNormal.dot(hit.controller->getUpDirection());
92 if (type != physx::PxGeometryType::eSPHERE && type != physx::PxGeometryType::eCAPSULE
93 && upness > 0.f && upness < hit.controller->getSlopeLimit()) {
94 sliding = true;
95 }
96 }
97
98 if (!trigger->enableShapeHitCallback())
99 return;
100
101 QVector3D position = QPhysicsUtils::toQtType(physx::toVec3(hit.worldPos));
102 QVector3D impulse = QPhysicsUtils::toQtType(hit.dir * hit.length);
103 QVector3D normal = QPhysicsUtils::toQtType(hit.worldNormal);
104
105 emit trigger->shapeHit(other, position, impulse, normal);
106 }
107 void onControllerHit(const physx::PxControllersHit & /*hit*/) override { }
108 void onObstacleHit(const physx::PxControllerObstacleHit & /*hit*/) override { }
109
110 // Whether the last move() hit a slope it slides down. Read after move(), not
111 // set on the controller from in here, so that it changes at most once a frame.
112 bool sliding = false;
113
114private:
115 QPhysicsWorld *world = nullptr;
116};
117
118// The one shape a controller's actor is created with, its capsule.
119static physx::PxShape *shapeOf(const physx::PxController &controller)
120{
121 physx::PxShape *shape = nullptr;
122 auto *actor = controller.getActor();
123 if (actor && actor->getShapes(&shape, 1) == 1)
124 return shape;
125 return nullptr;
126}
127
128// Decides what a controller's move() is stopped by. Two bodies are kept apart
129// or not by the simulation filter shader in QPhysXWorld, which reads their
130// groups off the simulation filter data of their shapes. A controller does not
131// move through the simulation but through scene queries of its own, which
132// never reach that shader, so the same question is asked here of every shape
133// it sweeps against and of every other controller it meets, off the same data.
136{
137public:
138 physx::PxQueryHitType::Enum preFilter(const physx::PxFilterData & /*queryData*/,
139 const physx::PxShape *shape,
140 const physx::PxRigidActor * /*actor*/,
141 physx::PxHitFlags & /*queryFlags*/) override
142 {
143 const QFilterData other = QPhysicsUtils::toQtType(shape->getSimulationFilterData());
144 return QPhysicsUtils::isFilteredOut(self, other) ? physx::PxQueryHitType::eNONE
145 : physx::PxQueryHitType::eBLOCK;
146 }
147
148 // Never called: the controller is given no ePOSTFILTER flag.
149 physx::PxQueryHitType::Enum postFilter(const physx::PxFilterData & /*queryData*/,
150 const physx::PxQueryHit & /*hit*/,
151 const physx::PxShape * /*shape*/,
152 const physx::PxRigidActor * /*actor*/) override
153 {
154 return physx::PxQueryHitType::eBLOCK;
155 }
156
157 bool filter(const physx::PxController &a, const physx::PxController &b) override
158 {
159 const auto dataOf = [](const physx::PxController &controller) {
160 auto *shape = shapeOf(controller);
161 return shape ? QPhysicsUtils::toQtType(shape->getSimulationFilterData())
162 : QFilterData();
163 };
164 return !QPhysicsUtils::isFilteredOut(dataOf(a), dataOf(b));
165 }
166
167 // This controller's own groups, kept in step with its shape by
168 // QPhysXCharacterController::applyFilterData().
170};
171
173 : QAbstractPhysXNode(frontEnd)
174{
175}
176
178{
179 PHYSX_RELEASE(controller);
180 delete reportCallback;
181 reportCallback = nullptr;
182 delete filter;
183 filter = nullptr;
185}
186
187void QPhysXCharacterController::init(QPhysicsWorld *world, QPhysXWorld * /*physX*/)
188{
189 Q_ASSERT(!controller);
190
191 auto *characterController = static_cast<QCharacterController *>(frontendNode);
192
193 auto shapes = characterController->getCollisionShapesList();
194 if (shapes.length() != 1) {
195 qWarning() << "CharacterController: invalid collision shapes list.";
196 return;
197 }
198 auto *capsule = qobject_cast<QCapsuleShape *>(shapes.first());
199 if (!capsule) {
200 qWarning() << "CharacterController: collision shape is not a capsule.";
201 return;
202 }
203 auto *mgr = world->controllerManager();
204 if (!mgr) {
205 qWarning() << "QtQuick3DPhysics internal error: missing controller manager.";
206 return;
207 }
208
210
211 const QVector3D scale = characterController->sceneScale();
212 const qreal heightScale = scale.y();
213 const qreal radiusScale = scale.x();
214 physx::PxCapsuleControllerDesc desc;
215 reportCallback = new ControllerCallback(world);
216 desc.reportCallback = reportCallback;
217 filter = new ControllerFilter;
218 desc.radius = 0.5f * radiusScale * capsule->diameter();
219 desc.height = heightScale * capsule->height();
220 desc.stepOffset =
221 resolveStepOffset(characterController->maximumStepHeight() * heightScale,
222 desc.height, desc.radius);
223
224 // Initialize the up direction depends on gravity - this is default practice for PhysX
225 // ignore this if the gravity is not set.
226 auto g = characterController->effectiveGravity();
227 if (!g.isNull()) {
228 QVector3D upDirection = -g.normalized();
229 desc.upDirection = QPhysicsUtils::toPhysXType(upDirection);
230
231 // apply initialized rotation in the space as gravity orientation
232 characterController->setGravityOrientation(
233 QQuaternion::rotationTo(QVector3D(0, 1, 0), upDirection));
234 }
235
236 desc.slopeLimit = toPhysXSlopeLimit(characterController->slopeLimit());
237 desc.nonWalkableMode = toPhysXNonWalkableMode(characterController->slideOnSteepSlopes());
238
239 desc.material = material;
240 const QVector3D pos = characterController->scenePosition();
241 desc.position = { pos.x(), pos.y(), pos.z() };
242 // Safe to static_cast since createController will always return a PxCapsuleController
243 // if desc is of type PxCapsuleControllerDesc
244 controller = static_cast<physx::PxCapsuleController *>(mgr->createController(desc));
245
246 if (!controller) {
247 qWarning() << "QtQuick3DPhysics internal error: could not create controller.";
248 return;
249 }
250
251 controller->setUserData(static_cast<void *>(frontendNode));
252
253 auto *actor = controller->getActor();
254 if (actor)
255 actor->userData = characterController;
256 else
257 qWarning() << "QtQuick3DPhysics internal error: CharacterController created without actor.";
258
259 applyFilterData();
260
261 // No collision shape in the userData here, unlike the shapes a body builds,
262 // which is how a trigger tells one body's pairs apart. A controller has
263 // exactly one shape, checked above, so its pairs are one per trigger shape
264 // either way, and pointing at the capsule would go stale: the controller's
265 // shape is never rebuilt, so swapping the capsule would re-report nothing.
266}
267
268void QPhysXCharacterController::sync(float deltaTime,
269 QHash<QQuick3DNode *, QMatrix4x4> & /*transformCache*/)
270{
271 if (!frontendNode)
272 return;
273
274 auto *characterController = static_cast<QCharacterController *>(frontendNode);
275
276 if (controller == nullptr) {
277 // Nothing moves the character without a controller, so drop this frame's
278 // gravity here rather than let it pile up until the controller exists.
279 characterController->clearEnvironmentGravity();
280 return;
281 }
282
283 // Update capsule height, radius, stepOffset (maximumStepHeight)
284 const auto &shapes = characterController->getCollisionShapesList();
285 auto capsule = shapes.length() == 1 ? qobject_cast<QCapsuleShape *>(shapes.front()) : nullptr;
286
287 if (shapes.length() != 1) {
288 qWarning() << "CharacterController: invalid collision shapes list.";
289 } else if (!capsule) {
290 qWarning() << "CharacterController: collision shape is not a capsule.";
291 } else {
292 const QVector3D sceneScale = characterController->sceneScale();
293 const qreal heightScale = sceneScale.y();
294 const qreal radiusScale = sceneScale.x();
295
296 // Update height and radius
297 const float heightNew = heightScale * capsule->height();
298 const float radiusNew = 0.5f * radiusScale * capsule->diameter();
299
300 if (!qIsFinite(heightNew) || heightNew <= 0.f || !qIsFinite(radiusNew)
301 || radiusNew <= 0.f) {
302 qWarning() << "CharacterController: scaled capsule height/radius must be finite "
303 "and positive, ignoring.";
304 } else {
305 if (!qFuzzyCompare(controller->getHeight(), heightNew))
306 controller->resize(heightNew);
307 if (!qFuzzyCompare(controller->getRadius(), radiusNew))
308 controller->setRadius(radiusNew);
309 }
310
311 // Update stepOffset
312 const float stepOffset =
313 resolveStepOffset(characterController->maximumStepHeight() * heightScale, heightNew,
314 radiusNew, controller->getStepOffset());
315 if (!qFuzzyCompare(controller->getStepOffset(), stepOffset))
316 controller->setStepOffset(stepOffset);
317
318 // Update up direction
319 auto pxUpDirection = controller->getUpDirection();
320 QVector3D oldUpDirection = QPhysicsUtils::toQtType(pxUpDirection);
321
322 auto g = characterController->effectiveGravity();
323 if (!g.isNull()) {
324 QVector3D newUpDirection = -g.normalized();
325
326 // Use fuzzy comparison for floating-point vector tolerance
327 if (!qFuzzyCompare(oldUpDirection, newUpDirection)) {
328 controller->setUpDirection(QPhysicsUtils::toPhysXType(newUpDirection));
329
330 QQuaternion delta = QQuaternion::rotationTo(oldUpDirection, newUpDirection);
331 characterController->setGravityOrientation((delta * characterController->gravityOrientation()).normalized());
332 // That ran the controller's bindings, which can delete it.
333 if (!frontendNode)
334 return;
335 }
336 }
337
338 // Update slope limit
339 const float slopeLimit = toPhysXSlopeLimit(characterController->slopeLimit());
340 if (!qFuzzyCompare(controller->getSlopeLimit(), slopeLimit)) {
341 controller->setSlopeLimit(slopeLimit);
342 }
343
344 const auto nonWalkableMode =
345 toPhysXNonWalkableMode(characterController->slideOnSteepSlopes());
346 if (controller->getNonWalkableMode() != nonWalkableMode) {
347 controller->setNonWalkableMode(nonWalkableMode);
348 }
349 }
350
351 // update node from physX
352 QVector3D position = QPhysicsUtils::toQtType(physx::toVec3(controller->getPosition()));
353 const QQuick3DNode *parentNode = static_cast<QQuick3DNode *>(characterController->parentItem());
354 if (!parentNode) {
355 // then it is the same space
356 characterController->setPosition(position);
357 } else {
358 characterController->setPosition(parentNode->mapPositionFromScene(position));
359 }
360
361 // setPosition() ran the controller's bindings, which can delete it.
362 if (!frontendNode)
363 return;
364
365 QVector3D teleportPos;
366 bool teleport = characterController->getTeleport(teleportPos);
367 if (teleport) {
368 controller->setPosition({ teleportPos.x(), teleportPos.y(), teleportPos.z() });
369 } else if (deltaTime > 0) {
370 const auto displacement =
371 QPhysicsUtils::toPhysXType(characterController->getDisplacement(deltaTime));
372 // getDisplacement() emits landed, and a handler for that can delete
373 // the controller.
374 if (!frontendNode)
375 return;
376 // No filter data on the query itself: PhysX's own query stage would
377 // match it against query filter data the shapes were never given, and
378 // let nothing through. The callback does the filtering instead.
379 const physx::PxControllerFilters filters(nullptr, filter, filter);
380
381 reportCallback->sliding = false;
382 auto collisions = controller->move(displacement, displacement.magnitude() * 0.01f,
383 deltaTime, filters);
384
385 // PxController::move() reports what it hits, and a handler for that
386 // can delete the controller.
387 if (!frontendNode)
388 return;
389 characterController->setCollisions(QCharacterController::Collisions(uint(collisions)));
390 // That ran the controller's bindings, which can delete it.
391 if (!frontendNode)
392 return;
393 characterController->setSliding(reportCallback->sliding);
394 }
395
396 // setCollisions() ran the controller's bindings, which can delete it.
397 if (!frontendNode)
398 return;
399
400 // The fields add their gravity again before the next sync().
401 characterController->clearEnvironmentGravity();
402
403 // Materials are shared between nodes, so a change of the material properties moves this
404 // node to another material, which the shape of the controller then has to be pointed at.
405 // The shape is created exclusive to the actor of the controller, so it stays writable.
406 if (updateMaterial() && material) {
407 if (auto *shape = shapeOf(*controller))
408 shape->setMaterials(&material, 1);
409 }
410}
411
412QPhysicsMaterial *QPhysXCharacterController::qtMaterial() const
413{
414 return static_cast<QCharacterController *>(frontendNode)->physicsMaterial();
415}
416
418{
419 return true;
420}
421
426
428{
429 if (!controller || !frontendNode || !filtersDirty())
430 return;
431 applyFilterData();
432}
433
434// Writes the frontend's groups to the controller's shape, which is where the
435// simulation filter shader reads them for the bodies and triggers the
436// controller's actor is paired with, and to the filter its own move() asks.
437void QPhysXCharacterController::applyFilterData()
438{
439 auto *shape = shapeOf(*controller);
440 if (!shape)
441 return;
442 const QFilterData data = frontendNode->filterData();
443 shape->setSimulationFilterData(QPhysicsUtils::toPhysXType(data));
444 filter->self = data;
445 // PxController caches the shapes near it, based on the filter settings,
446 // so we must invalidate that cache for the change to take effect.
447 controller->invalidateCache();
448 setFiltersDirty(false);
449}
450
452{
453 if (controller) {
454 controller->setUserData(nullptr);
455 if (auto *actor = controller->getActor())
456 actor->userData = nullptr;
457 }
458
460}
461
void onShapeHit(const physx::PxControllerShapeHit &hit) override
void onControllerHit(const physx::PxControllersHit &) override
ControllerCallback(QPhysicsWorld *worldIn)
void onObstacleHit(const physx::PxControllerObstacleHit &) override
physx::PxQueryHitType::Enum preFilter(const physx::PxFilterData &, const physx::PxShape *shape, const physx::PxRigidActor *, physx::PxHitFlags &) override
physx::PxQueryHitType::Enum postFilter(const physx::PxFilterData &, const physx::PxQueryHit &, const physx::PxShape *, const physx::PxRigidActor *) override
bool filter(const physx::PxController &a, const physx::PxController &b) override
virtual void cleanup(QPhysXWorld *)
void setFiltersDirty(bool dirty)
virtual void detachFrontend()
QPhysXCharacterController(QCharacterController *frontEnd)
QPhysicsMaterial * qtMaterial() const override
DebugDrawBodyType getDebugDrawBodyType() override
void init(QPhysicsWorld *world, QPhysXWorld *physX) override
void cleanup(QPhysXWorld *physX) override
void updateFilters(QPhysXWorld *physX) override
void sync(float deltaTime, QHash< QQuick3DNode *, QMatrix4x4 > &transformCache) override
#define PHYSX_RELEASE(x)
DebugDrawBodyType
static float resolveStepOffset(float maximumStepHeight, float height, float radius, float current=-1.f)
static float toPhysXSlopeLimit(float degrees)
static physx::PxShape * shapeOf(const physx::PxController &controller)
#define QT_BEGIN_NAMESPACE
#define QT_END_NAMESPACE