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
qgravityfield.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 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#include "physxnode/qphysxgravityfield_p.h"
7
8#include <utility>
9
11
12/*!
13 \qmltype GravityField
14 \inherits PhysicsNode
15 \inqmlmodule QtQuick3D.Physics
16 \since 6.13
17 \brief A gravity of its own, for the whole scene or a region of it.
18
19 A GravityField applies its own gravity to every \l DynamicRigidBody and
20 \l CharacterController it acts on, on top of the gravity they already
21 have: the \l{PhysicsWorld::gravity}{world's gravity} for a dynamic rigid
22 body, and its own \l{CharacterController::gravity}{gravity} property for a
23 character controller.
24
25 A field with no \l{PhysicsNode::collisionShapes}{collisionShapes} acts on
26 every body in the scene, wherever it is. A field with collision shapes
27 acts only on the bodies that overlap them, and stops acting on a body when
28 it leaves them. That is how you build a low gravity room, an updraft, a
29 corridor where down is sideways, or the space around a planet.
30
31 In the default \c Directional \l mode the gravity points the same way and
32 has the same strength everywhere, as world gravity does; it is uniform
33 rather than Newtonian. In \c Point mode it points at the field's own
34 position, which is how you build a spherical or planetary world: bodies
35 fall toward it from any direction, and with \l unitDistance set the gravity
36 weakens with distance, as Newtonian gravity does.
37
38 A negative \l gravity reverses either mode. A \c Point field with a
39 negative gravity pushes bodies away from its position instead of pulling
40 them in, which is how you build a repulsor.
41
42 A body does \e not need
43 \l{PhysicsNode::sendTriggerReports}{sendTriggerReports} set to be affected
44 by a field with collision shapes, and the field does not report the bodies
45 inside it either: it has no equivalent of TriggerBody's
46 \l{TriggerBody::bodyEntered}{bodyEntered} and
47 \l{TriggerBody::bodyExited}{bodyExited} signals or its
48 \l{TriggerBody::collisionCount}{collisionCount} property, and a body's
49 \l{PhysicsNode::enteredTriggerBody}{enteredTriggerBody} and
50 \l{PhysicsNode::exitedTriggerBody}{exitedTriggerBody} signals are not
51 emitted for it. To be notified of what enters the shapes, or to count what
52 is inside them, place a \l TriggerBody with the same shapes alongside the
53 field. The contact and trigger report properties of PhysicsNode have no
54 effect on a GravityField.
55
56 A field \e adds its gravity to what a body already has rather than
57 replacing it, so fields compose with world gravity, with each other, and
58 with a character controller's own gravity. A field never overwrites a
59 value, or a binding, that you set yourself, and a field stopping to act on
60 a body simply stops its contribution. A \l DynamicRigidBody with
61 \l{DynamicRigidBody::gravityEnabled}{gravityEnabled} set to \c false is not
62 affected by a field either.
63
64 A CharacterController has no such switch. Setting its
65 \l{CharacterController::gravity}{gravity} to zero only takes away its own
66 gravity, not that of the fields acting on it, so a character that is to be
67 free of gravity altogether, for instance while it swims or climbs a
68 ladder, has to be kept out of the fields with the filter groups described
69 below.
70
71 A field respects \l{PhysicsNode::filterGroup}{filterGroup} and
72 \l{PhysicsNode::filterIgnoreGroups}{filterIgnoreGroups}: a body in a group
73 the field ignores, or one that ignores the field's group, is left alone.
74 For a field without collision shapes this is how part of the scene is kept
75 out of it, which world gravity cannot do.
76
77 For example, the following weakens gravity inside a box by pushing back
78 against it, so that bodies inside fall at a fifth of the usual rate:
79
80 \qml
81 GravityField {
82 gravity: -785
83 collisionShapes: BoxShape { extents: Qt.vector3d(400, 400, 400) }
84 }
85 \endqml
86
87 and this defines a planet that bodies fall toward from any direction and
88 any distance:
89
90 \qml
91 PhysicsWorld {
92 // Required: world gravity would otherwise keep pulling everything
93 // down on top of the planet's gravity.
94 gravity: Qt.vector3d(0, 0, 0)
95 }
96
97 StaticRigidBody {
98 id: planet
99 collisionShapes: SphereShape { diameter: 280 }
100 }
101
102 GravityField {
103 position: planet.position
104 mode: GravityField.Point
105 gravity: 981
106 unitDistance: 140
107 }
108 \endqml
109
110 Note that \l{PhysicsWorld::gravity}{PhysicsWorld.gravity} has to be set to
111 a zero vector here. World gravity defaults to pulling everything down, and
112 a field adds to it rather than replacing it, so without that the bodies
113 would fall down past the planet instead of onto it.
114
115 Fields add up, so two \c Point fields with \l unitDistance set give the
116 combined gravity of a planet and its moon, weakening with distance from
117 each.
118
119 The two ways of finding bodies differ in what they cost. A field with
120 collision shapes finds what is inside them the way a \l TriggerBody does,
121 which costs the simulation one collision pair per body it overlaps,
122 updated on every step for as long as that body is awake. That is cheap for
123 shapes that cover part of a scene. A field without collision shapes goes
124 through every body in the scene, one at a time, before every step, and is
125 applied to the awake ones it acts on, which costs more in a scene with
126 many bodies.
127
128 This also decides what moving a field costs. Moving a field with shapes
129 only involves the bodies inside them, however many bodies the scene has.
130 A field that moves around should therefore be given shapes, sized to the
131 area it should affect. A \c Point field without shapes wakes every body it
132 acts on on each step it moves, so moving one keeps all of those bodies
133 awake. Moving a \c Directional field without shapes changes nothing, since
134 its gravity does not depend on where it is.
135
136 A \c Directional field without shapes or filter groups does what world
137 gravity does; prefer world gravity then, which is applied to all bodies at
138 once as part of each simulation step, and so performs better, since you do
139 not pay for filtering that you do not use. Keep in mind that world gravity
140 does not act on a \l CharacterController, so a character then needs its
141 own \l{CharacterController::gravity}{gravity} set.
142
143 \note A \l CharacterController is pulled by a \c Point field like any other
144 body, but it still stands and walks with respect to the world's up axis, so
145 it cannot walk on the side of a planet built this way. It falls toward the
146 field's position, and lands on, walks over, and steps up whatever is below
147 it in world space.
148
149 \note A body resting on a surface is still allowed to go to sleep, exactly
150 as it would under world gravity. Bodies are woken when the field starts or
151 stops acting on them, for instance as they enter or leave its shapes or as
152 filter groups change, when its gravity changes, when a \c Point field
153 moves, and when the field is destroyed, not continuously while the field
154 acts on them.
155
156 \sa TriggerBody, DynamicRigidBody, CharacterController
157*/
158
159/*!
160 \qmlproperty enumeration GravityField::mode
161 \since 6.13
162
163 This property defines which way the field's gravity points.
164
165 \value GravityField.Directional Along \l direction, the same everywhere.
166 This is the default.
167 \value GravityField.Point Toward the field's own position, so bodies fall
168 in from any direction, or away from it with a negative \l gravity.
169 \l unitDistance applies in this mode only.
170
171 \default GravityField.Directional
172
173 \sa direction, gravity
174*/
175
176/*!
177 \qmlproperty vector3d GravityField::direction
178 \since 6.13
179
180 This property defines the direction the field's gravity points in, when
181 \l mode is \c GravityField.Directional. It need not be normalized; only its
182 direction is used, with \l gravity giving the magnitude. It is ignored in
183 \c Point mode.
184
185 It is in scene space, like \l{PhysicsWorld::gravity}{the world's own
186 gravity}, so rotating the field turns its collision shapes without turning
187 the gravity.
188
189 \default Qt.vector3d(0, -1, 0)
190
191 \sa mode, gravity
192*/
193
194/*!
195 \qmlproperty real GravityField::gravity
196 \since 6.13
197
198 This property defines the gravitational acceleration applied to bodies,
199 along \l direction in Directional mode or toward the field's position in
200 Point mode. In Point mode with \l unitDistance set, it is the acceleration
201 at that distance from the field's position, and weaker elsewhere. A
202 negative value reverses it: against \l direction, or away from the field's
203 position rather than toward it, which makes a Point field a repulsor.
204
205 \default 981
206
207 \sa unitDistance, PhysicsWorld::gravity
208*/
209
210/*!
211 \qmlproperty real GravityField::unitDistance
212 \since 6.13
213
214 This property defines, in \c Point \l mode, the distance from the field's
215 position at which the acceleration equals \l gravity. Beyond it the
216 acceleration falls off with the inverse square of the distance, as
217 Newtonian gravity does, so at twice the distance it is a quarter as strong.
218 Inside it the acceleration falls off linearly toward the centre, as it
219 would inside a solid sphere of uniform density, so at half the distance it
220 is half as strong, and at the centre there is none. For example, for a
221 planet with a radius of 100 and a surface gravity of 4, set \l gravity to
222 \c 4 and \c unitDistance to \c 100.
223
224 A value of \c 0 disables falloff, giving the same acceleration everywhere.
225 A body exactly at the field's position then has no direction to fall in
226 and is given no acceleration.
227
228 It is ignored in \c Directional mode.
229
230 Range: \c{[0, inf)}
231
232 \default 0
233
234 \sa mode, gravity
235*/
236
237static_assert(int(QGravityField::Mode::Directional) == int(QPhysicsGravity::Mode::Directional)
238 && int(QGravityField::Mode::Point) == int(QPhysicsGravity::Mode::Point));
239
240QGravityField::QGravityField() = default;
241
242QGravityField::~QGravityField()
243{
244 // What the field acted on loses its gravity, so whatever is asleep under
245 // it has to be woken to fall under what is left. The backend outlives the
246 // field, and hands them to the world as it is deregistered.
247 QPhysXGravityField::fieldDestroyed(this);
248}
249
250QGravityField::Mode QGravityField::mode() const
251{
252 return Mode(m_gravity.mode);
253}
254
255void QGravityField::setMode(Mode mode)
256{
257 if (this->mode() == mode)
258 return;
259 m_gravity.mode = QPhysicsGravity::Mode(mode);
260 m_pendingWakeAll = true;
261 emit modeChanged();
262}
263
264const QVector3D &QGravityField::direction() const
265{
266 return m_gravity.direction;
267}
268
269void QGravityField::setDirection(const QVector3D &direction)
270{
271 if (!m_gravity.setDirection(direction, "GravityField"))
272 return;
273 if (m_gravity.readsDirection())
274 m_pendingWakeAll = true;
275 emit directionChanged();
276}
277
278float QGravityField::gravity() const
279{
280 return m_gravity.gravity;
281}
282
283void QGravityField::setGravity(float gravity)
284{
285 if (!m_gravity.setGravity(gravity, "GravityField"))
286 return;
287 m_pendingWakeAll = true;
288 emit gravityChanged();
289}
290
291float QGravityField::unitDistance() const
292{
293 return m_gravity.unitDistance;
294}
295
296void QGravityField::setUnitDistance(float unitDistance)
297{
298 if (!m_gravity.setUnitDistance(unitDistance, "GravityField"))
299 return;
300 if (m_gravity.readsUnitDistance())
301 m_pendingWakeAll = true;
302 emit unitDistanceChanged();
303}
304
305const QPhysicsGravity &QGravityField::gravityState() const
306{
307 return m_gravity;
308}
309
310bool QGravityField::isSceneWide() const
311{
312 return getCollisionShapesList().isEmpty();
313}
314
315bool QGravityField::countsBody(const QAbstractPhysicsNode *body) const
316{
317 // What the field can act on, whatever the body asked for with
318 // sendTriggerReports.
319 return QPhysicsGravity::targetOf(body) != QPhysicsGravity::Target::None;
320}
321
322void QGravityField::queueWake(QAbstractPhysicsNode *body)
323{
324 // Only a dynamic body has a sleep state.
325 if (QPhysicsGravity::targetOf(body) == QPhysicsGravity::Target::DynamicBody
326 && !m_pendingWakes.contains(body)) {
327 m_pendingWakes.append(body);
328 }
329}
330
331void QGravityField::bodyDidEnter(QAbstractPhysicsNode *body)
332{
333 queueWake(body);
334}
335
336void QGravityField::bodyDidExit(QAbstractPhysicsNode *body)
337{
338 // A sleeping body cannot leave by itself, but the field can move off it,
339 // change shape, or have its pair with the body filtered out, and then the
340 // body has to fall under whatever gravity is left.
341 queueWake(body);
342}
343
344QList<QPointer<QAbstractPhysicsNode>> QGravityField::trackedBodies() const
345{
346 QList<QPointer<QAbstractPhysicsNode>> bodies;
347 const auto &tracked = collisions();
348 for (auto it = tracked.cbegin(), end = tracked.cend(); it != end; ++it) {
349 if (it->reports)
350 bodies.append(it.key());
351 }
352 return bodies;
353}
354
355QAbstractPhysXNode *QGravityField::createPhysXBackend()
356{
357 return new QPhysXGravityField(this);
358}
359
#define QT_BEGIN_NAMESPACE
#define QT_END_NAMESPACE