LCOV - code coverage report
Current view: top level - source/graphics - CameraController.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 421 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 26 0.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "CameraController.h"
      21             : 
      22             : #include "graphics/Camera.h"
      23             : #include "graphics/Terrain.h"
      24             : #include "lib/external_libraries/libsdl.h"
      25             : #include "maths/MathUtil.h"
      26             : #include "maths/Matrix3D.h"
      27             : #include "maths/Quaternion.h"
      28             : #include "maths/Vector3D.h"
      29             : #include "ps/CLogger.h"
      30             : #include "ps/CStr.h"
      31             : #include "ps/ConfigDB.h"
      32             : #include "ps/Game.h"
      33             : #include "ps/Globals.h"
      34             : #include "ps/Hotkey.h"
      35             : #include "ps/VideoMode.h"
      36             : #include "ps/World.h"
      37             : #include "renderer/Renderer.h"
      38             : #include "renderer/SceneRenderer.h"
      39             : #include "renderer/WaterManager.h"
      40             : #include "simulation2/Simulation2.h"
      41             : #include "simulation2/components/ICmpPosition.h"
      42             : #include "simulation2/components/ICmpRangeManager.h"
      43             : #include "simulation2/system/Component.h"
      44             : 
      45             : #include <SDL_events.h>
      46             : #include <algorithm>
      47             : #include <numbers>
      48             : #include <functional>
      49             : #include <string>
      50             : 
      51             : // Maximum distance outside the edge of the map that the camera's
      52             : // focus point can be moved
      53             : static const float CAMERA_EDGE_MARGIN = 2.0f * TERRAIN_TILE_SIZE;
      54             : 
      55           0 : CCameraController::CCameraController(CCamera& camera)
      56             :     : ICameraController(camera),
      57           0 :       m_ConstrainCamera(true),
      58           0 :       m_FollowEntity(INVALID_ENTITY),
      59           0 :       m_FollowFirstPerson(false),
      60           0 :       m_BirdsEyeView(false),
      61             : 
      62             :       // Dummy values (these will be filled in by the config file)
      63           0 :       m_ViewScrollSpeed(0),
      64           0 :       m_ViewScrollSpeedModifier(1),
      65           0 :       m_ViewScrollMouseDetectDistance(3),
      66           0 :       m_ViewRotateXSpeed(0),
      67           0 :       m_ViewRotateXMin(0),
      68           0 :       m_ViewRotateXMax(0),
      69           0 :       m_ViewRotateXDefault(0),
      70           0 :       m_ViewRotateYSpeed(0),
      71           0 :       m_ViewRotateYSpeedWheel(0),
      72           0 :       m_ViewRotateYDefault(0),
      73           0 :       m_ViewRotateSpeedModifier(1),
      74           0 :       m_ViewDragSpeed(0),
      75           0 :       m_ViewDragInverted(false),
      76           0 :       m_ViewZoomSpeed(0),
      77           0 :       m_ViewZoomSpeedWheel(0),
      78           0 :       m_ViewZoomMin(0),
      79           0 :       m_ViewZoomMax(0),
      80           0 :       m_ViewZoomDefault(0),
      81           0 :       m_ViewZoomSpeedModifier(1),
      82           0 :       m_ViewFOV(DEGTORAD(45.f)),
      83           0 :       m_ViewNear(2.f),
      84           0 :       m_ViewFar(4096.f),
      85           0 :       m_HeightSmoothness(0.5f),
      86           0 :       m_HeightMin(16.f),
      87             : 
      88           0 :       m_PosX(0, 0, 0.01f),
      89           0 :       m_PosY(0, 0, 0.01f),
      90           0 :       m_PosZ(0, 0, 0.01f),
      91           0 :       m_Zoom(0, 0, 0.1f),
      92           0 :       m_RotateX(0, 0, 0.001f),
      93           0 :       m_RotateY(0, 0, 0.001f)
      94             : {
      95           0 :     m_ViewDragInvertedConfigHook =
      96           0 :         std::make_unique<CConfigDBHook>(g_ConfigDB.RegisterHookAndCall("view.drag.inverted", [this]() {
      97           0 :             m_ViewDragInverted = g_ConfigDB.Get("view.drag.inverted", m_ViewDragInverted);
      98           0 :         }));
      99           0 :     m_ViewDragSpeedConfigHook =
     100           0 :         std::make_unique<CConfigDBHook>(g_ConfigDB.RegisterHookAndCall("view.drag.speed", [this]() {
     101           0 :             m_ViewDragSpeed = g_ConfigDB.Get("view.drag.speed", m_ViewDragSpeed);
     102           0 :         }));
     103             : 
     104           0 :     SViewPort vp;
     105           0 :     vp.m_X = 0;
     106           0 :     vp.m_Y = 0;
     107           0 :     vp.m_Width = g_VideoMode.GetWindowWidth();
     108           0 :     vp.m_Height = g_VideoMode.GetWindowHeight();
     109           0 :     m_Camera.SetViewPort(vp);
     110             : 
     111           0 :     SetCameraProjection();
     112           0 :     SetupCameraMatrixSmooth(&m_Camera.m_Orientation);
     113           0 :     m_Camera.UpdateFrustum();
     114           0 : }
     115             : 
     116           0 : CCameraController::~CCameraController() = default;
     117             : 
     118           0 : void CCameraController::LoadConfig()
     119             : {
     120           0 :     m_ViewScrollSpeed = g_ConfigDB.Get("view.scroll.speed", m_ViewScrollSpeed);
     121           0 :     m_ViewScrollSpeedModifier = g_ConfigDB.Get("view.scroll.speed.modifier", m_ViewScrollSpeedModifier);
     122           0 :     m_ViewScrollMouseDetectDistance = g_ConfigDB.Get("view.scroll.mouse.detectdistance",
     123             :         m_ViewScrollMouseDetectDistance);
     124           0 :     m_ViewRotateXSpeed = g_ConfigDB.Get("view.rotate.x.speed", m_ViewRotateXSpeed);
     125           0 :     m_ViewRotateXMin = g_ConfigDB.Get("view.rotate.x.min", m_ViewRotateXMin);
     126           0 :     m_ViewRotateXMax = g_ConfigDB.Get("view.rotate.x.max", m_ViewRotateXMax);
     127           0 :     m_ViewRotateXDefault = g_ConfigDB.Get("view.rotate.x.default", m_ViewRotateXDefault);
     128           0 :     m_ViewRotateYSpeed = g_ConfigDB.Get("view.rotate.y.speed", m_ViewRotateYSpeed);
     129           0 :     m_ViewRotateYSpeedWheel = g_ConfigDB.Get("view.rotate.y.speed.wheel", m_ViewRotateYSpeedWheel);
     130           0 :     m_ViewRotateYDefault = g_ConfigDB.Get("view.rotate.y.default", m_ViewRotateYDefault);
     131           0 :     m_ViewRotateSpeedModifier = g_ConfigDB.Get("view.rotate.speed.modifier", m_ViewRotateSpeedModifier);
     132           0 :     m_ViewDragSpeed = g_ConfigDB.Get("view.drag.speed", m_ViewDragSpeed);
     133           0 :     m_ViewDragInverted = g_ConfigDB.Get("view.drag.inverted", m_ViewDragInverted);
     134           0 :     m_ViewZoomSpeed = g_ConfigDB.Get("view.zoom.speed", m_ViewZoomSpeed);
     135           0 :     m_ViewZoomSpeedWheel = g_ConfigDB.Get("view.zoom.speed.wheel", m_ViewZoomSpeedWheel);
     136           0 :     m_ViewZoomMin = g_ConfigDB.Get("view.zoom.min", m_ViewZoomMin);
     137           0 :     m_ViewZoomMax = g_ConfigDB.Get("view.zoom.max", m_ViewZoomMax);
     138           0 :     m_ViewZoomDefault = g_ConfigDB.Get("view.zoom.default", m_ViewZoomDefault);
     139           0 :     m_ViewZoomSpeedModifier = g_ConfigDB.Get("view.zoom.speed.modifier", m_ViewZoomSpeedModifier);
     140             : 
     141           0 :     m_HeightSmoothness = g_ConfigDB.Get("view.height.smoothness", m_HeightSmoothness);
     142           0 :     m_HeightMin = g_ConfigDB.Get("view.height.min", m_HeightMin);
     143             : 
     144             : #define SETUP_SMOOTHNESS(CFG_PREFIX, SMOOTHED_VALUE) \
     145             :     SMOOTHED_VALUE.SetSmoothness( \
     146             :         g_ConfigDB.Get(CFG_PREFIX ".smoothness", SMOOTHED_VALUE.GetSmoothness()));
     147             : 
     148           0 :     SETUP_SMOOTHNESS("view.pos", m_PosX);
     149           0 :     SETUP_SMOOTHNESS("view.pos", m_PosY);
     150           0 :     SETUP_SMOOTHNESS("view.pos", m_PosZ);
     151           0 :     SETUP_SMOOTHNESS("view.zoom", m_Zoom);
     152           0 :     SETUP_SMOOTHNESS("view.rotate.x", m_RotateX);
     153           0 :     SETUP_SMOOTHNESS("view.rotate.y", m_RotateY);
     154             : #undef SETUP_SMOOTHNESS
     155             : 
     156           0 :     m_ViewNear = g_ConfigDB.Get("view.near", m_ViewNear);
     157           0 :     m_ViewFar = g_ConfigDB.Get("view.far", m_ViewFar);
     158           0 :     m_ViewFOV = g_ConfigDB.Get("view.fov", m_ViewFOV);
     159             : 
     160             :     // Convert to radians
     161           0 :     m_RotateX.SetValue(DEGTORAD(m_ViewRotateXDefault));
     162           0 :     m_RotateY.SetValue(DEGTORAD(m_ViewRotateYDefault));
     163           0 :     m_ViewFOV = DEGTORAD(m_ViewFOV);
     164           0 : }
     165             : 
     166           0 : void CCameraController::SetViewport(const SViewPort& vp)
     167             : {
     168           0 :     m_Camera.SetViewPort(vp);
     169           0 :     SetCameraProjection();
     170           0 : }
     171             : 
     172           0 : void CCameraController::Update(const float deltaRealTime)
     173             : {
     174             :     // Calculate mouse movement
     175           0 :     static int mouse_last_x = 0;
     176           0 :     static int mouse_last_y = 0;
     177           0 :     int mouse_dx = g_mouse_x - mouse_last_x;
     178           0 :     int mouse_dy = g_mouse_y - mouse_last_y;
     179           0 :     mouse_last_x = g_mouse_x;
     180           0 :     mouse_last_y = g_mouse_y;
     181             : 
     182           0 :     if (HotkeyIsPressed("camera.rotate.cw"))
     183           0 :         m_RotateY.AddSmoothly(m_ViewRotateYSpeed * deltaRealTime);
     184           0 :     if (HotkeyIsPressed("camera.rotate.ccw"))
     185           0 :         m_RotateY.AddSmoothly(-m_ViewRotateYSpeed * deltaRealTime);
     186           0 :     if (HotkeyIsPressed("camera.rotate.up") && !m_BirdsEyeView)
     187           0 :         m_RotateX.AddSmoothly(-m_ViewRotateXSpeed * deltaRealTime);
     188           0 :     if (HotkeyIsPressed("camera.rotate.down") && !m_BirdsEyeView)
     189           0 :         m_RotateX.AddSmoothly(m_ViewRotateXSpeed * deltaRealTime);
     190             : 
     191           0 :     float moveRightward = 0.f;
     192           0 :     float moveForward = 0.f;
     193             : 
     194           0 :     if (HotkeyIsPressed("camera.pan"))
     195             :     {
     196           0 :         if (m_ViewDragInverted) {
     197           0 :             moveRightward += m_ViewDragSpeed * -mouse_dx;
     198           0 :             moveForward += m_ViewDragSpeed * mouse_dy;
     199             :         }
     200             :         else {
     201           0 :             moveRightward += m_ViewDragSpeed * mouse_dx;
     202           0 :             moveForward += m_ViewDragSpeed * -mouse_dy;
     203             :         }
     204             :     }
     205             : 
     206           0 :     if (g_mouse_active && m_ViewScrollMouseDetectDistance > 0)
     207             :     {
     208           0 :         if (g_mouse_x >= g_VideoMode.GetWindowWidth() - m_ViewScrollMouseDetectDistance && g_mouse_x < g_VideoMode.GetWindowWidth())
     209           0 :             moveRightward += m_ViewScrollSpeed * deltaRealTime;
     210           0 :         else if (g_mouse_x < m_ViewScrollMouseDetectDistance && g_mouse_x >= 0)
     211           0 :             moveRightward -= m_ViewScrollSpeed * deltaRealTime;
     212             : 
     213           0 :         if (g_mouse_y >= g_VideoMode.GetWindowHeight() - m_ViewScrollMouseDetectDistance && g_mouse_y < g_VideoMode.GetWindowHeight())
     214           0 :             moveForward -= m_ViewScrollSpeed * deltaRealTime;
     215           0 :         else if (g_mouse_y < m_ViewScrollMouseDetectDistance && g_mouse_y >= 0)
     216           0 :             moveForward += m_ViewScrollSpeed * deltaRealTime;
     217             :     }
     218             : 
     219           0 :     if (HotkeyIsPressed("camera.right"))
     220           0 :         moveRightward += m_ViewScrollSpeed * deltaRealTime;
     221           0 :     if (HotkeyIsPressed("camera.left"))
     222           0 :         moveRightward -= m_ViewScrollSpeed * deltaRealTime;
     223           0 :     if (HotkeyIsPressed("camera.up"))
     224           0 :         moveForward += m_ViewScrollSpeed * deltaRealTime;
     225           0 :     if (HotkeyIsPressed("camera.down"))
     226           0 :         moveForward -= m_ViewScrollSpeed * deltaRealTime;
     227             : 
     228           0 :     if (moveRightward || moveForward)
     229             :     {
     230             :         // Break out of following mode when the user starts scrolling
     231           0 :         m_FollowEntity = INVALID_ENTITY;
     232             : 
     233           0 :         float s = sin(m_RotateY.GetSmoothedValue());
     234           0 :         float c = cos(m_RotateY.GetSmoothedValue());
     235           0 :         m_PosX.AddSmoothly(c * moveRightward);
     236           0 :         m_PosZ.AddSmoothly(-s * moveRightward);
     237           0 :         m_PosX.AddSmoothly(s * moveForward);
     238           0 :         m_PosZ.AddSmoothly(c * moveForward);
     239             :     }
     240             : 
     241           0 :     if (m_FollowEntity)
     242             :     {
     243           0 :         CmpPtr<ICmpPosition> cmpPosition(*(g_Game->GetSimulation2()), m_FollowEntity);
     244           0 :         CmpPtr<ICmpRangeManager> cmpRangeManager(*(g_Game->GetSimulation2()), SYSTEM_ENTITY);
     245           0 :         if (cmpPosition && cmpPosition->IsInWorld() &&
     246           0 :             cmpRangeManager && cmpRangeManager->GetLosVisibility(m_FollowEntity, g_Game->GetViewedPlayerID()) == LosVisibility::VISIBLE)
     247             :         {
     248             :             // Get the most recent interpolated position
     249           0 :             float frameOffset = g_Game->GetSimulation2()->GetLastFrameOffset();
     250           0 :             CMatrix3D transform = cmpPosition->GetInterpolatedTransform(frameOffset);
     251           0 :             CVector3D pos = transform.GetTranslation();
     252             : 
     253           0 :             if (m_FollowFirstPerson)
     254             :             {
     255           0 :                 float x, z, angle;
     256           0 :                 cmpPosition->GetInterpolatedPosition2D(frameOffset, x, z, angle);
     257           0 :                 float height = 4.f;
     258           0 :                 m_Camera.m_Orientation.SetIdentity();
     259           0 :                 m_Camera.m_Orientation.RotateX(std::numbers::pi_v<float> / 24.f);
     260           0 :                 m_Camera.m_Orientation.RotateY(angle);
     261           0 :                 m_Camera.m_Orientation.Translate(pos.X, pos.Y + height, pos.Z);
     262             : 
     263           0 :                 m_Camera.UpdateFrustum();
     264           0 :                 return;
     265             :             }
     266             :             else
     267             :             {
     268             :                 // Move the camera to match the unit
     269           0 :                 CCamera targetCam = m_Camera;
     270           0 :                 SetupCameraMatrixSmoothRot(&targetCam.m_Orientation);
     271             : 
     272           0 :                 CVector3D pivot = GetSmoothPivot(targetCam);
     273           0 :                 CVector3D delta = pos - pivot;
     274           0 :                 m_PosX.AddSmoothly(delta.X);
     275           0 :                 m_PosY.AddSmoothly(delta.Y);
     276           0 :                 m_PosZ.AddSmoothly(delta.Z);
     277           0 :             }
     278             :         }
     279             :         else
     280             :         {
     281             :             // The unit disappeared (died or garrisoned etc), so stop following it
     282           0 :             m_FollowEntity = INVALID_ENTITY;
     283             :         }
     284             :     }
     285             : 
     286           0 :     if (HotkeyIsPressed("camera.zoom.in"))
     287           0 :         m_Zoom.AddSmoothly(-m_ViewZoomSpeed * deltaRealTime);
     288           0 :     if (HotkeyIsPressed("camera.zoom.out"))
     289           0 :         m_Zoom.AddSmoothly(m_ViewZoomSpeed * deltaRealTime);
     290             : 
     291           0 :     if (m_ConstrainCamera)
     292           0 :         m_Zoom.ClampSmoothly(m_ViewZoomMin, m_ViewZoomMax);
     293             : 
     294           0 :     float zoomDelta = -m_Zoom.Update(deltaRealTime);
     295           0 :     if (zoomDelta)
     296             :     {
     297           0 :         CVector3D forwards = m_Camera.GetOrientation().GetIn();
     298           0 :         m_PosX.AddSmoothly(forwards.X * zoomDelta);
     299           0 :         m_PosY.AddSmoothly(forwards.Y * zoomDelta);
     300           0 :         m_PosZ.AddSmoothly(forwards.Z * zoomDelta);
     301             :     }
     302             : 
     303           0 :     if (m_ConstrainCamera)
     304             :     {
     305           0 :         if (m_BirdsEyeView)
     306           0 :             m_RotateX.ClampSmoothly(std::numbers::pi_v<float> / 2.f, std::numbers::pi_v<float> / 2.f);
     307             :         else
     308           0 :             m_RotateX.ClampSmoothly(DEGTORAD(m_ViewRotateXMin), DEGTORAD(m_ViewRotateXMax));
     309             :     }
     310             : 
     311           0 :     FocusHeight(true);
     312             : 
     313             :     // Ensure the ViewCamera focus is inside the map with the chosen margins
     314             :     // if not so - apply margins to the camera
     315           0 :     if (m_ConstrainCamera)
     316             :     {
     317           0 :         CCamera targetCam = m_Camera;
     318           0 :         SetupCameraMatrixSmoothRot(&targetCam.m_Orientation);
     319             : 
     320           0 :         const CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
     321             : 
     322           0 :         CVector3D pivot = GetSmoothPivot(targetCam);
     323           0 :         CVector3D delta = targetCam.GetOrientation().GetTranslation() - pivot;
     324             : 
     325           0 :         CVector3D desiredPivot = pivot;
     326             : 
     327           0 :         CmpPtr<ICmpRangeManager> cmpRangeManager(*(g_Game->GetSimulation2()), SYSTEM_ENTITY);
     328           0 :         if (cmpRangeManager && cmpRangeManager->GetLosCircular())
     329             :         {
     330             :             // Clamp to a circular region around the center of the map
     331           0 :             const float r = terrain.GetMaxX() / 2.f;
     332           0 :             CVector3D center(r, desiredPivot.Y, r);
     333           0 :             float dist = (desiredPivot - center).Length();
     334           0 :             if (dist > r - CAMERA_EDGE_MARGIN)
     335           0 :                 desiredPivot = center + (desiredPivot - center).Normalized() * (r - CAMERA_EDGE_MARGIN);
     336             :         }
     337             :         else
     338             :         {
     339             :             // Clamp to the square edges of the map
     340           0 :             desiredPivot.X = Clamp(desiredPivot.X, terrain.GetMinX() + CAMERA_EDGE_MARGIN,
     341           0 :                 terrain.GetMaxX() - CAMERA_EDGE_MARGIN);
     342           0 :             desiredPivot.Z = Clamp(desiredPivot.Z, terrain.GetMinZ() + CAMERA_EDGE_MARGIN,
     343           0 :                 terrain.GetMaxZ() - CAMERA_EDGE_MARGIN);
     344             :         }
     345             : 
     346             :         // Update the position so that pivot is within the margin
     347           0 :         m_PosX.SetValueSmoothly(desiredPivot.X + delta.X);
     348           0 :         m_PosZ.SetValueSmoothly(desiredPivot.Z + delta.Z);
     349           0 :     }
     350             : 
     351           0 :     m_PosX.Update(deltaRealTime);
     352           0 :     m_PosY.Update(deltaRealTime);
     353           0 :     m_PosZ.Update(deltaRealTime);
     354             : 
     355             :     // Handle rotation around the Y (vertical) axis
     356           0 :     {
     357           0 :         CCamera targetCam = m_Camera;
     358           0 :         SetupCameraMatrixSmooth(&targetCam.m_Orientation);
     359             : 
     360           0 :         float rotateYDelta = m_RotateY.Update(deltaRealTime);
     361           0 :         if (rotateYDelta)
     362             :         {
     363             :             // We've updated RotateY, and need to adjust Pos so that it's still
     364             :             // facing towards the original focus point (the terrain in the center
     365             :             // of the screen).
     366             : 
     367           0 :             CVector3D upwards(0.0f, 1.0f, 0.0f);
     368             : 
     369           0 :             CVector3D pivot = GetSmoothPivot(targetCam);
     370           0 :             CVector3D delta = targetCam.GetOrientation().GetTranslation() - pivot;
     371             : 
     372           0 :             CQuaternion q;
     373           0 :             q.FromAxisAngle(upwards, rotateYDelta);
     374           0 :             CVector3D d = q.Rotate(delta) - delta;
     375             : 
     376           0 :             m_PosX.Add(d.X);
     377           0 :             m_PosY.Add(d.Y);
     378           0 :             m_PosZ.Add(d.Z);
     379             :         }
     380           0 :     }
     381             : 
     382             :     // Handle rotation around the X (sideways, relative to camera) axis
     383           0 :     {
     384           0 :         CCamera targetCam = m_Camera;
     385           0 :         SetupCameraMatrixSmooth(&targetCam.m_Orientation);
     386             : 
     387           0 :         float rotateXDelta = m_RotateX.Update(deltaRealTime);
     388           0 :         if (rotateXDelta)
     389             :         {
     390           0 :             CVector3D rightwards = targetCam.GetOrientation().GetLeft() * -1.0f;
     391             : 
     392           0 :             CVector3D pivot = GetSmoothPivot(targetCam);
     393           0 :             CVector3D delta = targetCam.GetOrientation().GetTranslation() - pivot;
     394             : 
     395           0 :             CQuaternion q;
     396           0 :             q.FromAxisAngle(rightwards, rotateXDelta);
     397           0 :             CVector3D d = q.Rotate(delta) - delta;
     398             : 
     399           0 :             m_PosX.Add(d.X);
     400           0 :             m_PosY.Add(d.Y);
     401           0 :             m_PosZ.Add(d.Z);
     402             :         }
     403           0 :     }
     404             : 
     405             :     /* This is disabled since it doesn't seem necessary:
     406             : 
     407             :     // Ensure the camera's near point is never inside the terrain
     408             :     if (m_ConstrainCamera)
     409             :     {
     410             :     CMatrix3D target;
     411             :     target.SetIdentity();
     412             :     target.RotateX(m_RotateX.GetValue());
     413             :     target.RotateY(m_RotateY.GetValue());
     414             :     target.Translate(m_PosX.GetValue(), m_PosY.GetValue(), m_PosZ.GetValue());
     415             : 
     416             :     CVector3D nearPoint = target.GetTranslation() + target.GetIn() * defaultNear;
     417             :     float ground = g_Game->GetWorld()->GetTerrain()->GetExactGroundLevel(nearPoint.X, nearPoint.Z);
     418             :     float limit = ground + 16.f;
     419             :     if (nearPoint.Y < limit)
     420             :     m_PosY.AddSmoothly(limit - nearPoint.Y);
     421             :     }
     422             :     */
     423             : 
     424           0 :     m_RotateY.Wrap(-std::numbers::pi_v<float>, std::numbers::pi_v<float>);
     425             : 
     426             :     // Update the camera matrix
     427           0 :     SetCameraProjection();
     428           0 :     SetupCameraMatrixSmooth(&m_Camera.m_Orientation);
     429           0 :     m_Camera.UpdateFrustum();
     430             : }
     431             : 
     432           0 : CVector3D CCameraController::GetSmoothPivot(CCamera& camera) const
     433             : {
     434           0 :     return camera.GetOrientation().GetTranslation() + camera.GetOrientation().GetIn() * m_Zoom.GetSmoothedValue();
     435             : }
     436             : 
     437           0 : CVector3D CCameraController::GetCameraPivot() const
     438             : {
     439           0 :     return GetSmoothPivot(m_Camera);
     440             : }
     441             : 
     442           0 : CVector3D CCameraController::GetCameraPosition() const
     443             : {
     444           0 :     return CVector3D(m_PosX.GetValue(), m_PosY.GetValue(), m_PosZ.GetValue());
     445             : }
     446             : 
     447           0 : CVector3D CCameraController::GetCameraRotation() const
     448             : {
     449             :     // The angle of rotation around the Z axis is not used.
     450           0 :     return CVector3D(m_RotateX.GetValue(), m_RotateY.GetValue(), 0.0f);
     451             : }
     452             : 
     453           0 : float CCameraController::GetCameraZoom() const
     454             : {
     455           0 :     return m_Zoom.GetValue();
     456             : }
     457             : 
     458           0 : void CCameraController::SetCamera(const CVector3D& pos, float rotX, float rotY, float zoom)
     459             : {
     460           0 :     m_PosX.SetValue(pos.X);
     461           0 :     m_PosY.SetValue(pos.Y);
     462           0 :     m_PosZ.SetValue(pos.Z);
     463           0 :     m_RotateX.SetValue(rotX);
     464           0 :     m_RotateY.SetValue(rotY);
     465           0 :     m_Zoom.SetValue(zoom);
     466             : 
     467           0 :     FocusHeight(false);
     468             : 
     469           0 :     SetupCameraMatrixNonSmooth(&m_Camera.m_Orientation);
     470           0 :     m_Camera.UpdateFrustum();
     471             : 
     472             :     // Break out of following mode so the camera really moves to the target
     473           0 :     m_FollowEntity = INVALID_ENTITY;
     474             : 
     475             :     // Leave bird's eye view
     476           0 :     m_BirdsEyeView = false;
     477           0 : }
     478             : 
     479           0 : void CCameraController::MoveCameraTarget(const CVector3D& target)
     480             : {
     481             :     // Maintain the same orientation and level of zoom, if we can
     482             :     // (do this by working out the point the camera is looking at, saving
     483             :     //  the difference between that position and the camera point, and restoring
     484             :     //  that difference to our new target)
     485             : 
     486           0 :     CCamera targetCam = m_Camera;
     487           0 :     SetupCameraMatrixNonSmooth(&targetCam.m_Orientation);
     488             : 
     489           0 :     CVector3D pivot = GetSmoothPivot(targetCam);
     490           0 :     CVector3D delta = target - pivot;
     491             : 
     492           0 :     m_PosX.SetValueSmoothly(delta.X + m_PosX.GetValue());
     493           0 :     m_PosZ.SetValueSmoothly(delta.Z + m_PosZ.GetValue());
     494             : 
     495           0 :     FocusHeight(false);
     496             : 
     497             :     // Break out of following mode so the camera really moves to the target
     498           0 :     m_FollowEntity = INVALID_ENTITY;
     499           0 : }
     500             : 
     501           0 : void CCameraController::ResetCameraTarget(const CVector3D& target)
     502             : {
     503           0 :     CMatrix3D orientation;
     504           0 :     orientation.SetIdentity();
     505           0 :     orientation.RotateX(DEGTORAD(m_ViewRotateXDefault));
     506           0 :     orientation.RotateY(DEGTORAD(m_ViewRotateYDefault));
     507             : 
     508           0 :     CVector3D delta = orientation.GetIn() * m_ViewZoomDefault;
     509           0 :     m_PosX.SetValue(target.X - delta.X);
     510           0 :     m_PosY.SetValue(target.Y - delta.Y);
     511           0 :     m_PosZ.SetValue(target.Z - delta.Z);
     512           0 :     m_RotateX.SetValue(DEGTORAD(m_ViewRotateXDefault));
     513           0 :     m_RotateY.SetValue(DEGTORAD(m_ViewRotateYDefault));
     514           0 :     m_Zoom.SetValue(m_ViewZoomDefault);
     515             : 
     516           0 :     FocusHeight(false);
     517             : 
     518           0 :     SetupCameraMatrixSmooth(&m_Camera.m_Orientation);
     519           0 :     m_Camera.UpdateFrustum();
     520             : 
     521             :     // Break out of following mode so the camera really moves to the target
     522           0 :     m_FollowEntity = INVALID_ENTITY;
     523             : 
     524             :     // Leave bird's eye view
     525           0 :     m_BirdsEyeView = false;
     526           0 : }
     527             : 
     528           0 : void CCameraController::FollowEntity(entity_id_t entity, bool firstPerson)
     529             : {
     530           0 :     m_FollowEntity = entity;
     531           0 :     m_FollowFirstPerson = firstPerson;
     532           0 : }
     533             : 
     534           0 : entity_id_t CCameraController::GetFollowedEntity()
     535             : {
     536           0 :     return m_FollowEntity;
     537             : }
     538             : 
     539           0 : void CCameraController::SetCameraProjection()
     540             : {
     541           0 :     m_Camera.SetPerspectiveProjection(m_ViewNear, m_ViewFar, m_ViewFOV);
     542           0 : }
     543             : 
     544           0 : void CCameraController::ResetCameraAngleZoom()
     545             : {
     546           0 :     CCamera targetCam = m_Camera;
     547           0 :     SetupCameraMatrixNonSmooth(&targetCam.m_Orientation);
     548             : 
     549             :     // Compute the zoom adjustment to get us back to the default
     550           0 :     CVector3D forwards = targetCam.GetOrientation().GetIn();
     551             : 
     552           0 :     CVector3D pivot = GetSmoothPivot(targetCam);
     553           0 :     CVector3D delta = pivot - targetCam.GetOrientation().GetTranslation();
     554           0 :     float dist = delta.Dot(forwards);
     555           0 :     m_Zoom.AddSmoothly(m_ViewZoomDefault - dist);
     556             : 
     557             :     // Reset orientations to default
     558           0 :     m_RotateX.SetValueSmoothly(DEGTORAD(m_ViewRotateXDefault));
     559           0 :     m_RotateY.SetValueSmoothly(DEGTORAD(m_ViewRotateYDefault));
     560             : 
     561             :     // Leave bird's eye view
     562           0 :     m_BirdsEyeView = false;
     563           0 : }
     564             : 
     565           0 : void CCameraController::ToggleBirdsEyeView()
     566             : {
     567           0 :     m_BirdsEyeView = !m_BirdsEyeView;
     568           0 :     float angle = m_BirdsEyeView ? std::numbers::pi_v<float> / 2.f : DEGTORAD(m_ViewRotateXDefault);
     569           0 :     m_RotateX.SetValueSmoothly(angle);
     570           0 : }
     571             : 
     572           0 : void CCameraController::SetupCameraMatrixSmooth(CMatrix3D* orientation)
     573             : {
     574           0 :     orientation->SetIdentity();
     575           0 :     orientation->RotateX(m_RotateX.GetSmoothedValue());
     576           0 :     orientation->RotateY(m_RotateY.GetSmoothedValue());
     577           0 :     orientation->Translate(m_PosX.GetSmoothedValue(), m_PosY.GetSmoothedValue(), m_PosZ.GetSmoothedValue());
     578           0 : }
     579             : 
     580           0 : void CCameraController::SetupCameraMatrixSmoothRot(CMatrix3D* orientation)
     581             : {
     582           0 :     orientation->SetIdentity();
     583           0 :     orientation->RotateX(m_RotateX.GetSmoothedValue());
     584           0 :     orientation->RotateY(m_RotateY.GetSmoothedValue());
     585           0 :     orientation->Translate(m_PosX.GetValue(), m_PosY.GetValue(), m_PosZ.GetValue());
     586           0 : }
     587             : 
     588           0 : void CCameraController::SetupCameraMatrixNonSmooth(CMatrix3D* orientation)
     589             : {
     590           0 :     orientation->SetIdentity();
     591           0 :     orientation->RotateX(m_RotateX.GetValue());
     592           0 :     orientation->RotateY(m_RotateY.GetValue());
     593           0 :     orientation->Translate(m_PosX.GetValue(), m_PosY.GetValue(), m_PosZ.GetValue());
     594           0 : }
     595             : 
     596           0 : void CCameraController::FocusHeight(bool smooth)
     597             : {
     598             :     /*
     599             :     The camera pivot height is moved towards ground level.
     600             :     To prevent excessive zoom when looking over a cliff,
     601             :     the target ground level is the maximum of the ground level at the camera's near and pivot points.
     602             :     The ground levels are filtered to achieve smooth camera movement.
     603             :     The filter radius is proportional to the zoom level.
     604             :     The camera height is clamped to prevent map penetration.
     605             :     */
     606             : 
     607           0 :     if (!m_ConstrainCamera)
     608           0 :         return;
     609             : 
     610           0 :     CCamera targetCam = m_Camera;
     611           0 :     SetupCameraMatrixSmoothRot(&targetCam.m_Orientation);
     612             : 
     613           0 :     const CVector3D position = targetCam.GetOrientation().GetTranslation();
     614           0 :     const CVector3D forwards = targetCam.GetOrientation().GetIn();
     615             : 
     616             :     // horizontal view radius
     617           0 :     const float radius = sqrtf(forwards.X * forwards.X + forwards.Z * forwards.Z) * m_Zoom.GetSmoothedValue();
     618           0 :     const float near_radius = radius * m_HeightSmoothness;
     619           0 :     const float pivot_radius = radius * m_HeightSmoothness;
     620             : 
     621           0 :     const CVector3D nearPoint = position + forwards * m_ViewNear;
     622           0 :     const CVector3D pivotPoint = position + forwards * m_Zoom.GetSmoothedValue();
     623             : 
     624           0 :     const float ground = std::max(
     625           0 :         g_Game->GetWorld()->GetTerrain().GetExactGroundLevel(nearPoint.X, nearPoint.Z),
     626           0 :         g_Renderer.GetSceneRenderer().GetWaterManager().m_WaterHeight);
     627             : 
     628             :     // filter ground levels for smooth camera movement
     629           0 :     const float filtered_near_ground = g_Game->GetWorld()->GetTerrain().GetFilteredGroundLevel(nearPoint.X, nearPoint.Z, near_radius);
     630           0 :     const float filtered_pivot_ground = g_Game->GetWorld()->GetTerrain().GetFilteredGroundLevel(pivotPoint.X, pivotPoint.Z, pivot_radius);
     631             : 
     632             :     // filtered maximum visible ground level in view
     633           0 :     const float filtered_ground = std::max(
     634             :         std::max(filtered_near_ground, filtered_pivot_ground),
     635           0 :         g_Renderer.GetSceneRenderer().GetWaterManager().m_WaterHeight);
     636             : 
     637             :     // target camera height above pivot point
     638           0 :     const float pivot_height = -forwards.Y * (m_Zoom.GetSmoothedValue() - m_ViewNear);
     639             : 
     640             :     // minimum camera height above filtered ground level
     641           0 :     const float min_height = (m_HeightMin + ground - filtered_ground);
     642             : 
     643           0 :     const float target_height = std::max(pivot_height, min_height);
     644           0 :     const float height = (nearPoint.Y - filtered_ground);
     645           0 :     const float diff = target_height - height;
     646             : 
     647           0 :     if (fabsf(diff) < 0.0001f)
     648           0 :         return;
     649             : 
     650           0 :     if (smooth)
     651           0 :         m_PosY.AddSmoothly(diff);
     652             :     else
     653           0 :         m_PosY.Add(diff);
     654           0 : }
     655             : 
     656           0 : Input::Reaction CCameraController::HandleEvent(const SDL_Event& ev)
     657             : {
     658           0 :     switch (ev.type)
     659             :     {
     660           0 :     case SDL_HOTKEYPRESS:
     661           0 :     {
     662           0 :         std::string hotkey = static_cast<const char*>(ev.user.data1);
     663           0 :         if (hotkey == "camera.reset")
     664             :         {
     665           0 :             ResetCameraAngleZoom();
     666             :             return Input::Reaction::HANDLED;
     667             :         }
     668           0 :         else if (hotkey == "camera.togglebirdseyeview")
     669             :         {
     670           0 :             ToggleBirdsEyeView();
     671           0 :             return Input::Reaction::HANDLED;
     672             :         }
     673             :         return Input::Reaction::PASS;
     674           0 :     }
     675             : 
     676           0 :     case SDL_HOTKEYDOWN:
     677           0 :     {
     678           0 :         std::string hotkey = static_cast<const char*>(ev.user.data1);
     679             : 
     680             :         // Mouse wheel must be treated using events instead of polling,
     681             :         // because SDL auto-generates a sequence of mousedown/mouseup events
     682             :         // and we never get to see the "down" state inside Update().
     683           0 :         if (hotkey == "camera.zoom.wheel.in")
     684             :         {
     685           0 :             m_Zoom.AddSmoothly(-m_ViewZoomSpeedWheel);
     686           0 :             return Input::Reaction::HANDLED;
     687             :         }
     688           0 :         else if (hotkey == "camera.zoom.wheel.out")
     689             :         {
     690           0 :             m_Zoom.AddSmoothly(m_ViewZoomSpeedWheel);
     691           0 :             return Input::Reaction::HANDLED;
     692             :         }
     693           0 :         else if (hotkey == "camera.rotate.wheel.cw")
     694             :         {
     695           0 :             m_RotateY.AddSmoothly(m_ViewRotateYSpeedWheel);
     696           0 :             return Input::Reaction::HANDLED;
     697             :         }
     698           0 :         else if (hotkey == "camera.rotate.wheel.ccw")
     699             :         {
     700           0 :             m_RotateY.AddSmoothly(-m_ViewRotateYSpeedWheel);
     701           0 :             return Input::Reaction::HANDLED;
     702             :         }
     703           0 :         else if (hotkey == "camera.scroll.speed.increase")
     704             :         {
     705           0 :             m_ViewScrollSpeed *= m_ViewScrollSpeedModifier;
     706           0 :             LOGMESSAGERENDER("Scroll speed increased to {:.1f}", m_ViewScrollSpeed);
     707           0 :             return Input::Reaction::HANDLED;
     708             :         }
     709           0 :         else if (hotkey == "camera.scroll.speed.decrease")
     710             :         {
     711           0 :             m_ViewScrollSpeed /= m_ViewScrollSpeedModifier;
     712           0 :             LOGMESSAGERENDER("Scroll speed decreased to {:.1f}", m_ViewScrollSpeed);
     713           0 :             return Input::Reaction::HANDLED;
     714             :         }
     715           0 :         else if (hotkey == "camera.rotate.speed.increase")
     716             :         {
     717           0 :             m_ViewRotateXSpeed *= m_ViewRotateSpeedModifier;
     718           0 :             m_ViewRotateYSpeed *= m_ViewRotateSpeedModifier;
     719           0 :             LOGMESSAGERENDER("Rotate speed increased to X={:.3f}, Y={:.3f}", m_ViewRotateXSpeed,
     720             :                 m_ViewRotateYSpeed);
     721           0 :             return Input::Reaction::HANDLED;
     722             :         }
     723           0 :         else if (hotkey == "camera.rotate.speed.decrease")
     724             :         {
     725           0 :             m_ViewRotateXSpeed /= m_ViewRotateSpeedModifier;
     726           0 :             m_ViewRotateYSpeed /= m_ViewRotateSpeedModifier;
     727           0 :             LOGMESSAGERENDER("Rotate speed decreased to X={:.3f}, Y={:.3f}", m_ViewRotateXSpeed,
     728             :                 m_ViewRotateYSpeed);
     729           0 :             return Input::Reaction::HANDLED;
     730             :         }
     731           0 :         else if (hotkey == "camera.zoom.speed.increase")
     732             :         {
     733           0 :             m_ViewZoomSpeed *= m_ViewZoomSpeedModifier;
     734           0 :             LOGMESSAGERENDER("Zoom speed increased to {:.1f}", m_ViewZoomSpeed);
     735           0 :             return Input::Reaction::HANDLED;
     736             :         }
     737           0 :         else if (hotkey == "camera.zoom.speed.decrease")
     738             :         {
     739           0 :             m_ViewZoomSpeed /= m_ViewZoomSpeedModifier;
     740           0 :             LOGMESSAGERENDER("Zoom speed decreased to {:.1f}", m_ViewZoomSpeed);
     741           0 :             return Input::Reaction::HANDLED;
     742             :         }
     743             :         return Input::Reaction::PASS;
     744           0 :     }
     745             :     }
     746             : 
     747             :     return Input::Reaction::PASS;
     748             : }

Generated by: LCOV version 1.16