From e1f6daabb777ac0d7db63cc1276c86c3b206629d Mon Sep 17 00:00:00 2001 From: ostermine Date: Wed, 11 Nov 2026 21:59:06 +0300 Subject: [PATCH] fix camera view rotation far from the world origin Camera::getView built the view with lookAt(position, position + front): the direction came back as a difference of large floats. Far from the origin the view turned away from where the camera looks - at 16M blocks by up to 24 degrees, at 30M the camera looked straight up or down whatever its yaw (at pitch 0 the direction is a zero vector, the matrix is NaN). The rotation is built from front itself now, then translated by -position: the same matrix, without the subtraction. --- src/window/Camera.cpp | 13 ++++--------- test/window/Camera.cpp | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 9 deletions(-) create mode 100644 test/window/Camera.cpp diff --git a/src/window/Camera.cpp b/src/window/Camera.cpp index fb23676d2..a8b2e6431 100644 --- a/src/window/Camera.cpp +++ b/src/window/Camera.cpp @@ -41,16 +41,11 @@ glm::mat4 Camera::getProjection() const { } glm::mat4 Camera::getView(bool pos) const { - glm::vec3 camera_pos = this->position; - if (!pos) { - camera_pos = glm::vec3(0.0f); - } - if (perspective) { - return glm::lookAt(camera_pos, camera_pos + front, up); - } else { - return glm::lookAt(camera_pos, camera_pos + front, up); - //return glm::translate(glm::mat4(1.0f), camera_pos); + glm::mat4 view = glm::lookAt(glm::vec3(0.0f), front, up); + if (pos) { + view = glm::translate(view, -position); } + return view; } glm::mat4 Camera::getProjView(bool pos) const { diff --git a/test/window/Camera.cpp b/test/window/Camera.cpp new file mode 100644 index 000000000..51c80b14e --- /dev/null +++ b/test/window/Camera.cpp @@ -0,0 +1,31 @@ +#include + +#include +#include + +#include "window/Camera.hpp" + +TEST(Camera, ViewRotationFarFromOrigin) { + for (float coord : {0.0f, 1e5f, 1e6f, 3e7f}) { + for (bool rotated : {false, true}) { + Camera camera(glm::vec3(coord, 64.0f, coord), 1.0f); + if (rotated) { + camera.rotate(glm::radians(-20.0f), glm::radians(35.0f), 0.0f); + } + glm::mat4 rotation = camera.getView(false); + glm::mat4 view = camera.getView(); + for (int col = 0; col < 4; col++) { + for (int row = 0; row < 4; row++) { + ASSERT_TRUE(std::isfinite(view[col][row])) + << "at " << coord; + } + } + for (int col = 0; col < 3; col++) { + for (int row = 0; row < 3; row++) { + EXPECT_NEAR(rotation[col][row], view[col][row], 1e-5f) + << "at " << coord << ", rotated " << rotated; + } + } + } + } +}