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
qquick3dcamera.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5
7
8#include <QtQuick3DRuntimeRender/private/qssgrendercamera_p.h>
9
12
13#include <QtMath>
14#include <QtQuick3DUtils/private/qssgutils_p.h>
15
17
19
20/*!
21 \qmltype Camera
22 \inherits Node
23 \inqmlmodule QtQuick3D
24 \brief Defines an abstract base for Cameras.
25
26 A Camera defines how the content of the 3D scene is projected onto a 2D surface,
27 such as a View3D. A scene needs at least one Camera in order to visualize its
28 contents.
29
30 It is possible to position and rotate the Camera like any other spatial \l{QtQuick3D::Node}{Node} in
31 the scene. The \l{QtQuick3D::Node}{Node}'s location and orientation determines where the Camera is in
32 the scene, and what direction it is facing. The default orientation of the camera
33 has its forward vector pointing along the negative Z axis and its up vector along
34 the positive Y axis.
35
36 Together with the position and orientation, the frustum defines which parts of
37 a scene are visible to the Camera and how they are projected onto the 2D surface.
38 The different Camera subtypes provide multiple options to determine the shape of the
39 Camera's frustum.
40
41 \list
42 \li PerspectiveCamera provides a camera with a pyramid-shaped frustum, where objects are
43 projected so that those further away from the camera appear to be smaller. This is the
44 most commonly used camera type, and corresponds to how most real world cameras work.
45 \li OrthographicCamera provides a camera where the lines of the frustum are parallel,
46 making the perceived scale of an object unaffected by its distance to the camera. Typical
47 use cases for this type of camera are CAD (Computer-Assisted Design) applications and
48 cartography.
49 \li FrustumCamera is a perspective camera type where the frustum can be freely customized
50 by the coordinates of its intersection with the near plane. It can be useful if an
51 asymmetrical camera frustum is needed.
52 \li CustomCamera is a camera type where the projection matrix can be freely customized,
53 and can be useful for advanced users who wish to calculate their own projection matrix.
54 \endlist
55
56 To illustrate the difference, these screenshots show the same scene as projected by a
57 PerspectiveCamera and an OrthographicCamera. Notice how the red box is smaller than the
58 green box in the image rendered using the perspective projection.
59 \table
60 \header
61 \li Perspective camera
62 \li Orthographic camera
63 \row
64 \li \image perspectivecamera.png
65 {Perspective camera view of plate}
66 \li \image orthographiccamera.png
67 {Orthographic camera view of plate}
68 \endtable
69
70 \sa {Qt Quick 3D - View3D Example}
71*/
72
73/*!
74 \internal
75*/
76QQuick3DCamera::QQuick3DCamera(QQuick3DNodePrivate &dd, QQuick3DNode *parent)
77 : QQuick3DNode(dd, parent) {}
78
79/*!
80 \qmlproperty bool Camera::frustumCullingEnabled
81
82 When this property is \c true, objects outside the camera frustum will be culled, meaning they will
83 not be passed to the renderer. By default this property is set to \c false. For scenes where all or
84 most objects are inside the camera frustum, frustum culling is an unnecessary performance overhead.
85 But for complex scenes where large parts are located outside the camera's view, enabling frustum
86 culling may improve performance.
87
88 For an instanced Model that gets the level of detail of each instance
89 selected automatically, this also leaves out the instances outside the
90 camera frustum.
91
92 \sa {instanced-lod}{Instanced models}
93*/
94bool QQuick3DCamera::frustumCullingEnabled() const
95{
96 return m_frustumCullingEnabled;
97}
98
99void QQuick3DCamera::setFrustumCullingEnabled(bool frustumCullingEnabled)
100{
101 if (m_frustumCullingEnabled == frustumCullingEnabled)
102 return;
103
104 m_frustumCullingEnabled = frustumCullingEnabled;
105 emit frustumCullingEnabledChanged();
106 update();
107}
108
109/*!
110 \qmlproperty Node Camera::lookAtNode
111
112 If this property is set to a \c non-null value, the rotation of this camera is automatically
113 updated so that this camera keeps looking at the specified node whenever the scene position of
114 this camera or the specified node changes.
115 By default this property is set to \c{null}.
116
117 \sa lookAt
118*/
119QQuick3DNode *QQuick3DCamera::lookAtNode() const
120{
121 return m_lookAtNode;
122}
123
124void QQuick3DCamera::setLookAtNode(QQuick3DNode *node)
125{
126 if (m_lookAtNode == node)
127 return;
128
129 if (m_lookAtNode) {
130 disconnect(m_lookAtNode, &QQuick3DNode::scenePositionChanged, this, &QQuick3DCamera::updateLookAt);
131 disconnect(this, &QQuick3DNode::scenePositionChanged, this, &QQuick3DCamera::updateLookAt);
132 }
133
134 m_lookAtNode = node;
135
136 if (m_lookAtNode) {
137 connect(m_lookAtNode, &QQuick3DNode::scenePositionChanged, this, &QQuick3DCamera::updateLookAt);
138 connect(this, &QQuick3DNode::scenePositionChanged, this, &QQuick3DCamera::updateLookAt);
139 }
140
141 emit lookAtNodeChanged();
142 updateLookAt();
143}
144
145/*!
146 \qmlmethod vector3d Camera::mapToViewport(vector3d scenePos)
147
148 Transforms \a scenePos from global scene space (3D) into viewport space (2D).
149
150 The returned position is normalized, with the top-left of the viewport
151 at [0, 0] and the bottom-right at [1, 1]. The returned z-value will contain
152 the distance from the near clip plane of the frustum (clipNear) to \a scenePos in
153 scene coordinates. If the distance is negative, the point is behind camera.
154
155 If \a scenePos cannot successfully be mapped to a position in the viewport, a
156 position of [0, 0, 0] is returned.
157
158 \sa mapFromViewport(), {View3D::mapFrom3DScene()}{View3D.mapFrom3DScene()}
159*/
160QVector3D QQuick3DCamera::mapToViewport(const QVector3D &scenePos) const
161{
162 QSSGRenderCamera *cameraNode = static_cast<QSSGRenderCamera *>(QQuick3DObjectPrivate::get(this)->spatialNode);
163 if (!cameraNode)
164 return QVector3D(0, 0, 0);
165
166 QVector4D scenePosRightHand(scenePos, 1);
167
168 // Transform position
169 const QMatrix4x4 sceneToCamera = sceneTransform().inverted();
170 const QMatrix4x4 projectionViewMatrix = cameraNode->projection * sceneToCamera;
171 const QVector4D transformedScenePos = QSSGUtils::mat44::transform(projectionViewMatrix, scenePosRightHand);
172
173 if (qFuzzyIsNull(transformedScenePos.w()) || qIsNaN(transformedScenePos.w()))
174 return QVector3D(0, 0, 0);
175
176 // Normalize scenePosView between [-1, 1]
177 QVector3D scenePosView = transformedScenePos.toVector3D() / transformedScenePos.w();
178
179 // Set z to be the scene distance from clipNear so that the return value
180 // can be used as argument to viewportToscene() to reverse the call.
181 const QVector4D clipNearPos(scenePosView.x(), scenePosView.y(), -1, 1);
182 auto invProj = projectionViewMatrix.inverted();
183 const QVector4D clipNearPosTransformed = QSSGUtils::mat44::transform(invProj, clipNearPos);
184 if (qFuzzyIsNull(clipNearPosTransformed.w()) || qIsNaN(clipNearPosTransformed.w()))
185 return QVector3D(0, 0, 0);
186 const QVector4D clipNearPosScene = clipNearPosTransformed / clipNearPosTransformed.w();
187 QVector4D clipFarPos = clipNearPos;
188 clipFarPos.setZ(0);
189 const QVector4D clipFarPosTransformed = QSSGUtils::mat44::transform(invProj, clipFarPos);
190 if (qFuzzyIsNull(clipFarPosTransformed.w()) || qIsNaN(clipFarPosTransformed.w()))
191 return QVector3D(0, 0, 0);
192 const QVector4D clipFarPosScene = clipFarPosTransformed / clipFarPosTransformed.w();
193 const QVector3D direction = (clipFarPosScene - clipNearPosScene).toVector3D();
194 const QVector3D scenePosVec = (scenePosRightHand - clipNearPosScene).toVector3D();
195
196 const float distanceToScenePos = scenePosVec.length()
197 * (QVector3D::dotProduct(direction, scenePosVec) > 0.f ? 1 : -1);
198
199 scenePosView.setZ(distanceToScenePos);
200
201 // Convert x and y to be between [0, 1]
202 scenePosView.setX((scenePosView.x() / 2) + 0.5f);
203 scenePosView.setY((scenePosView.y() / 2) + 0.5f);
204 // And convert origin from bottom-left to top-left
205 scenePosView.setY(1 - scenePosView.y());
206 return scenePosView;
207}
208
209/*!
210 \qmlmethod vector3d Camera::mapFromViewport(vector3d viewportPos)
211
212 Transforms \a viewportPos from viewport space (2D) into global scene space (3D).
213
214 The x- and y-values of \a viewportPos must be normalized, with the top-left
215 of the viewport at [0, 0] and the bottom-right at [1, 1]. The z-value is interpreted
216 as the distance from the near clip plane of the frustum (clipNear).
217
218 If \a viewportPos cannot successfully be mapped to a position in the scene, a position
219 of [0, 0, 0] is returned.
220
221 \sa mapToViewport, {View3D::mapTo3DScene()}{View3D.mapTo3DScene()}
222*/
223QVector3D QQuick3DCamera::mapFromViewport(const QVector3D &viewportPos) const
224{
225 QSSGRenderCamera *cameraNode = static_cast<QSSGRenderCamera *>(QQuick3DObjectPrivate::get(this)->spatialNode);
226 if (!cameraNode)
227 return QVector3D(0, 0, 0);
228
229 // Pick two positions in the frustum
230 QVector4D clipNearPos(viewportPos, 1);
231 // Convert origin from top-left to bottom-left
232 clipNearPos.setY(1 - clipNearPos.y());
233 // Convert to homogenous position between [-1, 1]
234 clipNearPos.setX((clipNearPos.x() * 2.0f) - 1.0f);
235 clipNearPos.setY((clipNearPos.y() * 2.0f) - 1.0f);
236 QVector4D clipFarPos = clipNearPos;
237 // clipNear: z = -1, clipFar: z = 1. It's recommended to use 0 as
238 // far pos instead of clipFar because of infinite projection issues.
239 clipNearPos.setZ(-1);
240 clipFarPos.setZ(0);
241
242 // Transform position to scene
243 const QMatrix4x4 sceneToCamera = sceneTransform().inverted();
244 const QMatrix4x4 projectionViewMatrixInv = (cameraNode->projection * sceneToCamera).inverted();
245 const QVector4D transformedClipNearPos = QSSGUtils::mat44::transform(projectionViewMatrixInv, clipNearPos);
246 const QVector4D transformedClipFarPos = QSSGUtils::mat44::transform(projectionViewMatrixInv, clipFarPos);
247
248 if (qFuzzyIsNull(transformedClipNearPos.w()) || qIsNaN(transformedClipNearPos.w()) ||
249 qFuzzyIsNull(transformedClipFarPos.w()) || qIsNaN(transformedClipFarPos.w()))
250 return QVector3D(0, 0, 0);
251
252 // Reverse the projection
253 const QVector3D clipNearPosScene = transformedClipNearPos.toVector3D()
254 / transformedClipNearPos.w();
255 const QVector3D clipFarPosScene = transformedClipFarPos.toVector3D()
256 / transformedClipFarPos.w();
257
258 // Calculate the position in the scene
259 const QVector3D direction = (clipFarPosScene - clipNearPosScene).normalized();
260 const float distanceFromClipNear = viewportPos.z();
261 QVector3D scenePos = clipNearPosScene + (direction * distanceFromClipNear);
262
263 return scenePos;
264}
265
266/*!
267 * \internal
268 */
269QVector3D QQuick3DCamera::mapToViewport(const QVector3D &scenePos,
270 qreal width,
271 qreal height)
272{
273 // We can be called before a spatial node is created, if that is the case, create the node now.
274 if (QSSGRenderCamera *cameraNode = static_cast<QSSGRenderCamera *>(updateSpatialNode(QQuick3DObjectPrivate::get(this)->spatialNode))) {
275 QQuick3DObjectPrivate::get(this)->spatialNode = cameraNode;
276 QSSGRenderCamera::Configuration camConfig { cameraNode->getDpr(), 1.0f /* ssaa multiplier */ };
277 QSSGRenderCamera::calculateProjectionInternal(*cameraNode, QRect(0, 0, width * camConfig.dpr, height * camConfig.dpr), camConfig);
278 }
279
280 return QQuick3DCamera::mapToViewport(scenePos);
281}
282
283/*!
284 * \internal
285 */
286QVector3D QQuick3DCamera::mapFromViewport(const QVector3D &viewportPos,
287 qreal width,
288 qreal height)
289{
290 // We can be called before a spatial node is created, if that is the case, create the node now.
291 if (QSSGRenderCamera *cameraNode = static_cast<QSSGRenderCamera *>(updateSpatialNode(QQuick3DObjectPrivate::get(this)->spatialNode))) {
292 QQuick3DObjectPrivate::get(this)->spatialNode = cameraNode;
293 QSSGRenderCamera::Configuration camConfig { cameraNode->getDpr(), 1.0f /* ssaa multiplier */ };
294 QSSGRenderCamera::calculateProjectionInternal(*cameraNode, QRect(0, 0, width * camConfig.dpr, height * camConfig.dpr));
295 }
296
297 return QQuick3DCamera::mapFromViewport(viewportPos);
298}
299
300/*!
301 \qmlmethod vector3d Camera::lookAt(vector3d scenePos)
302 \since 5.15
303
304 Sets the rotation value of the Camera so that it is pointing at \a scenePos.
305*/
306
307void QQuick3DCamera::lookAt(const QVector3D &scenePos)
308{
309 // Assumption: we never want the camera to roll.
310 // We use Euler angles here to avoid roll to sneak in through numerical instability.
311
312 const auto &targetPosition = scenePos;
313 auto sourcePosition = scenePosition();
314
315 QVector3D targetVector = sourcePosition - targetPosition;
316
317 float yaw = qRadiansToDegrees(atan2(targetVector.x(), targetVector.z()));
318
319 QVector2D p(targetVector.x(), targetVector.z()); // yaw vector projected to horizontal plane
320 float pitch = qRadiansToDegrees(atan2(p.length(), targetVector.y())) - 90;
321
322 const float previousRoll = eulerRotation().z();
323 setEulerRotation(QVector3D(pitch, yaw, previousRoll));
324}
325
326/*!
327 \qmlmethod vector3d Camera::lookAt(QtQuick3D::Node node)
328 \since 5.15
329
330 Sets the rotation value of the Camera so that it is pointing at \a node.
331*/
332
333void QQuick3DCamera::lookAt(QQuick3DNode *node)
334{
335 if (!node)
336 return;
337 lookAt(node->scenePosition());
338}
339
340void QQuick3DCamera::updateGlobalVariables(const QRectF &inViewport)
341{
342 QSSGRenderCamera *node = static_cast<QSSGRenderCamera *>(QQuick3DObjectPrivate::get(this)->spatialNode);
343 if (node)
344 QSSGRenderCamera::calculateProjectionInternal(*node, inViewport);
345}
346
347/*!
348 * \internal
349 */
350QSSGRenderGraphObject *QQuick3DCamera::updateSpatialNode(QSSGRenderGraphObject *node)
351{
352 if (!node) {
353 markAllDirty();
354 node = new QSSGRenderCamera(QQuick3DObjectPrivate::get(this)->type);
355 }
356
357 QQuick3DNode::updateSpatialNode(node);
358
359 QSSGRenderCamera *camera = static_cast<QSSGRenderCamera *>(node);
360 if (qUpdateIfNeeded(camera->enableFrustumClipping, m_frustumCullingEnabled))
361 camera->markDirty(QSSGRenderCamera::DirtyFlag::CameraDirty);
362 if (qUpdateIfNeeded(camera->levelOfDetailPixelThreshold, m_levelOfDetailBias))
363 camera->markDirty(QSSGRenderCamera::DirtyFlag::CameraDirty);
364 if (qUpdateIfNeeded(camera->layerMask, quint32(QQuick3DNodePrivate::get(this)->m_tag)))
365 camera->markDirty(QSSGRenderCamera::DirtyFlag::LayerMaskDirty);
366
367 return node;
368}
369
370void QQuick3DCamera::updateLookAt()
371{
372 if (m_lookAtNode)
373 lookAt(m_lookAtNode);
374}
375
376/*!
377 \qmlproperty real Camera::levelOfDetailBias
378 \since 6.5
379
380 This property changes the size a model needs to be when rendered before the
381 automatic level of detail meshes are used. Each generated level of detail
382 mesh contains an ideal size value that each level should be shown, which is
383 a ratio of how much of the rendered scene will be that mesh. A model that
384 represents only a few pixels on screen will not require the full geometry
385 to look correct, so a lower level of detail mesh will be used instead in
386 this case. This value is a bias to the ideal value such that a value smaller
387 than \c 1.0 will require an even smaller rendered size before switching to
388 a lesser level of detail. Values above \c 1.0 will lead to lower levels of detail
389 being used sooner. A value of \c 0.0 will disable the usage of levels of detail
390 completely.
391
392 The default value is \c 1.0
393
394 \note This property will only have an effect on Models with geomtry containing
395 levels of detail.
396
397 \sa Model::levelOfDetailBias
398*/
399
400float QQuick3DCamera::levelOfDetailBias() const
401{
402 return m_levelOfDetailBias;
403}
404
405void QQuick3DCamera::setLevelOfDetailBias(float newLevelOfDetailBias)
406{
407 if (qFuzzyCompare(m_levelOfDetailBias, newLevelOfDetailBias))
408 return;
409 m_levelOfDetailBias = newLevelOfDetailBias;
410 emit levelOfDetailBiasChanged();
411 update();
412}
413
414QT_END_NAMESPACE
Combined button and popup list for selecting options.