QGIS API Documentation 4.5.0-Master (c9e0ddc514d)
Loading...
Searching...
No Matches
qgscameracontroller.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgscameracontroller.cpp
3 --------------------------------------
4 Date : July 2017
5 Copyright : (C) 2017 by Martin Dobias
6 Email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgscameracontroller.h"
17
18#include <cmath>
19
20#include "qgis.h"
21#include "qgs3dmapscene.h"
22#include "qgs3dutils.h"
23#include "qgscrosssection.h"
24#include "qgseventtracing.h"
25#include "qgsgui.h"
26#include "qgslogger.h"
27#include "qgsnative.h"
28#include "qgsray3d.h"
29#include "qgsraycastcontext.h"
30#include "qgsraycasthit.h"
31#include "qgsterrainentity.h"
32#include "qgsvector3d.h"
33#include "qgswindow3dengine.h"
34
35#include <QDomDocument>
36#include <QQuaternion>
37#include <QString>
38#include <QStringLiteral>
39#include <Qt3DInput>
40#include <Qt3DRender/QCamera>
41
42#include "moc_qgscameracontroller.cpp"
43
44using namespace Qt::StringLiterals;
45
47 : Qt3DCore::QEntity( scene )
48 , mScene( scene )
49 , mCamera( scene->engine()->camera() )
50 , mCameraBefore( new Qt3DRender::QCamera )
51 , mMouseHandler( new Qt3DInput::QMouseHandler )
52 , mKeyboardHandler( new Qt3DInput::QKeyboardHandler )
53 , mOrigin( scene->mapSettings()->origin() )
54{
55 if ( QgsGui::nativePlatformInterface()->capabilities() & QgsNative::Capability::NativePointerLock )
56 {
57 mPointerLocker = QgsGui::nativePlatformInterface()->createPointerLocker( window(), this );
58 if ( mPointerLocker )
59 {
60 connect( mPointerLocker, &QgsPointerLocker::pointerMoved, this, [this]( double dx, double dy ) {
61 if ( !mCaptureFpsMouseMovements || !mInputHandlersEnabled )
62 return;
63 applyRelativePointerRotation( dx, dy );
64 } );
65 }
66 }
67
68 mMouseHandler->setSourceDevice( new Qt3DInput::QMouseDevice() );
69 connect( mMouseHandler, &Qt3DInput::QMouseHandler::positionChanged, this, &QgsCameraController::onPositionChanged );
70 connect( mMouseHandler, &Qt3DInput::QMouseHandler::wheel, this, &QgsCameraController::onWheel );
71 connect( mMouseHandler, &Qt3DInput::QMouseHandler::pressed, this, &QgsCameraController::onMousePressed );
72 connect( mMouseHandler, &Qt3DInput::QMouseHandler::released, this, &QgsCameraController::onMouseReleased );
73 addComponent( mMouseHandler );
74
75 // Disable the handlers when the entity is disabled
76 connect( this, &Qt3DCore::QEntity::enabledChanged, mMouseHandler, &Qt3DInput::QMouseHandler::setEnabled );
77 connect( this, &Qt3DCore::QEntity::enabledChanged, mKeyboardHandler, &Qt3DInput::QKeyboardHandler::setEnabled );
78
79 mFpsNavTimer = new QTimer( this );
80 mFpsNavTimer->setInterval( 10 );
81 connect( mFpsNavTimer, &QTimer::timeout, this, &QgsCameraController::applyFlyModeKeyMovements );
82 mFpsNavTimer->start();
83
84 if ( mScene->mapSettings()->sceneMode() == Qgis::SceneMode::Globe )
85 {
86 setCameraNavigationMode( mScene->mapSettings()->cameraNavigationMode() );
87 mGlobeCrsToLatLon = QgsCoordinateTransform( mScene->mapSettings()->crs(), mScene->mapSettings()->crs().toGeographicCrs(), mScene->mapSettings()->transformContext() );
88 }
89}
90
92
93QWindow *QgsCameraController::window() const
94{
95 QgsWindow3DEngine *windowEngine = qobject_cast<QgsWindow3DEngine *>( mScene->engine() );
96 return windowEngine ? windowEngine->window() : nullptr;
97}
98
100{
101 if ( navigationMode == mCameraNavigationMode )
102 return;
103
104 mCameraNavigationMode = navigationMode;
105 mIgnoreNextMouseMove = true;
106 emit navigationModeChanged( mCameraNavigationMode );
107}
108
110{
111 if ( movementSpeed == mCameraMovementSpeed )
112 return;
113
114 // If the speed becomes 0, navigation does not work anymore
115 // If the speed becomes too important, only one walk can move the view far from the scene.
116 mCameraMovementSpeed = std::clamp( movementSpeed, 0.05, 150.0 );
117 emit cameraMovementSpeedChanged( mCameraMovementSpeed );
118}
119
121{
122 mVerticalAxisInversion = inversion;
123}
124
125void QgsCameraController::rotateCamera( float diffPitch, float diffHeading )
126{
127 float newPitch = mCameraPose.pitchAngle() + diffPitch;
128 float newHeading = mCameraPose.headingAngle() + diffHeading;
129
130 newPitch = std::clamp( newPitch, 0.f, 180.f ); // prevent going over the head
131
132 switch ( mScene->mapSettings()->sceneMode() )
133 {
135 {
136 // When on a globe, we need to calculate "where is up" (the normal of a tangent plane).
137 // Also it uses different axes than the standard plane-based view.
138 // See QgsCameraPose::updateCameraGlobe(), we basically want to make sure
139 // that after an update, the camera stays in the same spot.
140 QgsVector3D viewCenterLatLon;
141 try
142 {
143 viewCenterLatLon = mGlobeCrsToLatLon.transform( mCameraPose.centerPoint() + mOrigin );
144 }
145 catch ( const QgsCsException & )
146 {
147 QgsDebugError( u"rotateCamera: ECEF -> lat,lon transform failed!"_s );
148 return;
149 }
150 QQuaternion qLatLon = QQuaternion::fromAxisAndAngle( QVector3D( 0, 0, 1 ), static_cast<float>( viewCenterLatLon.x() ) )
151 * QQuaternion::fromAxisAndAngle( QVector3D( 0, -1, 0 ), static_cast<float>( viewCenterLatLon.y() ) );
152 QQuaternion qPitchHeading = QQuaternion::fromAxisAndAngle( QVector3D( 1, 0, 0 ), newHeading ) * QQuaternion::fromAxisAndAngle( QVector3D( 0, 1, 0 ), newPitch );
153 QVector3D newCameraToCenter = ( qLatLon * qPitchHeading * QVector3D( -1, 0, 0 ) ) * mCameraPose.distanceFromCenterPoint();
154
155 mCameraPose.setCenterPoint( mCamera->position() + newCameraToCenter );
156 mCameraPose.setPitchAngle( newPitch );
157 mCameraPose.setHeadingAngle( newHeading );
158 updateCameraFromPose();
159 return;
160 }
161
163 {
164 QQuaternion q = Qgs3DUtils::rotationFromPitchHeadingAngles( newPitch, newHeading );
165 QVector3D newCameraToCenter = q * QVector3D( 0, 0, -mCameraPose.distanceFromCenterPoint() );
166 mCameraPose.setCenterPoint( mCamera->position() + newCameraToCenter );
167 mCameraPose.setPitchAngle( newPitch );
168 mCameraPose.setHeadingAngle( newHeading );
169 updateCameraFromPose();
170 return;
171 }
172 }
173}
174
175void QgsCameraController::rotateCameraAroundPivot( float newPitch, float newHeading, const QVector3D &pivotPoint )
176{
177 const float oldPitch = mCameraPose.pitchAngle();
178 const float oldHeading = mCameraPose.headingAngle();
179
180 newPitch = std::clamp( newPitch, 0.f, 180.f ); // prevent going over the head
181
182 // First undo the previously applied rotation, then apply the new rotation
183 // (We can't just apply our euler angles difference because the camera may be already rotated)
184 const QQuaternion qNew = Qgs3DUtils::rotationFromPitchHeadingAngles( newPitch, newHeading );
185 const QQuaternion qOld = Qgs3DUtils::rotationFromPitchHeadingAngles( oldPitch, oldHeading );
186 const QQuaternion q = qNew * qOld.conjugated();
187
188 const QVector3D newViewCenter = q * ( mCamera->viewCenter() - pivotPoint ) + pivotPoint;
189
190 mCameraPose.setCenterPoint( newViewCenter );
191 mCameraPose.setPitchAngle( newPitch );
192 mCameraPose.setHeadingAngle( newHeading );
193 updateCameraFromPose();
194}
195
196void QgsCameraController::zoomCameraAroundPivot( const QVector3D &oldCameraPosition, double zoomFactor, const QVector3D &pivotPoint )
197{
198 // step 1: move camera along the line connecting reference camera position and our pivot point
199 QVector3D newCamPosition = pivotPoint + ( oldCameraPosition - pivotPoint ) * zoomFactor;
200 double newDistance = mCameraPose.distanceFromCenterPoint() * zoomFactor;
201
202 // step 2: using the new camera position and distance from center, calculate new view center
203 QQuaternion q = Qgs3DUtils::rotationFromPitchHeadingAngles( mCameraPose.pitchAngle(), mCameraPose.headingAngle() );
204 QVector3D cameraToCenter = q * QVector3D( 0, 0, -newDistance );
205 QVector3D newViewCenter = newCamPosition + cameraToCenter;
206
207 mCameraPose.setDistanceFromCenterPoint( newDistance );
208 mCameraPose.setCenterPoint( newViewCenter );
209 updateCameraFromPose();
210}
211
212void QgsCameraController::zoomCameraAroundPivot( const QVector3D &oldCameraPosition, double oldDistanceFromCenterPoint, double zoomFactor, const QVector3D &pivotPoint )
213{
214 // step 1: move camera along the line connecting reference camera position and our pivot point
215 QVector3D newCamPosition = pivotPoint + ( oldCameraPosition - pivotPoint ) * zoomFactor;
216 const double newDistance = oldDistanceFromCenterPoint * zoomFactor;
217
218 // step 2: using the new camera position and distance from center, calculate new view center
219 QQuaternion q = Qgs3DUtils::rotationFromPitchHeadingAngles( mCameraPose.pitchAngle(), mCameraPose.headingAngle() );
220 QVector3D cameraToCenter = q * QVector3D( 0, 0, -newDistance );
221 QVector3D newViewCenter = newCamPosition + cameraToCenter;
222
223 mCameraPose.setDistanceFromCenterPoint( newDistance );
224 mCameraPose.setCenterPoint( newViewCenter );
225 updateCameraFromPose();
226}
227
229{
230 Q_UNUSED( dt )
231
232 // In case viewport size has changed
233 updateOrthographicProjectionPlane();
234
235 if ( mCameraChanged )
236 {
237 emit cameraChanged();
238 mCameraChanged = false;
239 }
240}
241
243{
244 QgsPointXY extentCenter = mScene->mapSettings()->extent().center();
245 QgsVector3D origin = mScene->mapSettings()->origin();
246 setViewFromTop( extentCenter.x() - origin.x(), extentCenter.y() - origin.y(), distance );
247}
248
249void QgsCameraController::setViewFromTop( float worldX, float worldY, float distance, float yaw )
250{
251 if ( mScene->mapSettings()->sceneMode() == Qgis::SceneMode::Globe )
252 {
253 QgsDebugError( u"setViewFromTop() should not be used with globe!"_s );
254 return;
255 }
256
257 QgsCameraPose camPose;
258 QgsTerrainEntity *terrain = mScene->terrainEntity();
259 const float terrainElevationOffset = terrain ? terrain->terrainElevationOffset() : 0.0f;
260 camPose.setCenterPoint( QgsVector3D( worldX, worldY, terrainElevationOffset - mScene->mapSettings()->origin().z() ) );
262 camPose.setHeadingAngle( yaw );
263
264 // a basic setup to make frustum depth range long enough that it does not cull everything
265 mCamera->setNearPlane( distance / 2 );
266 mCamera->setFarPlane( distance * 2 );
267 // we force the updateCameraNearFarPlanes() in Qgs3DMapScene to properly set the planes
268 setCameraPose( camPose, true );
269}
270
272{
273 return mCameraPose.centerPoint();
274}
275
276void QgsCameraController::setLookingAtPoint( const QgsVector3D &point, float distance, float pitch, float yaw )
277{
278 QgsCameraPose camPose;
279 camPose.setCenterPoint( point );
281 camPose.setPitchAngle( pitch );
282 camPose.setHeadingAngle( yaw );
283 setCameraPose( camPose );
284}
285
287{
288 return lookingAtPoint() + mOrigin;
289}
290
292{
293 setLookingAtPoint( point - mOrigin, distance, pitch, yaw );
294}
295
296void QgsCameraController::setCameraPose( const QgsCameraPose &camPose, bool force )
297{
298 if ( camPose == mCameraPose && !force )
299 return;
300
301 mCameraPose = camPose;
302 updateCameraFromPose();
303}
304
305QDomElement QgsCameraController::writeXml( QDomDocument &doc ) const
306{
307 QDomElement elemCamera = doc.createElement( u"camera"_s );
308 // Save center point in map coordinates, since our world origin won't be
309 // the same on loading
310 QgsVector3D centerPoint = mCameraPose.centerPoint() + mOrigin;
311 elemCamera.setAttribute( u"xMap"_s, centerPoint.x() );
312 elemCamera.setAttribute( u"yMap"_s, centerPoint.y() );
313 elemCamera.setAttribute( u"zMap"_s, centerPoint.z() );
314 elemCamera.setAttribute( u"dist"_s, mCameraPose.distanceFromCenterPoint() );
315 elemCamera.setAttribute( u"pitch"_s, mCameraPose.pitchAngle() );
316 elemCamera.setAttribute( u"yaw"_s, mCameraPose.headingAngle() );
317 return elemCamera;
318}
319
320void QgsCameraController::readXml( const QDomElement &elem, QgsVector3D savedOrigin )
321{
322 const float dist = elem.attribute( u"dist"_s ).toFloat();
323 const float pitch = elem.attribute( u"pitch"_s ).toFloat();
324 const float yaw = elem.attribute( u"yaw"_s ).toFloat();
325
326 QgsVector3D centerPoint;
327 if ( elem.hasAttribute( "xMap" ) )
328 {
329 // Prefer newer point saved in map coordinates ...
330 const double x = elem.attribute( u"xMap"_s ).toDouble();
331 const double y = elem.attribute( u"yMap"_s ).toDouble();
332 const double z = elem.attribute( u"zMap"_s ).toDouble();
333 centerPoint = QgsVector3D( x, y, z ) - mOrigin;
334 }
335 else
336 {
337 // ... but allow use of older origin-relative coordinates.
338 const double x = elem.attribute( u"x"_s ).toDouble();
339 const double y = elem.attribute( u"y"_s ).toDouble();
340 const double elev = elem.attribute( u"elev"_s ).toDouble();
341 centerPoint = QgsVector3D( x, elev, y ) - savedOrigin + mOrigin;
342 }
343 setLookingAtPoint( centerPoint, dist, pitch, yaw );
344}
345
347{
348 if ( !mDepthBufferIsReady )
349 {
350 QgsDebugError( u"Asked to sample depth buffer, but depth buffer not ready!"_s );
351 }
352
353 double depth = 1;
354
355 if ( QWindow *win = window() )
356 {
357 // on high DPI screens, the mouse position is in device-independent pixels,
358 // but the depth buffer is in physical pixels...
359 px = static_cast<int>( px * win->devicePixelRatio() );
360 py = static_cast<int>( py * win->devicePixelRatio() );
361 }
362
363 // Sample the neighbouring pixels for the closest point to the camera
364 for ( int x = px - 3; x <= px + 3; ++x )
365 {
366 for ( int y = py - 3; y <= py + 3; ++y )
367 {
368 if ( mDepthBufferImage.valid( x, y ) )
369 {
370 depth = std::min( depth, Qgs3DUtils::decodeDepth( mDepthBufferImage.pixel( x, y ) ) );
371 }
372 }
373 }
374 return depth;
375}
376
377double QgsCameraController::depthBufferNonVoidAverage()
378{
379 // Cache the computed depth, since averaging over all pixels can be expensive
380 if ( mDepthBufferNonVoidAverage != -1 )
381 return mDepthBufferNonVoidAverage;
382
383 // Returns the average of depth values that are not 1 (void area)
384 double depth = 0;
385 int samplesCount = 0;
386 // Make sure we can do the cast
387 Q_ASSERT( mDepthBufferImage.format() == QImage::Format_RGB32 );
388 for ( int y = 0; y < mDepthBufferImage.height(); ++y )
389 {
390 const QRgb *line = reinterpret_cast<const QRgb *>( mDepthBufferImage.constScanLine( y ) );
391 for ( int x = 0; x < mDepthBufferImage.width(); ++x )
392 {
393 double d = Qgs3DUtils::decodeDepth( line[x] );
394 if ( d < 1 )
395 {
396 depth += d;
397 samplesCount += 1;
398 }
399 }
400 }
401
402 // if the whole buffer is white, a depth cannot be computed
403 if ( samplesCount == 0 )
404 depth = 1.0;
405 else
406 depth /= samplesCount;
407
408 mDepthBufferNonVoidAverage = depth;
409
410 return depth;
411}
412
413QgsVector3D QgsCameraController::moveGeocentricPoint( const QgsVector3D &point, double latDiff, double lonDiff )
414{
415 try
416 {
417 QgsVector3D pointLatLon = mGlobeCrsToLatLon.transform( point );
418 pointLatLon.setX( pointLatLon.x() + lonDiff );
419 pointLatLon.setY( std::clamp( pointLatLon.y() + latDiff, -90., 90. ) );
420
421 return mGlobeCrsToLatLon.transform( pointLatLon, Qgis::TransformDirection::Reverse );
422 }
423 catch ( const QgsCsException & )
424 {
425 QgsDebugError( u"moveGeocentricPoint: transform failed!"_s );
426 return point;
427 }
428}
429
430void QgsCameraController::applyRelativePointerRotation( double dx, double dy )
431{
432 float diffPitch = -0.2f * static_cast<float>( dy );
433 if ( mVerticalAxisInversion & Qgis::VerticalAxisInversion::WhenRotatingCaptured )
434 diffPitch *= -1;
435
436 const float diffYaw = -0.2f * static_cast<float>( dx );
437 rotateCamera( diffPitch, diffYaw );
438}
439
440void QgsCameraController::globeMoveCenterPoint( double latDiff, double lonDiff )
441{
442 const QgsVector3D viewCenter = mCameraPose.centerPoint() + mOrigin;
443 const QgsVector3D newViewCenter = moveGeocentricPoint( viewCenter, latDiff, lonDiff );
444 mCameraPose.setCenterPoint( newViewCenter - mOrigin );
445 updateCameraFromPose();
446}
447
449{
450 mCameraPose.setDistanceFromCenterPoint( mCameraPose.distanceFromCenterPoint() * factor );
451 updateCameraFromPose();
452}
453
455{
456 mCameraPose.setPitchAngle( std::clamp( mCameraPose.pitchAngle() + angleDiff, 0.f, 90.f ) );
457 updateCameraFromPose();
458}
459
461{
462 mCameraPose.setHeadingAngle( mCameraPose.headingAngle() + angleDiff );
463 updateCameraFromPose();
464}
465
466void QgsCameraController::resetGlobe( float distance, double lat, double lon )
467{
468 QgsVector3D mapPoint;
469 try
470 {
471 mapPoint = mGlobeCrsToLatLon.transform( QgsVector3D( lon, lat, 0 ), Qgis::TransformDirection::Reverse );
472 }
473 catch ( const QgsCsException & )
474 {
475 QgsDebugError( u"resetGlobe: transform failed!"_s );
476 return;
477 }
478
479 QgsCameraPose cp;
480 cp.setCenterPoint( mapPoint - mOrigin );
482 setCameraPose( cp );
483}
484
485void QgsCameraController::updateOrthographicProjectionPlane()
486{
487 // When using orthographic projection, reuse the distance to center (which
488 // ordinarily wouldn't do anything) to set the viewport size in the world.
490 {
491 const QSize viewportRect = mScene->engine()->size();
492 const float viewWidthFromCenter = distance();
493 const float viewHeightFromCenter = distance() * static_cast<float>( viewportRect.height() ) / static_cast<float>( viewportRect.width() );
494 mCamera->lens()->setOrthographicProjection( -viewWidthFromCenter, viewWidthFromCenter, -viewHeightFromCenter, viewHeightFromCenter, mCamera->nearPlane(), mCamera->farPlane() );
495 }
496}
497
498void QgsCameraController::updateCameraFromPose()
499{
500 if ( mCamera )
501 {
502 if ( mScene->mapSettings()->sceneMode() == Qgis::SceneMode::Globe )
503 {
504 const QgsVector3D viewCenter = mCameraPose.centerPoint() + mOrigin;
505
506 QgsVector3D viewCenterLatLon;
507 try
508 {
509 viewCenterLatLon = mGlobeCrsToLatLon.transform( viewCenter );
510 }
511 catch ( const QgsCsException & )
512 {
513 QgsDebugError( u"updateCameraFromPose: transform failed!"_s );
514 return;
515 }
516
517 mCameraPose.updateCameraGlobe( mCamera, viewCenterLatLon.y(), viewCenterLatLon.x() );
518 }
519 else
520 {
521 mCameraPose.updateCamera( mCamera );
522 }
523
524 updateOrthographicProjectionPlane();
525
526 mCameraChanged = true;
527 }
528}
529
530void QgsCameraController::moveCenterPoint( const QVector3D &posDiff )
531{
532 mCameraPose.setCenterPoint( mCameraPose.centerPoint() + posDiff );
533 updateCameraFromPose();
534}
535
536void QgsCameraController::onPositionChanged( Qt3DInput::QMouseEvent *mouse )
537{
538 if ( !mInputHandlersEnabled )
539 return;
540
541 QgsScopedEvent traceEvent( u"3D"_s, u"QgsCameraController::onPositionChanged"_s );
542
543 switch ( mCameraNavigationMode )
544 {
546 onPositionChangedTerrainNavigation( mouse );
547 break;
548
550 onPositionChangedFlyNavigation( mouse );
551 break;
552
554 onPositionChangedGlobeTerrainNavigation( mouse );
555 break;
556 }
557}
558
559bool QgsCameraController::screenPointToWorldPos( QPoint position, double &depth, QVector3D &worldPosition )
560{
561 depth = sampleDepthBuffer( position.x(), position.y() );
562
563 // if there's nothing around the given position, try to get just any depth
564 // from the scene as a coarse approximation...
565 if ( depth == 1 )
566 {
567 depth = depthBufferNonVoidAverage();
568 }
569
570 worldPosition = Qgs3DUtils::screenPointToWorldPos( position, depth, mScene->engine()->size(), mDepthBufferCamera.get() );
571 if ( !std::isfinite( worldPosition.x() ) || !std::isfinite( worldPosition.y() ) || !std::isfinite( worldPosition.z() ) )
572 {
573 QgsDebugMsgLevel( u"screenPointToWorldPos: position is NaN or Inf. This should not happen."_s, 2 );
574 return false;
575 }
576
577 return true;
578}
579
580void QgsCameraController::onPositionChangedTerrainNavigation( Qt3DInput::QMouseEvent *mouse )
581{
582 if ( mIgnoreNextMouseMove )
583 {
584 mIgnoreNextMouseMove = false;
585 mMousePos = QPoint( mouse->x(), mouse->y() );
586 return;
587 }
588
589 const int dx = mouse->x() - mMousePos.x();
590 const int dy = mouse->y() - mMousePos.y();
591
592 const bool hasShift = ( mouse->modifiers() & Qt3DInput::QMouseEvent::Modifiers::ShiftModifier );
593 const bool hasCtrl = ( mouse->modifiers() & Qt3DInput::QMouseEvent::Modifiers::ControlModifier );
594 const bool hasLeftButton = ( mouse->buttons() & Qt::LeftButton );
595 const bool hasMiddleButton = ( mouse->buttons() & Qt::MiddleButton );
596 const bool hasRightButton = ( mouse->buttons() & Qt::RightButton );
597
598 if ( ( hasLeftButton && hasShift && !hasCtrl ) || ( hasMiddleButton && !hasShift && !hasCtrl ) )
599 {
600 // rotate/tilt using mouse (camera moves as it rotates around the clicked point)
601 setMouseParameters( MouseOperation::RotationCenter, mMousePos );
602
603 float scale = static_cast<float>( std::max( mScene->engine()->size().width(), mScene->engine()->size().height() ) );
604 float pitchDiff = -180.0f * static_cast<float>( mouse->y() - mClickPoint.y() ) / scale;
605 float yawDiff = -180.0f * static_cast<float>( mouse->x() - mClickPoint.x() ) / scale;
606
607 if ( mVerticalAxisInversion & Qgis::VerticalAxisInversion::WhenPivoting )
608 pitchDiff *= -1;
609
610 if ( !mDepthBufferIsReady )
611 return;
612
613 if ( !mRotationCenterCalculated )
614 {
615 double depth;
616 QVector3D worldPosition;
617 if ( screenPointToWorldPos( mClickPoint, depth, worldPosition ) )
618 {
619 mRotationCenter = worldPosition;
620 mRotationDistanceFromCenter = ( mRotationCenter - mCameraBefore->position() ).length();
621 emit cameraRotationCenterChanged( mRotationCenter );
622 mRotationCenterCalculated = true;
623 }
624 }
625
626 rotateCameraAroundPivot( mRotationPitch + pitchDiff, mRotationYaw + yawDiff, mRotationCenter );
627 }
628 else if ( hasLeftButton && hasCtrl && !hasShift )
629 {
630 setMouseParameters( MouseOperation::RotationCamera );
631 // rotate/tilt using mouse (camera stays at one position as it rotates)
632 applyRelativePointerRotation( dx, dy );
633 }
634 else if ( hasLeftButton && !hasShift && !hasCtrl )
635 {
636 // translation works as if one grabbed a point on the 3D viewer and dragged it
637 setMouseParameters( MouseOperation::Translation, mMousePos );
638
639 if ( !mDepthBufferIsReady )
640 return;
641
642 if ( !mDragPointCalculated )
643 {
644 double depth;
645 QVector3D worldPosition;
646 if ( screenPointToWorldPos( mClickPoint, depth, worldPosition ) )
647 {
648 mDragDepth = depth;
649 mDragPoint = worldPosition;
650 mDragPointCalculated = true;
651 }
652 }
653
654 QVector3D cameraBeforeDragPos = mCameraBefore->position();
655 QVector3D moveToPosition = Qgs3DUtils::screenPointToWorldPos( { mouse->x(), mouse->y() }, mDragDepth, mScene->engine()->size(), mCameraBefore.get() );
656
657 QVector3D shiftVector;
658 // Compute angle of camera's view vector to ground and decide if moving
659 // the cursor up-down should change altitude or latitude/longitude.
660 float angle = std::fabs( std::acos( QVector3D::dotProduct( QVector3D( 0, 0, 1 ), mCameraBefore->viewVector().normalized() ) ) - M_PI / 2 );
661 bool changeAltitude = false;
662 // Choose threshold angle based on projection type so it "feels right".
663 switch ( mScene->mapSettings()->projectionType() )
664 {
666 changeAltitude = angle < M_PI / 30;
667 break;
669 changeAltitude = angle < M_PI / 3;
670 break;
671 default:
672 QgsDebugError( "Unhandled 3D projection type" );
673 }
674
675 if ( changeAltitude )
676 shiftVector = mDragPoint - moveToPosition;
677 else
678 switch ( mScene->mapSettings()->projectionType() )
679 {
681 {
682 // Project change to XY plane.
683 // This isn't quite accurate at higher angles, "desyncing" the mouse
684 // cursor and the dragged point.
685 shiftVector = { mDragPoint.x() - moveToPosition.x(), mDragPoint.y() - moveToPosition.y(), 0 };
686 break;
687 }
689 {
690 QVector3D cameraBeforeToMoveToPos = ( moveToPosition - mCameraBefore->position() ).normalized();
691 QVector3D cameraBeforeToDragPointPos = ( mDragPoint - mCameraBefore->position() ).normalized();
692
693 // Make sure the rays are not horizontal (add small z shift if it is)
694 if ( cameraBeforeToMoveToPos.z() == 0 )
695 {
696 cameraBeforeToMoveToPos.setZ( 0.01 );
697 cameraBeforeToMoveToPos = cameraBeforeToMoveToPos.normalized();
698 }
699
700 if ( cameraBeforeToDragPointPos.z() == 0 )
701 {
702 cameraBeforeToDragPointPos.setZ( 0.01 );
703 cameraBeforeToDragPointPos = cameraBeforeToDragPointPos.normalized();
704 }
705
706 float d1 = ( mDragPoint.z() - cameraBeforeDragPos.z() ) / cameraBeforeToMoveToPos.z();
707 float d2 = ( mDragPoint.z() - cameraBeforeDragPos.z() ) / cameraBeforeToDragPointPos.z();
708
709 QVector3D from = cameraBeforeDragPos + d1 * cameraBeforeToMoveToPos;
710 QVector3D to = cameraBeforeDragPos + d2 * cameraBeforeToDragPointPos;
711
712 shiftVector = to - from;
713 break;
714 }
715 default:
716 QgsDebugError( "Unhandled 3D projection type" );
717 }
718
719 mCameraPose.setCenterPoint( mCameraBefore->viewCenter() + shiftVector );
720 updateCameraFromPose();
721 }
722 else if ( hasLeftButton && hasShift && hasCtrl )
723 {
724 // change the camera elevation, similar to pageUp/pageDown
725 QgsVector3D center = mCameraPose.centerPoint();
726 double tElev = mMousePos.y() - mouse->y();
727 center.set( center.x(), center.y(), center.z() + tElev * 0.5 );
728 mCameraPose.setCenterPoint( center );
729 updateCameraFromPose();
730 }
731 else if ( hasRightButton && !hasShift && !hasCtrl )
732 {
733 setMouseParameters( MouseOperation::Zoom, mMousePos );
734 if ( !mDepthBufferIsReady )
735 return;
736
737 if ( !mDragPointCalculated )
738 {
739 double depth;
740 QVector3D worldPosition;
741 if ( screenPointToWorldPos( mClickPoint, depth, worldPosition ) )
742 {
743 mDragPoint = worldPosition;
744 mDragPointCalculated = true;
745 }
746 }
747
748 const double oldDist = ( QgsVector3D( mCameraBefore->position() ) - QgsVector3D( mDragPoint ) ).length();
749 double newDist = oldDist;
750
751 int yOffset = 0;
752 int screenHeight = mScene->engine()->size().height();
753 QWindow *win = window();
754 if ( win )
755 {
756 yOffset = win->mapToGlobal( QPoint( 0, 0 ) ).y();
757 screenHeight = win->screen()->virtualSize().height();
758 }
759
760 // Applies smoothing
761 if ( mMousePos.y() > mClickPoint.y() ) // zoom in
762 {
763 double f = ( double ) ( mMousePos.y() - mClickPoint.y() ) / ( double ) ( screenHeight - mClickPoint.y() - yOffset );
764 f = std::max( 0.0, std::min( 1.0, f ) );
765 f = 1 - ( std::expm1( -2 * f ) ) / ( std::expm1( -2 ) );
766 newDist = newDist * f;
767 }
768 else // zoom out
769 {
770 double f = 1 - ( double ) ( mMousePos.y() + yOffset ) / ( double ) ( mClickPoint.y() + yOffset );
771 f = std::max( 0.0, std::min( 1.0, f ) );
772 f = ( std::expm1( 2 * f ) ) / ( std::expm1( 2 ) );
773 newDist = newDist + 2 * newDist * f;
774 }
775
776 const double zoomFactor = newDist / oldDist;
777 zoomCameraAroundPivot( mCameraBefore->position(), mCameraBefore->viewCenter().distanceToPoint( mCameraBefore->position() ), zoomFactor, mDragPoint );
778 }
779
780 mMousePos = QPoint( mouse->x(), mouse->y() );
781}
782
783void QgsCameraController::onPositionChangedGlobeTerrainNavigation( Qt3DInput::QMouseEvent *mouse )
784{
785 const bool hasShift = ( mouse->modifiers() & Qt3DInput::QMouseEvent::Modifiers::ShiftModifier );
786 const bool hasCtrl = ( mouse->modifiers() & Qt3DInput::QMouseEvent::Modifiers::ControlModifier );
787 const bool hasLeftButton = ( mouse->buttons() & Qt::LeftButton );
788 const bool hasMiddleButton = ( mouse->buttons() & Qt::MiddleButton );
789
790 if ( ( hasLeftButton && hasShift && !hasCtrl ) || ( hasMiddleButton && !hasShift && !hasCtrl ) )
791 {
792 setMouseParameters( MouseOperation::RotationCenter, mMousePos );
793
794 const float scale = static_cast<float>( std::max( mScene->engine()->size().width(), mScene->engine()->size().height() ) );
795 float pitchDiff = -180.0f * static_cast<float>( mouse->y() - mClickPoint.y() ) / scale;
796 const float yawDiff = -180.0f * static_cast<float>( mouse->x() - mClickPoint.x() ) / scale;
797
798 if ( mVerticalAxisInversion & Qgis::VerticalAxisInversion::WhenPivoting )
799 pitchDiff *= -1;
800
801 mCameraPose.setPitchAngle( mRotationPitch + pitchDiff );
802 mCameraPose.setHeadingAngle( mRotationYaw + yawDiff );
803 updateCameraFromPose();
804 return;
805 }
806
807 if ( !( mouse->buttons() & Qt::LeftButton ) )
808 return;
809
810 // translation works as if one grabbed a point on the 3D viewer and dragged it
811 setMouseParameters( MouseOperation::Translation, mMousePos );
812
813 if ( !mDepthBufferIsReady )
814 return;
815
816 if ( !mDragPointCalculated )
817 {
818 double depth;
819 QVector3D worldPosition;
820 if ( !screenPointToWorldPos( mClickPoint, depth, worldPosition ) )
821 return;
822
823 mDragDepth = depth;
824 mDragPoint = worldPosition;
825 mDragPointCalculated = true;
826 }
827
828 // Approximate the globe as a sphere with a center in (0,0,0) map coords and
829 // of radius the same as at startPosMap.
830 const QgsVector3D startPosMap = QgsVector3D( mDragPoint ) + mOrigin;
831 const double sphereRadiusMap = startPosMap.length();
832 // Find the intersection of this sphere and the ray from the current clicked point.
833 const QgsRay3D ray = Qgs3DUtils::rayFromScreenPoint( QPoint( mouse->x(), mouse->y() ), mScene->engine()->size(), mCameraBefore.get() );
834 const QgsVector3D rayOriginMap = QgsVector3D( ray.origin() ) + mOrigin;
835 // From equations of ray and sphere
836 const double quadA = QVector3D::dotProduct( ray.direction(), ray.direction() );
837 const double quadB = 2 * QgsVector3D::dotProduct( ray.direction(), rayOriginMap );
838 const double quadC = QgsVector3D::dotProduct( rayOriginMap, rayOriginMap ) - sphereRadiusMap * sphereRadiusMap;
839 const double disc = quadB * quadB - 4 * quadA * quadC;
840 if ( disc < 0 )
841 // Ray misses sphere
842 return;
843 // Distance to intersection along ray (take smaller root, closer to camera)
844 const double rayDistMap = ( -quadB - sqrt( disc ) ) / ( 2 * quadA );
845 if ( rayDistMap < 0 )
846 {
847 QgsDebugError( u"Sphere intersection result negative, canceling move"_s );
848 return;
849 }
850 const QgsVector3D newPosMap = rayOriginMap + QgsVector3D( ray.direction() ) * rayDistMap;
851
852 // now that we have old and new mouse position in ECEF coordinates,
853 // let's figure out the difference in lat/lon angles and update the center point
854
855 QgsVector3D oldLatLon, newLatLon;
856 try
857 {
858 oldLatLon = mGlobeCrsToLatLon.transform( startPosMap );
859 newLatLon = mGlobeCrsToLatLon.transform( newPosMap );
860 }
861 catch ( const QgsCsException & )
862 {
863 QgsDebugError( u"onPositionChangedGlobeTerrainNavigation: transform failed!"_s );
864 return;
865 }
866
867 const double latDiff = oldLatLon.y() - newLatLon.y();
868 const double lonDiff = oldLatLon.x() - newLatLon.x();
869
870 const QgsVector3D newVC = moveGeocentricPoint( mMousePressViewCenter, latDiff, lonDiff );
871 const QgsVector3D newVCWorld = newVC - mOrigin;
872
873 mCameraPose.setCenterPoint( newVCWorld );
874 updateCameraFromPose();
875}
876
877
878void QgsCameraController::zoom( float factor )
879{
880 // zoom in/out
881 float dist = mCameraPose.distanceFromCenterPoint();
882 dist -= dist * factor * 0.01f;
883 mCameraPose.setDistanceFromCenterPoint( dist );
884 updateCameraFromPose();
885}
886
887void QgsCameraController::handleTerrainNavigationWheelZoom()
888{
889 if ( !mDepthBufferIsReady )
890 return;
891
892 if ( !mZoomPointCalculated )
893 {
894 double depth;
895 QVector3D worldPosition;
896 if ( screenPointToWorldPos( mMousePos, depth, worldPosition ) )
897 {
898 mZoomPoint = worldPosition;
899 mZoomPointCalculated = true;
900 }
901 }
902
903 double oldDist = ( mZoomPoint - mCameraBefore->position() ).length();
904 // Each step of the scroll wheel decreases distance by 20%
905 double newDist = std::pow( 0.8, mCumulatedWheelY ) * oldDist;
906 // Make sure we don't clip the thing we're zooming to.
907 newDist = std::max( newDist, 2.0 );
908 double zoomFactor = newDist / oldDist;
909 // Don't change the distance too suddenly to hopefully prevent numerical instability
910 zoomFactor = std::clamp( zoomFactor, 0.01, 100.0 );
911
912 zoomCameraAroundPivot( mCameraBefore->position(), mCameraBefore->viewCenter().distanceToPoint( mCameraBefore->position() ), zoomFactor, mZoomPoint );
913
914 mCumulatedWheelY = 0;
915 setMouseParameters( MouseOperation::None );
916}
917
918void QgsCameraController::onWheel( Qt3DInput::QWheelEvent *wheel )
919{
920 if ( !mInputHandlersEnabled )
921 return;
922
923 switch ( mCameraNavigationMode )
924 {
926 {
927 const float scaling = ( ( wheel->modifiers() & Qt3DInput::QWheelEvent::Modifiers::ControlModifier ) != 0 ? 0.1f : 1.0f ) / 1000.f;
928 setCameraMovementSpeed( mCameraMovementSpeed + mCameraMovementSpeed * scaling * wheel->angleDelta().y() );
929 break;
930 }
931
933 {
934 // Scale our variable to roughly "number of normal steps", with Ctrl
935 // increasing granularity 10x
936 const double scaling = ( 1.0 / 120.0 ) * ( ( wheel->modifiers() & Qt3DInput::QWheelEvent::Modifiers::ControlModifier ) != 0 ? 0.1 : 1.0 );
937
938 // Apparently angleDelta needs to be accumulated
939 // see: https://doc.qt.io/qt-6/qwheelevent.html#angleDelta
940 mCumulatedWheelY += scaling * wheel->angleDelta().y();
941
942 if ( mCurrentOperation != MouseOperation::ZoomWheel )
943 {
944 setMouseParameters( MouseOperation::ZoomWheel );
945 // The actual zooming will happen after we get a new depth buffer
946 }
947 else
948 {
949 handleTerrainNavigationWheelZoom();
950 }
951 break;
952 }
953
955 {
956 float wheelAmount = static_cast<float>( wheel->angleDelta().y() );
957 float factor = abs( wheelAmount ) / 1000.f;
958 float mulFactor = wheelAmount > 0 ? ( 1 - factor ) : ( 1 + factor );
959 mCameraPose.setDistanceFromCenterPoint( mCameraPose.distanceFromCenterPoint() * mulFactor );
960 updateCameraFromPose();
961 break;
962 }
963 }
964}
965
966void QgsCameraController::onMousePressed( Qt3DInput::QMouseEvent *mouse )
967{
968 if ( !mInputHandlersEnabled )
969 return;
970
971 mKeyboardHandler->setFocus( true );
972
973 if ( mouse->button() == Qt3DInput::QMouseEvent::MiddleButton
974 || ( ( mouse->modifiers() & Qt3DInput::QMouseEvent::Modifiers::ShiftModifier ) != 0 && mouse->button() == Qt3DInput::QMouseEvent::LeftButton )
975 || ( ( mouse->modifiers() & Qt3DInput::QMouseEvent::Modifiers::ControlModifier ) != 0 && mouse->button() == Qt3DInput::QMouseEvent::LeftButton ) )
976 {
977 mMousePos = QPoint( mouse->x(), mouse->y() );
978
979 if ( mCaptureFpsMouseMovements )
980 mIgnoreNextMouseMove = true;
981
982 const MouseOperation operation {
983 ( mouse->modifiers() & Qt3DInput::QMouseEvent::Modifiers::ControlModifier ) != 0 && mouse->button() == Qt3DInput::QMouseEvent::LeftButton ? MouseOperation::RotationCamera
984 : MouseOperation::RotationCenter
985 };
986 setMouseParameters( operation, mMousePos );
987 }
988
989 else if ( mouse->button() == Qt3DInput::QMouseEvent::LeftButton || mouse->button() == Qt3DInput::QMouseEvent::RightButton )
990 {
991 mMousePos = QPoint( mouse->x(), mouse->y() );
992
993 if ( mCaptureFpsMouseMovements )
994 mIgnoreNextMouseMove = true;
995
996 const MouseOperation operation = ( mouse->button() == Qt3DInput::QMouseEvent::LeftButton ) ? MouseOperation::Translation : MouseOperation::Zoom;
997 setMouseParameters( operation, mMousePos );
998 }
999}
1000
1001void QgsCameraController::onMouseReleased( Qt3DInput::QMouseEvent *mouse )
1002{
1003 Q_UNUSED( mouse )
1004 if ( !mInputHandlersEnabled )
1005 return;
1006
1007
1008 setMouseParameters( MouseOperation::None );
1009}
1010
1011bool QgsCameraController::onKeyPressedTerrainNavigation( QKeyEvent *event )
1012{
1013 const bool hasShift = ( event->modifiers() & Qt::ShiftModifier );
1014 const bool hasCtrl = ( event->modifiers() & Qt::ControlModifier );
1015
1016 int tx = 0, ty = 0, tElev = 0;
1017 switch ( event->key() )
1018 {
1019 case Qt::Key_Left:
1020 tx -= 1;
1021 break;
1022 case Qt::Key_Right:
1023 tx += 1;
1024 break;
1025
1026 case Qt::Key_Up:
1027 ty += 1;
1028 break;
1029 case Qt::Key_Down:
1030 ty -= 1;
1031 break;
1032
1033 case Qt::Key_PageDown:
1034 tElev -= 1;
1035 break;
1036 case Qt::Key_PageUp:
1037 tElev += 1;
1038 break;
1039 default:
1040 break;
1041 }
1042
1043 if ( tx || ty )
1044 {
1045 if ( !hasShift && !hasCtrl )
1046 {
1047 moveView( tx, ty );
1048 }
1049 else if ( hasShift && !hasCtrl )
1050 {
1051 // rotate/tilt using keyboard (camera moves as it rotates around its view center)
1054 }
1055 else if ( hasCtrl && !hasShift )
1056 {
1057 // rotate/tilt using keyboard (camera stays at one position as it rotates)
1058 const float diffPitch = ty; // down key = rotating camera down
1059 const float diffYaw = -tx; // right key = rotating camera to the right
1060 rotateCamera( diffPitch, diffYaw );
1061 }
1062 return true;
1063 }
1064
1065 if ( tElev )
1066 {
1067 QgsVector3D center = mCameraPose.centerPoint();
1068 center.set( center.x(), center.y(), center.z() + tElev * 10 );
1069 mCameraPose.setCenterPoint( center );
1070 return true;
1071 }
1072
1073 return false;
1074}
1075
1076bool QgsCameraController::onKeyPressedGlobeTerrainNavigation( QKeyEvent *event )
1077{
1078 // both move factor and zoom factor are just empirically picked numbers
1079 // that seem to work well (providing steps that are not too big / not too small)
1080 constexpr float MOVE_FACTOR = 0.000001f; // multiplied by distance to get angle
1081 constexpr float ZOOM_FACTOR = 0.9f;
1082
1083 const bool hasShift = ( event->modifiers() & Qt::ShiftModifier );
1084
1085 switch ( event->key() )
1086 {
1087 case Qt::Key_Left:
1088 if ( hasShift )
1090 else
1091 globeMoveCenterPoint( 0, -MOVE_FACTOR * mCameraPose.distanceFromCenterPoint() );
1092 return true;
1093 case Qt::Key_Right:
1094 if ( hasShift )
1096 else
1097 globeMoveCenterPoint( 0, MOVE_FACTOR * mCameraPose.distanceFromCenterPoint() );
1098 return true;
1099 case Qt::Key_Up:
1100 if ( hasShift )
1102 else
1103 globeMoveCenterPoint( MOVE_FACTOR * mCameraPose.distanceFromCenterPoint(), 0 );
1104 return true;
1105 case Qt::Key_Down:
1106 if ( hasShift )
1108 else
1109 globeMoveCenterPoint( -MOVE_FACTOR * mCameraPose.distanceFromCenterPoint(), 0 );
1110 return true;
1111 case Qt::Key_PageDown:
1112 globeZoom( ZOOM_FACTOR );
1113 return true;
1114 case Qt::Key_PageUp:
1115 globeZoom( 1 / ZOOM_FACTOR );
1116 return true;
1117 default:
1118 break;
1119 }
1120 return false;
1121}
1122
1123static const QSet<int> walkNavigationSavedKeys = {
1124 Qt::Key_Left,
1125 Qt::Key_A,
1126 Qt::Key_Right,
1127 Qt::Key_D,
1128 Qt::Key_Up,
1129 Qt::Key_W,
1130 Qt::Key_Down,
1131 Qt::Key_S,
1132 Qt::Key_PageUp,
1133 Qt::Key_E,
1134 Qt::Key_PageDown,
1135 Qt::Key_Q,
1136};
1137
1138bool QgsCameraController::onKeyPressedFlyNavigation( QKeyEvent *event )
1139{
1140 switch ( event->key() )
1141 {
1142 case Qt::Key_QuoteLeft:
1143 {
1144 // toggle mouse lock mode
1145 mCaptureFpsMouseMovements = !mCaptureFpsMouseMovements;
1146 mIgnoreNextMouseMove = true;
1147
1148 if ( mCaptureFpsMouseMovements )
1149 {
1150 if ( mPointerLocker )
1151 {
1152 mPointerLocker->lock();
1153 }
1154 qApp->setOverrideCursor( QCursor( Qt::BlankCursor ) );
1155 }
1156 else
1157 {
1158 if ( mPointerLocker )
1159 {
1160 mPointerLocker->unlock();
1161 }
1162 qApp->restoreOverrideCursor();
1163 }
1164 event->accept();
1165 return true;
1166 }
1167
1168 case Qt::Key_Escape:
1169 {
1170 // always exit mouse lock mode
1171 if ( mCaptureFpsMouseMovements )
1172 {
1173 mCaptureFpsMouseMovements = false;
1174 mIgnoreNextMouseMove = true;
1175 if ( mPointerLocker )
1176 {
1177 mPointerLocker->unlock();
1178 }
1179
1180 qApp->restoreOverrideCursor();
1181 event->accept();
1182 return true;
1183 }
1184 break;
1185 }
1186 default:
1187 break;
1188 }
1189
1190 if ( walkNavigationSavedKeys.contains( event->key() ) )
1191 {
1192 if ( !event->isAutoRepeat() )
1193 {
1194 mDepressedKeys.insert( event->key() );
1195 }
1196 event->accept();
1197 return true;
1198 }
1199 return false;
1200}
1201
1202void QgsCameraController::walkView( double tx, double ty, double tz )
1203{
1204 const QVector3D cameraUp = mCamera->upVector().normalized();
1205 const QVector3D cameraFront = ( QVector3D( mCameraPose.centerPoint().x(), mCameraPose.centerPoint().y(), mCameraPose.centerPoint().z() ) - mCamera->position() ).normalized();
1206 const QVector3D cameraLeft = QVector3D::crossProduct( cameraUp, cameraFront );
1207
1208 QVector3D cameraPosDiff( 0.0f, 0.0f, 0.0f );
1209
1210 if ( tx != 0.0 )
1211 {
1212 cameraPosDiff += static_cast<float>( tx ) * cameraFront;
1213 }
1214 if ( ty != 0.0 )
1215 {
1216 cameraPosDiff += static_cast<float>( ty ) * cameraLeft;
1217 }
1218 if ( tz != 0.0 )
1219 {
1220 cameraPosDiff += static_cast<float>( tz ) * QVector3D( 0.0f, 0.0f, 1.0f );
1221 }
1222
1223 moveCenterPoint( cameraPosDiff );
1224}
1225
1226void QgsCameraController::applyFlyModeKeyMovements()
1227{
1228 if ( mCameraNavigationMode != Qgis::NavigationMode::Walk )
1229 return;
1230
1231 // shift = "run", ctrl = "slow walk"
1232 const bool shiftPressed = mDepressedKeys.contains( Qt::Key_Shift );
1233 const bool ctrlPressed = mDepressedKeys.contains( Qt::Key_Control );
1234
1235 const double movementSpeed = mCameraMovementSpeed * ( shiftPressed ? 2 : 1 ) * ( ctrlPressed ? 0.1 : 1 );
1236
1237 bool changed = false;
1238 double x = 0.0;
1239 double y = 0.0;
1240 double z = 0.0;
1241 if ( mDepressedKeys.contains( Qt::Key_Left ) || mDepressedKeys.contains( Qt::Key_A ) )
1242 {
1243 changed = true;
1244 y += movementSpeed;
1245 }
1246
1247 if ( mDepressedKeys.contains( Qt::Key_Right ) || mDepressedKeys.contains( Qt::Key_D ) )
1248 {
1249 changed = true;
1250 y -= movementSpeed;
1251 }
1252
1253 if ( mDepressedKeys.contains( Qt::Key_Up ) || mDepressedKeys.contains( Qt::Key_W ) )
1254 {
1255 changed = true;
1256 x += movementSpeed;
1257 }
1258
1259 if ( mDepressedKeys.contains( Qt::Key_Down ) || mDepressedKeys.contains( Qt::Key_S ) )
1260 {
1261 changed = true;
1262 x -= movementSpeed;
1263 }
1264
1265 // note -- vertical axis movements are slower by default then horizontal ones, as GIS projects
1266 // tend to have much more limited elevation range vs ground range
1267 static constexpr double ELEVATION_MOVEMENT_SCALE = 0.5;
1268 if ( mDepressedKeys.contains( Qt::Key_PageUp ) || mDepressedKeys.contains( Qt::Key_E ) )
1269 {
1270 changed = true;
1271 z += ELEVATION_MOVEMENT_SCALE * movementSpeed;
1272 }
1273
1274 if ( mDepressedKeys.contains( Qt::Key_PageDown ) || mDepressedKeys.contains( Qt::Key_Q ) )
1275 {
1276 changed = true;
1277 z -= ELEVATION_MOVEMENT_SCALE * movementSpeed;
1278 }
1279
1280 if ( changed )
1281 walkView( x, y, z );
1282}
1283
1284void QgsCameraController::onPositionChangedFlyNavigation( Qt3DInput::QMouseEvent *mouse )
1285{
1286 const bool hasMiddleButton = ( mouse->buttons() & Qt::MiddleButton );
1287 const bool hasRightButton = ( mouse->buttons() & Qt::RightButton );
1288
1289 const double dx = mCaptureFpsMouseMovements ? QCursor::pos().x() - mMousePos.x() : mouse->x() - mMousePos.x();
1290 const double dy = mCaptureFpsMouseMovements ? QCursor::pos().y() - mMousePos.y() : mouse->y() - mMousePos.y();
1291 mMousePos = mCaptureFpsMouseMovements ? QCursor::pos() : QPoint( mouse->x(), mouse->y() );
1292
1293 if ( mIgnoreNextMouseMove )
1294 {
1295 mIgnoreNextMouseMove = false;
1296 return;
1297 }
1298
1299 if ( hasMiddleButton )
1300 {
1301 // middle button drag = pan camera in place (strafe)
1302 const QVector3D cameraUp = mCamera->upVector().normalized();
1303 const QVector3D cameraFront = ( QVector3D( mCameraPose.centerPoint().x(), mCameraPose.centerPoint().y(), mCameraPose.centerPoint().z() ) - mCamera->position() ).normalized();
1304 const QVector3D cameraLeft = QVector3D::crossProduct( cameraUp, cameraFront );
1305 const QVector3D cameraPosDiff = -dx * cameraLeft - dy * cameraUp;
1306 moveCenterPoint( static_cast<float>( mCameraMovementSpeed ) * cameraPosDiff / 10.0 );
1307 }
1308 else if ( hasRightButton )
1309 {
1310 // right button drag = camera dolly
1311 const QVector3D cameraFront = ( QVector3D( mCameraPose.centerPoint().x(), mCameraPose.centerPoint().y(), mCameraPose.centerPoint().z() ) - mCamera->position() ).normalized();
1312 const QVector3D cameraPosDiff = dy * cameraFront;
1313 moveCenterPoint( static_cast<float>( mCameraMovementSpeed ) * cameraPosDiff / 5.0 );
1314 }
1315 else
1316 {
1317 if ( mCaptureFpsMouseMovements )
1318 {
1319 // if we have a pointer locker this is handled elsewhere
1320 if ( !mPointerLocker )
1321 {
1322 applyRelativePointerRotation( dx, dy );
1323 }
1324 }
1325 else if ( mouse->buttons() & Qt::LeftButton )
1326 {
1327 applyRelativePointerRotation( dx, dy );
1328 }
1329 }
1330
1331 if ( mCaptureFpsMouseMovements )
1332 {
1333 if ( !mPointerLocker )
1334 {
1335 // reset cursor back to center of map widget
1336 mIgnoreNextMouseMove = true;
1337 emit setCursorPosition( QPoint( mScene->engine()->size().width() / 2, mScene->engine()->size().height() / 2 ) );
1338 }
1339 }
1340}
1341
1343{
1344 // Tilt up the view by deltaPitch around the view center (camera moves)
1345 float pitch = mCameraPose.pitchAngle();
1346 pitch -= deltaPitch; // down key = moving camera toward terrain
1347 mCameraPose.setPitchAngle( pitch );
1348 updateCameraFromPose();
1349}
1350
1352{
1353 // Rotate clockwise the view by deltaYaw around the view center (camera moves)
1354 float yaw = mCameraPose.headingAngle();
1355 yaw -= deltaYaw; // right key = moving camera clockwise
1356 mCameraPose.setHeadingAngle( yaw );
1357 updateCameraFromPose();
1358}
1359
1361{
1362 mCameraPose.setHeadingAngle( angle );
1363 updateCameraFromPose();
1364}
1365
1366void QgsCameraController::moveView( float tx, float ty )
1367{
1368 const float yaw = mCameraPose.headingAngle();
1369 const float dist = mCameraPose.distanceFromCenterPoint();
1370 const float x = tx * dist * 0.02f;
1371 const float y = -ty * dist * 0.02f;
1372
1373 // moving with keyboard - take into account yaw of camera
1374 const float t = sqrt( x * x + y * y );
1375 const float a = atan2( y, x ) - yaw * M_PI / 180;
1376 const float dx = cos( a ) * t;
1377 const float dy = sin( a ) * t;
1378
1379 QgsVector3D center = mCameraPose.centerPoint();
1380 center.set( center.x() + dx, center.y() - dy, center.z() );
1381 mCameraPose.setCenterPoint( center );
1382 updateCameraFromPose();
1383}
1384
1386{
1387 if ( !mInputHandlersEnabled )
1388 return false;
1389
1390 if ( event->type() == QKeyEvent::Type::KeyRelease )
1391 {
1392 if ( !event->isAutoRepeat() && mDepressedKeys.contains( event->key() ) )
1393 {
1394 mDepressedKeys.remove( event->key() );
1395 return true;
1396 }
1397 }
1398 else if ( event->type() == QEvent::ShortcutOverride )
1399 {
1400 if ( event->modifiers() & Qt::ControlModifier )
1401 {
1402 switch ( event->key() )
1403 {
1404 case Qt::Key_QuoteLeft:
1405 {
1406 // switch navigation mode
1407 switch ( mCameraNavigationMode )
1408 {
1410 // clang-format off
1412 mScene->mapSettings()->sceneMode() == Qgis::SceneMode::Globe
1415 );
1416 // clang-format on
1417 break;
1421 break;
1422 }
1423 event->accept();
1424 return true;
1425 }
1426
1427 // Make sure to sync the key combinations with strings in Qgs3DAxis::createMenu()!
1428 case Qt::Key_8:
1430 return true;
1431 case Qt::Key_6:
1433 return true;
1434 case Qt::Key_2:
1436 return true;
1437 case Qt::Key_4:
1439 return true;
1440 case Qt::Key_9:
1442 return true;
1443 case Qt::Key_3:
1445 return true;
1446 case Qt::Key_5:
1448 return true;
1449
1450 default:
1451 break;
1452 }
1453 }
1454
1455 switch ( mCameraNavigationMode )
1456 {
1458 return onKeyPressedFlyNavigation( event );
1459
1461 return onKeyPressedTerrainNavigation( event );
1462
1464 return onKeyPressedGlobeTerrainNavigation( event );
1465 }
1466 }
1467 return false;
1468}
1469
1470void QgsCameraController::depthBufferCaptured( const QImage &depthImage )
1471{
1472 mDepthBufferImage = depthImage;
1473 mDepthBufferIsReady = true;
1474 mDepthBufferNonVoidAverage = -1;
1475
1476 // To read distances from the captured depth buffer, we need to know the
1477 // camera parameters it was rendered with. This seems like the closest
1478 // place to save them, though I have no idea if they can't be changed
1479 // between the rendering and now anyway...
1480 mDepthBufferCamera = Qgs3DUtils::copyCamera( mCamera );
1481
1482 emit depthBufferReady();
1483
1484 if ( mCurrentOperation == MouseOperation::ZoomWheel )
1485 {
1486 handleTerrainNavigationWheelZoom();
1487 }
1488}
1489
1490bool QgsCameraController::isATranslationRotationSequence( MouseOperation newOperation ) const
1491{
1492 return std::find( mTranslateOrRotate.begin(), mTranslateOrRotate.end(), newOperation ) != std::end( mTranslateOrRotate )
1493 && std::find( mTranslateOrRotate.begin(), mTranslateOrRotate.end(), mCurrentOperation ) != std::end( mTranslateOrRotate );
1494}
1495
1496void QgsCameraController::setMouseParameters( const MouseOperation &newOperation, const QPoint &clickPoint )
1497{
1498 if ( newOperation == mCurrentOperation )
1499 {
1500 return;
1501 }
1502
1503 if ( newOperation == MouseOperation::None )
1504 {
1505 mClickPoint = QPoint();
1506 }
1507 // click point and rotation angles are updated if:
1508 // - it has never been computed
1509 // - the current and new operations are both rotation and translation
1510 // Indeed, if the sequence such as rotation -> zoom -> rotation updating mClickPoint on
1511 // the click point does not need to be updated because the relative mouse position is kept
1512 // during a zoom operation
1513 else if ( mClickPoint.isNull() || isATranslationRotationSequence( newOperation ) )
1514 {
1515 mClickPoint = clickPoint;
1516 mRotationPitch = mCameraPose.pitchAngle();
1517 mRotationYaw = mCameraPose.headingAngle();
1518 }
1519 mCurrentOperation = newOperation;
1520 mDepthBufferIsReady = false;
1521 mRotationCenterCalculated = false;
1522 mDragPointCalculated = false;
1523 mZoomPointCalculated = false;
1524
1525 if ( mCurrentOperation != MouseOperation::None && mCurrentOperation != MouseOperation::RotationCamera )
1526 {
1527 mMousePressViewCenter = mCameraPose.centerPoint() + mOrigin;
1528 mCameraBefore = Qgs3DUtils::copyCamera( mCamera );
1529
1531 }
1532}
1533
1535{
1536 QgsVector3D diff = origin - mOrigin;
1537 mCameraPose.setCenterPoint( mCameraPose.centerPoint() - diff );
1538
1539 // update other members that depend on world coordinates
1540 mCameraBefore->setPosition( ( QgsVector3D( mCameraBefore->position() ) - diff ).toVector3D() );
1541 mCameraBefore->setViewCenter( ( QgsVector3D( mCameraBefore->viewCenter() ) - diff ).toVector3D() );
1542 mDragPoint = ( QgsVector3D( mDragPoint ) - diff ).toVector3D();
1543 mRotationCenter = ( QgsVector3D( mRotationCenter ) - diff ).toVector3D();
1544
1545 mOrigin = origin;
1546
1547 updateCameraFromPose();
1548}
1549
1550void QgsCameraController::rotateToRespectingTerrain( float pitch, float yaw )
1551{
1553 double elevation = 0.0;
1554 if ( mScene->mapSettings()->terrainRenderingEnabled() )
1555 {
1556 QgsDebugMsgLevel( "Checking elevation from terrain...", 2 );
1557 QVector3D camPos = mCamera->position();
1558 const QgsRay3D ray( camPos, pos.toVector3D() - camPos );
1559 QgsRayCastContext context;
1560 context.setSingleResult( true );
1561 context.setMaximumDistance( mCamera->farPlane() );
1562 const QList<QgsRayCastHit> results = mScene->terrainEntity()->rayIntersection( ray, context );
1563
1564 if ( !results.isEmpty() )
1565 {
1566 elevation = results.constFirst().mapCoordinates().z() - mOrigin.z();
1567 QgsDebugMsgLevel( QString( "Computed elevation from terrain: %1" ).arg( elevation ), 2 );
1568 }
1569 else
1570 {
1571 QgsDebugMsgLevel( "Unable to obtain elevation from terrain", 2 );
1572 }
1573 }
1574 pos.set( pos.x(), pos.y(), elevation + mScene->terrainEntity()->terrainElevationOffset() );
1575
1576 setLookingAtPoint( pos, ( mCamera->position() - pos.toVector3D() ).length(), pitch, yaw );
1577}
1578
1580{
1581 if ( !crossSection.isValid() )
1582 return;
1583
1584 const QgsPoint startPoint = crossSection.startPoint();
1585 const QgsPoint endPoint = crossSection.endPoint();
1586 const double width = crossSection.halfWidth();
1587
1588 const QgsVector3D startVec { startPoint.x(), startPoint.y(), 0 };
1589 const QgsVector3D endVec { endPoint.x(), endPoint.y(), 0 };
1590
1591 QgsVector linePerpVec( ( endPoint - startPoint ).x(), ( endPoint - startPoint ).y() );
1592 linePerpVec = -linePerpVec.normalized().perpVector();
1593
1594 const QgsVector3D linePerpVec3D( linePerpVec.x(), linePerpVec.y(), 0 );
1595 const QgsVector3D frontStartPoint( startVec + linePerpVec3D * width );
1596 const QgsVector3D frontEndPoint( endVec + linePerpVec3D * width );
1597
1598 const QgsCameraPose camPose = Qgs3DUtils::lineSegmentToCameraPose( frontStartPoint, frontEndPoint, mScene->elevationRange( true ), mCamera->fieldOfView(), mOrigin );
1599
1600 setCameraPose( camPose );
1601}
@ WhenPivoting
When pivoting camera around point in terrain.
Definition qgis.h:4634
@ WhenRotatingCaptured
When rotating camera around self with mouse button pressed.
Definition qgis.h:4633
NavigationMode
The navigation mode used by 3D cameras.
Definition qgis.h:4606
@ TerrainBased
The default navigation based on the terrain.
Definition qgis.h:4607
@ Walk
Uses WASD keys or arrows to navigate in walking (first person) manner.
Definition qgis.h:4608
@ GlobeTerrainBased
Navigation similar to TerrainBased, but for use with globe.
Definition qgis.h:4609
QFlags< VerticalAxisInversion > VerticalAxisInversionFlags
Definition qgis.h:4643
@ Orthographic
Orthogonal projection.
Definition qgis.h:4445
@ Perspective
Perspective projection.
Definition qgis.h:4446
@ Globe
Scene is represented as a globe using a geocentric CRS.
Definition qgis.h:4621
@ Local
Local scene based on a projected CRS.
Definition qgis.h:4620
@ Reverse
Reverse/inverse transform (from destination to source).
Definition qgis.h:2899
Entity that encapsulates our 3D scene - contains all other entities (such as terrain) as children.
QgsTerrainEntity * terrainEntity() SIP_SKIP
Returns terrain entity (may be nullptr if using globe scene, terrain rendering is disabled or when te...
Qgs3DMapSettings * mapSettings() const
Returns the 3D map settings.
QgsAbstract3DEngine * engine() const SIP_SKIP
Returns the abstract 3D engine.
Qgis::Map3DProjectionType projectionType() const
Returns the camera lens' projection type.
bool terrainRenderingEnabled() const
Returns whether the 2D terrain surface will be rendered.
static QQuaternion rotationFromPitchHeadingAngles(float pitchAngle, float headingAngle)
Returns rotation quaternion that performs rotation around X axis by pitchAngle, followed by rotation ...
static std::unique_ptr< Qt3DRender::QCamera > copyCamera(Qt3DRender::QCamera *cam)
Returns new camera object with copied properties.
static double decodeDepth(const QRgb &pixel)
Decodes the depth value from the pixel's color value The depth value is encoded from OpenGL side (the...
Definition qgs3dutils.h:326
static QVector3D screenPointToWorldPos(const QPoint &screenPoint, double depth, const QSize &screenSize, Qt3DRender::QCamera *camera)
Converts the clicked mouse position to the corresponding 3D world coordinates.
static QgsRay3D rayFromScreenPoint(const QPoint &point, const QSize &windowSize, Qt3DRender::QCamera *camera)
Convert from clicked point on the screen to a ray in world coordinates.
static QgsCameraPose lineSegmentToCameraPose(const QgsVector3D &startPoint, const QgsVector3D &endPoint, const QgsDoubleRange &elevationRange, float fieldOfView, const QgsVector3D &worldOrigin)
Returns the camera pose for a camera looking at mid-point between startPoint and endPoint.
virtual QSize size() const =0
Returns size of the engine's rendering area in pixels.
void navigationModeChanged(Qgis::NavigationMode mode)
Emitted when the navigation mode is changed using the hotkey ctrl + ~.
void rotateCameraToBottom()
Rotate to bottom-up view.
void setLookingAtMapPoint(const QgsVector3D &point, float distance, float pitch, float yaw)
Sets camera configuration like setLookingAtPoint(), but the point is given in map coordinates.
float pitch() const
Returns pitch angle in degrees (0 = looking from the top, 90 = looking from the side).
Qt3DRender::QCamera * camera() const
Returns camera that is being controlled.
~QgsCameraController() override
float yaw() const
Returns yaw angle in degrees.
void requestDepthBufferCapture()
Emitted to ask for the depth buffer image.
void rotateCameraToTop()
Rotate to top-down view.
void tiltUpAroundViewCenter(float deltaPitch)
Tilt up the view by deltaPitch around the view center (camera moves).
void globeMoveCenterPoint(double latDiff, double lonDiff)
Orbits camera around the globe by the specified amount given as the difference in latitude/longitude ...
void rotateCameraToEast()
Rotate to view from the east.
const QgsVector3D origin() const
Returns the origin of the scene in map coordinates.
void rotateCameraToHome()
Rotate to diagonal view.
void rotateCameraToNorth()
Rotate to view from the north.
float distance() const
Returns distance of the camera from the point it is looking at.
void globeUpdatePitchAngle(float angleDiff)
Updates pitch angle by the specified amount given as the angular difference in degrees.
Q_DECL_DEPRECATED void zoomCameraAroundPivot(const QVector3D &oldCameraPosition, double zoomFactor, const QVector3D &pivotPoint)
Zooms camera by given zoom factor (>1 one means zoom in) while keeping the pivot point (given in worl...
void globeZoom(float factor)
Moves camera closer or further away from the globe.
void rotateCamera(float diffPitch, float diffYaw)
Rotates the camera on itself.
void rotateCameraToWest()
Rotate to view from the west.
void setCameraNavigationMode(Qgis::NavigationMode navigationMode)
Sets the navigation mode used by the camera controller.
void setVerticalAxisInversion(Qgis::VerticalAxisInversionFlags inversion)
Sets the vertical axis inversion behavior.
void cameraChanged()
Emitted when camera has been updated.
void moveCenterPoint(const QVector3D &posDiff)
Moves camera position by the given difference vector in world coordinates.
void cameraMovementSpeedChanged(double speed)
Emitted whenever the camera movement speed is changed by the controller.
void setCrossSectionSideView(const QgsCrossSection &crossSection)
Sets the cross section side view definition for the 3D map canvas.
QgsCameraController(Qgs3DMapScene *scene)
Constructs the camera controller with optional parent node that will take ownership.
void frameTriggered(float dt)
Called internally from 3D scene when a new frame is generated. Updates camera according to keyboard/m...
void resetView(float distance)
Move camera back to the initial position (looking down towards origin of world's coordinates).
void setLookingAtPoint(const QgsVector3D &point, float distance, float pitch, float yaw)
Sets the complete camera configuration: the point towards it is looking (in 3D world coordinates),...
QgsVector3D lookingAtPoint() const
Returns the point in the world coordinates towards which the camera is looking.
QgsVector3D lookingAtMapPoint() const
Returns the point in the map coordinates towards which the camera is looking.
void depthBufferReady()
Emitted after the depth buffer has been captured and is ready to sample.
void rotateCameraToSouth()
Rotate to view from the south.
QDomElement writeXml(QDomDocument &doc) const
Writes camera configuration to the given DOM element.
void setViewFromTop(float worldX, float worldY, float distance, float yaw=0)
Sets camera to look down towards given point in world coordinate, in given distance from plane with z...
bool keyboardEventFilter(QKeyEvent *event)
If the event is relevant, handles the event and returns true, otherwise false.
void resetGlobe(float distance, double lat=0, double lon=0)
Resets view of the globe to look at a particular location given as latitude and longitude (in degrees...
void readXml(const QDomElement &elem, QgsVector3D savedOrigin)
Reads camera configuration from the given DOM element.
void zoom(float factor)
Zoom the map by factor.
void globeUpdateHeadingAngle(float angleDiff)
Updates heading angle by the specified amount given as the angular difference in degrees.
void rotateAroundViewCenter(float deltaYaw)
Rotate clockwise the view by deltaYaw around the view center (camera moves).
void walkView(double tx, double ty, double tz)
Walks into the map by tx, ty, and tz.
void setCameraPose(const QgsCameraPose &camPose, bool force=false)
Sets camera pose.
void setOrigin(const QgsVector3D &origin)
Reacts to the shift of origin of the scene, updating camera pose and any other member variables so th...
double sampleDepthBuffer(int px, int py)
Returns the minimum depth value in the square [px - 3, px + 3] * [py - 3, py + 3] Returned depth is i...
void setCameraHeadingAngle(float angle)
Set camera heading to angle (used for rotating the view).
void setCameraMovementSpeed(double movementSpeed)
Sets the camera movement speed.
void rotateCameraAroundPivot(float newPitch, float newHeading, const QVector3D &pivotPoint)
Rotates the camera around the pivot point (in world coordinates) to the given new pitch and heading a...
void depthBufferCaptured(const QImage &depthImage)
Sets the depth buffer image used by the camera controller to calculate world position from a pixel's ...
void cameraRotationCenterChanged(QVector3D position)
Emitted when the camera rotation center changes.
void setCursorPosition(QPoint point)
Emitted when the mouse cursor position should be moved to the specified point on the map viewport.
void moveView(float tx, float ty)
Move the map by tx and ty.
Encapsulates camera pose in a 3D scene.
void setPitchAngle(float pitch)
Sets pitch angle in degrees.
void setCenterPoint(const QgsVector3D &point)
Sets center point (towards which point the camera is looking).
void setHeadingAngle(float heading)
Sets heading (yaw) angle in degrees.
void setDistanceFromCenterPoint(float distance)
Sets distance of the camera from the center point.
Handles coordinate transforms between two coordinate systems.
Encapsulates the definition of a cross section in 3D map coordinates.
double halfWidth() const
Returns the half-width of the cross section.
QgsPoint endPoint() const
Returns the end point of the cross section.
bool isValid() const
Returns cross section validity.
QgsPoint startPoint() const
Returns the start point of the cross section.
Custom exception class for Coordinate Reference System related exceptions.
static QgsNative * nativePlatformInterface()
Returns the global native interface, which offers abstraction to the host OS's underlying public inte...
Definition qgsgui.cpp:100
Represents a 2D point.
Definition qgspointxy.h:62
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
double x
Definition qgspoint.h:56
double y
Definition qgspoint.h:57
A representation of a ray in 3D.
Definition qgsray3d.h:31
QVector3D origin() const
Returns the origin of the ray.
Definition qgsray3d.h:43
QVector3D direction() const
Returns the direction of the ray see setDirection().
Definition qgsray3d.h:49
Responsible for defining parameters of the ray casting operations in 3D map canvases.
void setSingleResult(bool enable)
Sets whether to fetch only the closest hit for each layer or entity type.
void setMaximumDistance(float distance)
Sets the maximum distance from ray origin to look for hits when casting a ray.
A 3D vector (similar to QVector3D) with the difference that it uses double precision instead of singl...
Definition qgsvector3d.h:33
double y() const
Returns Y coordinate.
Definition qgsvector3d.h:60
double z() const
Returns Z coordinate.
Definition qgsvector3d.h:62
QVector3D toVector3D() const
Converts the current object to QVector3D.
static double dotProduct(const QgsVector3D &v1, const QgsVector3D &v2)
Returns the dot product of two vectors.
double x() const
Returns X coordinate.
Definition qgsvector3d.h:58
void setX(double x)
Sets X coordinate.
Definition qgsvector3d.h:68
void set(double x, double y, double z)
Sets vector coordinates.
Definition qgsvector3d.h:83
void setY(double y)
Sets Y coordinate.
Definition qgsvector3d.h:74
double length() const
Returns the length of the vector.
Represent a 2-dimensional vector.
Definition qgsvector.h:34
double y() const
Returns the vector's y-component.
Definition qgsvector.h:155
QgsVector normalized() const
Returns the vector's normalized (or "unit") vector (ie same angle but length of 1....
Definition qgsvector.cpp:33
QgsVector perpVector() const
Returns the perpendicular vector to this vector (rotated 90 degrees counter-clockwise).
Definition qgsvector.h:163
double x() const
Returns the vector's x-component.
Definition qgsvector.h:146
On-screen 3D engine: it creates an OpenGL window (QWindow) and displays rendered 3D scenes there.
QWindow * window()
Returns the internal 3D window where all the rendered output is displayed.
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored).
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71