Line data Source code
1 : /* Copyright (C) 2025 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 "Camera.h"
21 :
22 : #include "graphics/HFTracer.h"
23 : #include "graphics/Terrain.h"
24 : #include "lib/code_generation.h"
25 : #include "lib/debug.h"
26 : #include "lib/posix/posix_types.h"
27 : #include "maths/MathUtil.h"
28 : #include "maths/Plane.h"
29 : #include "maths/Vector2D.h"
30 : #include "maths/Vector4D.h"
31 : #include "ps/Game.h"
32 : #include "ps/World.h"
33 : #include "renderer/Renderer.h"
34 : #include "renderer/SceneRenderer.h"
35 : #include "renderer/WaterManager.h"
36 :
37 : #include <cmath>
38 : #include <cstddef>
39 :
40 53 : CCamera::CCamera()
41 : {
42 : // Set viewport to something anything should handle, but should be initialised
43 : // to window size before use.
44 53 : m_ViewPort.m_X = 0;
45 53 : m_ViewPort.m_Y = 0;
46 53 : m_ViewPort.m_Width = 800;
47 53 : m_ViewPort.m_Height = 600;
48 53 : }
49 :
50 54 : CCamera::~CCamera() = default;
51 :
52 2 : void CCamera::SetProjection(const CMatrix3D& matrix)
53 : {
54 2 : m_ProjType = ProjectionType::CUSTOM;
55 2 : m_ProjMat = matrix;
56 2 : }
57 :
58 0 : void CCamera::SetProjectionFromCamera(const CCamera& camera)
59 : {
60 0 : m_ProjType = camera.m_ProjType;
61 0 : m_NearPlane = camera.m_NearPlane;
62 0 : m_FarPlane = camera.m_FarPlane;
63 0 : if (m_ProjType == ProjectionType::PERSPECTIVE)
64 : {
65 0 : m_FOV = camera.m_FOV;
66 : }
67 0 : else if (m_ProjType == ProjectionType::ORTHO)
68 : {
69 0 : m_OrthoScale = camera.m_OrthoScale;
70 : }
71 0 : m_ProjMat = camera.m_ProjMat;
72 0 : }
73 :
74 5 : void CCamera::SetOrthoProjection(float nearp, float farp, float scale)
75 : {
76 5 : m_ProjType = ProjectionType::ORTHO;
77 5 : m_NearPlane = nearp;
78 5 : m_FarPlane = farp;
79 5 : m_OrthoScale = scale;
80 :
81 5 : const float halfHeight = 0.5f * m_OrthoScale;
82 5 : const float halfWidth = halfHeight * GetAspectRatio();
83 5 : m_ProjMat.SetOrtho(-halfWidth, halfWidth, -halfHeight, halfHeight, m_NearPlane, m_FarPlane);
84 5 : }
85 :
86 7 : void CCamera::SetPerspectiveProjection(float nearp, float farp, float fov)
87 : {
88 7 : m_ProjType = ProjectionType::PERSPECTIVE;
89 7 : m_NearPlane = nearp;
90 7 : m_FarPlane = farp;
91 7 : m_FOV = fov;
92 :
93 7 : m_ProjMat.SetPerspective(m_FOV, GetAspectRatio(), m_NearPlane, m_FarPlane);
94 7 : }
95 :
96 : // Updates the frustum planes. Should be called
97 : // everytime the view or projection matrices are
98 : // altered.
99 4 : void CCamera::UpdateFrustum(const CBoundingBoxAligned& scissor)
100 : {
101 4 : CMatrix3D MatFinal;
102 4 : CMatrix3D MatView;
103 :
104 4 : m_Orientation.GetInverse(MatView);
105 :
106 4 : MatFinal = m_ProjMat * MatView;
107 :
108 4 : m_ViewFrustum.SetNumPlanes(6);
109 :
110 : // get the RIGHT plane
111 4 : m_ViewFrustum[0].m_Norm.X = scissor[1].X*MatFinal._41 - MatFinal._11;
112 4 : m_ViewFrustum[0].m_Norm.Y = scissor[1].X*MatFinal._42 - MatFinal._12;
113 4 : m_ViewFrustum[0].m_Norm.Z = scissor[1].X*MatFinal._43 - MatFinal._13;
114 4 : m_ViewFrustum[0].m_Dist = scissor[1].X*MatFinal._44 - MatFinal._14;
115 :
116 : // get the LEFT plane
117 4 : m_ViewFrustum[1].m_Norm.X = -scissor[0].X*MatFinal._41 + MatFinal._11;
118 4 : m_ViewFrustum[1].m_Norm.Y = -scissor[0].X*MatFinal._42 + MatFinal._12;
119 4 : m_ViewFrustum[1].m_Norm.Z = -scissor[0].X*MatFinal._43 + MatFinal._13;
120 4 : m_ViewFrustum[1].m_Dist = -scissor[0].X*MatFinal._44 + MatFinal._14;
121 :
122 : // get the BOTTOM plane
123 4 : m_ViewFrustum[2].m_Norm.X = -scissor[0].Y*MatFinal._41 + MatFinal._21;
124 4 : m_ViewFrustum[2].m_Norm.Y = -scissor[0].Y*MatFinal._42 + MatFinal._22;
125 4 : m_ViewFrustum[2].m_Norm.Z = -scissor[0].Y*MatFinal._43 + MatFinal._23;
126 4 : m_ViewFrustum[2].m_Dist = -scissor[0].Y*MatFinal._44 + MatFinal._24;
127 :
128 : // get the TOP plane
129 4 : m_ViewFrustum[3].m_Norm.X = scissor[1].Y*MatFinal._41 - MatFinal._21;
130 4 : m_ViewFrustum[3].m_Norm.Y = scissor[1].Y*MatFinal._42 - MatFinal._22;
131 4 : m_ViewFrustum[3].m_Norm.Z = scissor[1].Y*MatFinal._43 - MatFinal._23;
132 4 : m_ViewFrustum[3].m_Dist = scissor[1].Y*MatFinal._44 - MatFinal._24;
133 :
134 : // get the FAR plane
135 4 : m_ViewFrustum[4].m_Norm.X = scissor[1].Z*MatFinal._41 - MatFinal._31;
136 4 : m_ViewFrustum[4].m_Norm.Y = scissor[1].Z*MatFinal._42 - MatFinal._32;
137 4 : m_ViewFrustum[4].m_Norm.Z = scissor[1].Z*MatFinal._43 - MatFinal._33;
138 4 : m_ViewFrustum[4].m_Dist = scissor[1].Z*MatFinal._44 - MatFinal._34;
139 :
140 : // get the NEAR plane
141 4 : m_ViewFrustum[5].m_Norm.X = -scissor[0].Z*MatFinal._41 + MatFinal._31;
142 4 : m_ViewFrustum[5].m_Norm.Y = -scissor[0].Z*MatFinal._42 + MatFinal._32;
143 4 : m_ViewFrustum[5].m_Norm.Z = -scissor[0].Z*MatFinal._43 + MatFinal._33;
144 4 : m_ViewFrustum[5].m_Dist = -scissor[0].Z*MatFinal._44 + MatFinal._34;
145 :
146 28 : for (size_t i = 0; i < 6; ++i)
147 24 : m_ViewFrustum[i].Normalize();
148 4 : }
149 :
150 0 : void CCamera::ClipFrustum(const CPlane& clipPlane)
151 : {
152 0 : CPlane normClipPlane = clipPlane;
153 0 : normClipPlane.Normalize();
154 0 : m_ViewFrustum.AddPlane(normClipPlane);
155 0 : }
156 :
157 13 : void CCamera::SetViewPort(const SViewPort& viewport)
158 : {
159 13 : m_ViewPort.m_X = viewport.m_X;
160 13 : m_ViewPort.m_Y = viewport.m_Y;
161 13 : m_ViewPort.m_Width = viewport.m_Width;
162 13 : m_ViewPort.m_Height = viewport.m_Height;
163 13 : }
164 :
165 28 : float CCamera::GetAspectRatio() const
166 : {
167 12 : return static_cast<float>(m_ViewPort.m_Width) / static_cast<float>(m_ViewPort.m_Height);
168 : }
169 :
170 18 : CCamera::Quad CCamera::GetViewQuad(const float dist) const
171 : {
172 18 : if (m_ProjType == ProjectionType::CUSTOM)
173 : {
174 3 : const CMatrix3D invProjection = m_ProjMat.GetInverse();
175 3 : const std::array<CVector2D, 4> ndcCorners = {
176 : CVector2D{-1.0f, -1.0f}, CVector2D{1.0f, -1.0f},
177 3 : CVector2D{1.0f, 1.0f}, CVector2D{-1.0f, 1.0f}};
178 3 : Quad quad;
179 15 : for (size_t idx = 0; idx < 4; ++idx)
180 : {
181 12 : const CVector2D& corner = ndcCorners[idx];
182 12 : CVector4D nearCorner =
183 12 : invProjection.Transform(CVector4D(corner.X, corner.Y, -1.0f, 1.0f));
184 12 : nearCorner /= nearCorner.W;
185 12 : CVector4D farCorner =
186 12 : invProjection.Transform(CVector4D(corner.X, corner.Y, 1.0f, 1.0f));
187 12 : farCorner /= farCorner.W;
188 12 : const float t = (dist - nearCorner.Z) / (farCorner.Z - nearCorner.Z);
189 12 : const CVector4D quadCorner = nearCorner * (1.0 - t) + farCorner * t;
190 12 : quad[idx].X = quadCorner.X;
191 12 : quad[idx].Y = quadCorner.Y;
192 12 : quad[idx].Z = quadCorner.Z;
193 : }
194 3 : return quad;
195 : }
196 :
197 15 : const float y = m_ProjType == ProjectionType::PERSPECTIVE ? dist * tanf(m_FOV * 0.5f) : m_OrthoScale * 0.5f;
198 15 : const float x = y * GetAspectRatio();
199 :
200 15 : return {{
201 : {-x, -y, dist},
202 : {x, -y, dist},
203 : {x, y, dist},
204 : {-x, y, dist}
205 15 : }};
206 : }
207 :
208 6 : CCamera::Ray CCamera::BuildCameraRay(const int px, const int py) const
209 : {
210 6 : ENSURE(m_ProjType == ProjectionType::PERSPECTIVE || m_ProjType == ProjectionType::ORTHO);
211 :
212 : // Coordinates relative to the camera plane.
213 6 : const float dx = static_cast<float>(px) / m_ViewPort.m_Width;
214 6 : const float dy = 1.0f - static_cast<float>(py) / m_ViewPort.m_Height;
215 :
216 6 : Quad points{GetViewQuad(m_FarPlane)};
217 :
218 : // Transform from camera space to world space.
219 30 : for (CVector3D& point : points)
220 24 : point = m_Orientation.Transform(point);
221 :
222 : // Get world space position of mouse point at the far clipping plane.
223 6 : const CVector3D basisX = points[1] - points[0];
224 6 : const CVector3D basisY = points[3] - points[0];
225 :
226 6 : Ray result;
227 6 : if (m_ProjType == ProjectionType::PERSPECTIVE)
228 : {
229 : // Build direction for the camera origin to the target point.
230 3 : result.origin = m_Orientation.GetTranslation();
231 3 : CVector3D targetPoint = points[0] + (basisX * dx) + (basisY * dy);
232 3 : result.direction = targetPoint - result.origin;
233 : }
234 3 : else if (m_ProjType == ProjectionType::ORTHO)
235 : {
236 3 : result.origin = m_Orientation.GetTranslation() + (basisX * (dx - 0.5f)) + (basisY * (dy - 0.5f));
237 3 : result.direction = m_Orientation.GetIn();
238 : }
239 6 : result.direction.Normalize();
240 6 : return result;
241 : }
242 :
243 0 : CVector2D CCamera::GetScreenCoordinates(const CVector3D& world) const
244 : {
245 0 : CMatrix3D transform = m_ProjMat * m_Orientation.GetInverse();
246 :
247 0 : CVector4D screenspace = transform.Transform(CVector4D(world.X, world.Y, world.Z, 1.0f));
248 :
249 0 : float x = screenspace.X / screenspace.W;
250 0 : float y = screenspace.Y / screenspace.W;
251 0 : x = (x + 1) * 0.5f * m_ViewPort.m_Width;
252 0 : y = (1 - y) * 0.5f * m_ViewPort.m_Height;
253 0 : return {x, y};
254 : }
255 :
256 0 : CVector3D CCamera::GetWorldCoordinates(int px, int py, bool aboveWater) const
257 : {
258 0 : CHFTracer tracer(g_Game->GetWorld()->GetTerrain());
259 0 : int x, z;
260 0 : CVector3D terrainPoint, waterPoint;
261 :
262 0 : const auto [origin, dir] = BuildCameraRay(px, py);
263 :
264 0 : bool gotTerrain = tracer.RayIntersect(origin, dir, x, z, terrainPoint);
265 :
266 0 : if (!aboveWater)
267 : {
268 0 : if (gotTerrain)
269 0 : return terrainPoint;
270 :
271 : // Off the edge of the world?
272 : // Work out where it /would/ hit, if the map were extended out to infinity with average height.
273 0 : return GetWorldCoordinates(px, py, 50.0f);
274 : }
275 :
276 0 : CPlane plane;
277 0 : plane.Set(CVector3D(0.f, 1.f, 0.f), // upwards normal
278 0 : CVector3D(0.f, g_Renderer.GetSceneRenderer().GetWaterManager().m_WaterHeight, 0.f)); // passes through water plane
279 :
280 0 : bool gotWater = plane.FindRayIntersection( origin, dir, &waterPoint );
281 :
282 : // Clamp the water intersection to within the map's bounds, so that
283 : // we'll always return a valid position on the map
284 0 : const ssize_t mapSize = g_Game->GetWorld()->GetTerrain().GetVerticesPerSide();
285 0 : if (gotWater)
286 : {
287 0 : waterPoint.X = Clamp<float>(waterPoint.X, 0.f, (mapSize - 1) * TERRAIN_TILE_SIZE);
288 0 : waterPoint.Z = Clamp<float>(waterPoint.Z, 0.f, (mapSize - 1) * TERRAIN_TILE_SIZE);
289 : }
290 :
291 0 : if (gotTerrain)
292 : {
293 0 : if (gotWater)
294 : {
295 : // Intersecting both heightmap and water plane; choose the closest of those
296 0 : if ((origin - terrainPoint).LengthSquared() < (origin - waterPoint).LengthSquared())
297 0 : return terrainPoint;
298 : else
299 0 : return waterPoint;
300 : }
301 : else
302 : {
303 : // Intersecting heightmap but parallel to water plane
304 0 : return terrainPoint;
305 : }
306 : }
307 : else
308 : {
309 0 : if (gotWater)
310 : {
311 : // Only intersecting water plane
312 0 : return waterPoint;
313 : }
314 : else
315 : {
316 : // Not intersecting terrain or water; just return 0,0,0.
317 0 : return CVector3D(0.f, 0.f, 0.f);
318 : }
319 : }
320 :
321 : }
322 :
323 0 : CVector3D CCamera::GetWorldCoordinates(int px, int py, float h) const
324 : {
325 0 : CPlane plane;
326 0 : plane.Set(CVector3D(0.f, 1.f, 0.f), CVector3D(0.f, h, 0.f)); // upwards normal, passes through h
327 :
328 0 : CVector3D currentTarget;
329 :
330 0 : const auto [origin, dir] = BuildCameraRay(px, py);
331 :
332 0 : if (plane.FindRayIntersection(origin, dir, ¤tTarget))
333 0 : return currentTarget;
334 :
335 : // No intersection with the infinite plane - nothing sensible can be returned,
336 : // so just choose an arbitrary point on the plane
337 0 : return CVector3D(0.f, h, 0.f);
338 : }
339 :
340 0 : CVector3D CCamera::GetFocus() const
341 : {
342 : // Basically the same as GetWorldCoordinates
343 :
344 0 : CHFTracer tracer(g_Game->GetWorld()->GetTerrain());
345 0 : int x, z;
346 :
347 0 : CVector3D origin, dir, terrainPoint, waterPoint;
348 :
349 0 : origin = m_Orientation.GetTranslation();
350 0 : dir = m_Orientation.GetIn();
351 :
352 0 : bool gotTerrain = tracer.RayIntersect(origin, dir, x, z, terrainPoint);
353 :
354 0 : CPlane plane;
355 0 : plane.Set(CVector3D(0.f, 1.f, 0.f), // upwards normal
356 0 : CVector3D(0.f, g_Renderer.GetSceneRenderer().GetWaterManager().m_WaterHeight, 0.f)); // passes through water plane
357 :
358 0 : bool gotWater = plane.FindRayIntersection( origin, dir, &waterPoint );
359 :
360 : // Clamp the water intersection to within the map's bounds, so that
361 : // we'll always return a valid position on the map
362 0 : const ssize_t mapSize = g_Game->GetWorld()->GetTerrain().GetVerticesPerSide();
363 0 : if (gotWater)
364 : {
365 0 : waterPoint.X = Clamp<float>(waterPoint.X, 0.f, (mapSize - 1) * TERRAIN_TILE_SIZE);
366 0 : waterPoint.Z = Clamp<float>(waterPoint.Z, 0.f, (mapSize - 1) * TERRAIN_TILE_SIZE);
367 : }
368 :
369 0 : if (gotTerrain)
370 : {
371 0 : if (gotWater)
372 : {
373 : // Intersecting both heightmap and water plane; choose the closest of those
374 0 : if ((origin - terrainPoint).LengthSquared() < (origin - waterPoint).LengthSquared())
375 0 : return terrainPoint;
376 : else
377 0 : return waterPoint;
378 : }
379 : else
380 : {
381 : // Intersecting heightmap but parallel to water plane
382 0 : return terrainPoint;
383 : }
384 : }
385 : else
386 : {
387 0 : if (gotWater)
388 : {
389 : // Only intersecting water plane
390 0 : return waterPoint;
391 : }
392 : else
393 : {
394 : // Not intersecting terrain or water; just return 0,0,0.
395 0 : return CVector3D(0.f, 0.f, 0.f);
396 : }
397 : }
398 : }
399 :
400 11 : CBoundingBoxAligned CCamera::GetBoundsInViewPort(const CBoundingBoxAligned& boundigBox) const
401 : {
402 11 : const CVector3D cameraPosition = GetOrientation().GetTranslation();
403 11 : if (boundigBox.IsPointInside(cameraPosition))
404 2 : return CBoundingBoxAligned(CVector3D(-1.0f, -1.0f, 0.0f), CVector3D(1.0f, 1.0f, 0.0f));
405 :
406 10 : const CMatrix3D viewProjection = GetViewProjection();
407 100 : CBoundingBoxAligned viewPortBounds;
408 : #define ADD_VISIBLE_POINT_TO_VIEWBOUNDS(POSITION) STMT( \
409 : CVector4D v = viewProjection.Transform(CVector4D((POSITION).X, (POSITION).Y, (POSITION).Z, 1.0f)); \
410 : if (v.W != 0.0f) \
411 : viewPortBounds += CVector3D(v.X, v.Y, v.Z) * (1.0f / v.W); )
412 :
413 : std::array<CVector3D, 8> worldPositions;
414 10 : std::array<bool, 8> isBehindNearPlane;
415 10 : const CVector3D lookDirection = GetOrientation().GetIn();
416 : // Check corners.
417 90 : for (size_t idx = 0; idx < 8; ++idx)
418 : {
419 80 : worldPositions[idx] = CVector3D(boundigBox[(idx >> 0) & 0x1].X, boundigBox[(idx >> 1) & 0x1].Y, boundigBox[(idx >> 2) & 0x1].Z);
420 80 : isBehindNearPlane[idx] = lookDirection.Dot(worldPositions[idx]) < lookDirection.Dot(cameraPosition) + GetNearPlane();
421 80 : if (!isBehindNearPlane[idx])
422 68 : ADD_VISIBLE_POINT_TO_VIEWBOUNDS(worldPositions[idx]);
423 : }
424 : // Check edges for intersections with the near plane.
425 90 : for (size_t idxBegin = 0; idxBegin < 8; ++idxBegin)
426 320 : for (size_t nextComponent = 0; nextComponent < 3; ++nextComponent)
427 : {
428 240 : const size_t idxEnd = idxBegin | (static_cast<size_t>(1) << nextComponent);
429 240 : if (idxBegin == idxEnd || isBehindNearPlane[idxBegin] == isBehindNearPlane[idxEnd])
430 232 : continue;
431 12 : CVector3D intersection;
432 : // Intersect the segment with the near plane.
433 12 : if (!m_ViewFrustum[5].FindLineSegIntersection(worldPositions[idxBegin], worldPositions[idxEnd], &intersection))
434 4 : continue;
435 8 : ADD_VISIBLE_POINT_TO_VIEWBOUNDS(intersection);
436 : }
437 : #undef ADD_VISIBLE_POINT_TO_VIEWBOUNDS
438 10 : if (viewPortBounds[0].X >= 1.0f || viewPortBounds[1].X <= -1.0f || viewPortBounds[0].Y >= 1.0f || viewPortBounds[1].Y <= -1.0f)
439 4 : return CBoundingBoxAligned{};
440 6 : return viewPortBounds;
441 : }
442 :
443 9 : void CCamera::LookAt(const CVector3D& camera, const CVector3D& focus, const CVector3D& up)
444 : {
445 9 : CVector3D delta = focus - camera;
446 9 : LookAlong(camera, delta, up);
447 9 : }
448 :
449 13 : void CCamera::LookAlong(const CVector3D& camera, CVector3D orientation, CVector3D up)
450 : {
451 13 : orientation.Normalize();
452 13 : up.Normalize();
453 13 : const CVector3D s = orientation.Cross(up);
454 13 : up = s.Cross(orientation);
455 :
456 13 : m_Orientation._11 = -s.X; m_Orientation._12 = up.X; m_Orientation._13 = orientation.X; m_Orientation._14 = camera.X;
457 13 : m_Orientation._21 = -s.Y; m_Orientation._22 = up.Y; m_Orientation._23 = orientation.Y; m_Orientation._24 = camera.Y;
458 13 : m_Orientation._31 = -s.Z; m_Orientation._32 = up.Z; m_Orientation._33 = orientation.Z; m_Orientation._34 = camera.Z;
459 13 : m_Orientation._41 = 0.0f; m_Orientation._42 = 0.0f; m_Orientation._43 = 0.0f; m_Orientation._44 = 1.0f;
460 13 : }
|