From e1f6daabb777ac0d7db63cc1276c86c3b206629d Mon Sep 17 00:00:00 2001 From: ostermine Date: Wed, 11 Nov 2026 21:59:06 +0300 Subject: [PATCH 1/8] 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; + } + } + } + } +} From 89bdadd6aacdd53fd798f466dbde3751fe169284 Mon Sep 17 00:00:00 2001 From: ostermine Date: Thu, 12 Nov 2026 00:48:30 +0300 Subject: [PATCH 2/8] render the world relative to an origin near the camera World coordinates were passed to GPU as floats: u_model of a chunk and of a model had the world translation, vertices of translucent blocks, particles, precipitation, block wrappers, lines and 3D texts were built in the world space, and the camera position was subtracted in shaders. The float step grows with the distance from the world origin (6 cm at 1M blocks, 2 m at 30M): blocks got skewed, then stuck together. Camera::getOrigin() is an integer point near the camera (X and Z are rounded to 1024 blocks, Y is 0). Camera::getView() is relative to it, and every position passed to GPU is "world - origin" calculated on CPU, so the shaders keep working with small numbers and do not change: u_cameraPos, a_modelpos, u_inverseView and the shadows matrices are in the same space as before, shifted by the origin. Matrices of a shadow map are converted from the origin of its camera to the origin of the player camera. The clouds shader gets the origin wrapped by the period of its waves, the waves stay bound to the world. Vertices of translucent blocks are local to the chunk now, as vertices of opaque ones, and drawn with u_model of the chunk. --- .../scripting/builtins/libgfx-posteffects.md | 6 ++ .../scripting/builtins/libgfx-posteffects.md | 6 ++ res/shaders/clouds.glslv | 3 + src/animation/rigging.cpp | 23 +++++-- src/animation/rigging.hpp | 7 +- src/graphics/core/PostProcessing.cpp | 2 +- src/graphics/core/Shadows.cpp | 23 +++++-- src/graphics/core/Shadows.hpp | 2 +- src/graphics/render/BlockWrapsRenderer.cpp | 14 ++-- src/graphics/render/BlockWrapsRenderer.hpp | 7 +- src/graphics/render/BlocksRenderer.cpp | 11 +-- src/graphics/render/ChunksRenderer.cpp | 67 ++++++++++--------- src/graphics/render/CloudsRenderer.cpp | 25 +++++-- src/graphics/render/DebugLinesRenderer.cpp | 20 +++--- src/graphics/render/EntitiesRenderer.cpp | 54 +++++++++++---- src/graphics/render/EntitiesRenderer.hpp | 12 +++- src/graphics/render/HandsRenderer.cpp | 3 +- src/graphics/render/MainBatch.cpp | 4 +- src/graphics/render/MainBatch.hpp | 2 +- src/graphics/render/ModelBatch.cpp | 6 +- src/graphics/render/ModelBatch.hpp | 6 +- src/graphics/render/ParticlesRenderer.cpp | 2 +- src/graphics/render/PrecipitationRenderer.cpp | 19 +++--- src/graphics/render/TextsRenderer.cpp | 13 ++-- src/graphics/render/WorldRenderer.cpp | 25 ++++--- src/graphics/render/WorldRenderer.hpp | 2 +- src/maths/util.hpp | 4 ++ src/window/Camera.cpp | 16 ++++- src/window/Camera.hpp | 5 ++ test/window/Camera.cpp | 21 ++++++ 30 files changed, 283 insertions(+), 127 deletions(-) diff --git a/doc/en/scripting/builtins/libgfx-posteffects.md b/doc/en/scripting/builtins/libgfx-posteffects.md index 5e36683c4..c8a2835c1 100644 --- a/doc/en/scripting/builtins/libgfx-posteffects.md +++ b/doc/en/scripting/builtins/libgfx-posteffects.md @@ -55,3 +55,9 @@ for i = 0, 63 do end gfx.posteffects.set_array(slot, "u_arrayName", Bytearray_as_string(buffer)) ``` + +## Coordinates in shaders + +World-space values available in shaders (`u_cameraPos`, `u_view`, `u_inverseView`, positions of vertices and models) are relative to the rendering origin, not to the world origin. The rendering origin is an integer point near the camera: its X and Z are multiples of 1024 blocks, Y is 0. This keeps `float` precise far from the world origin. + +Directions, distances and positions relative to the camera do not depend on the rendering origin. Neither does an effect bound to the blocks grid or repeating with a period that divides 1024. diff --git a/doc/ru/scripting/builtins/libgfx-posteffects.md b/doc/ru/scripting/builtins/libgfx-posteffects.md index 64fb6c064..bde5554cf 100644 --- a/doc/ru/scripting/builtins/libgfx-posteffects.md +++ b/doc/ru/scripting/builtins/libgfx-posteffects.md @@ -55,3 +55,9 @@ for i = 0, 63 do end gfx.posteffects.set_array(slot, "u_имяМассива", Bytearray_as_string(buffer)) ``` + +## Координаты в шейдерах + +Значения в мировом пространстве, доступные в шейдерах (`u_cameraPos`, `u_view`, `u_inverseView`, позиции вершин и моделей), заданы относительно начала координат рендера, а не начала координат мира. Начало координат рендера - целочисленная точка рядом с камерой: X и Z кратны 1024 блокам, Y равен 0. Так `float` сохраняет точность вдали от начала координат мира. + +Направления, расстояния и позиции относительно камеры от начала координат рендера не зависят. Не зависит и эффект, привязанный к сетке блоков или повторяющийся с периодом, на который делится 1024. diff --git a/res/shaders/clouds.glslv b/res/shaders/clouds.glslv index e1576f633..29067abca 100644 --- a/res/shaders/clouds.glslv +++ b/res/shaders/clouds.glslv @@ -11,14 +11,17 @@ layout (location = 3) in vec4 v_normal; #include uniform float u_dayTime; +uniform vec2 u_waveOffset; out vec4 a_torchLight; void main() { a_modelpos = u_model * vec4(v_position, 1.0f); + a_modelpos.xz += u_waveOffset; a_modelpos.x += sin(u_timer * 0.05 + a_modelpos.z * 0.002) * 1.5; a_modelpos.z += sin(u_timer * 0.2 + a_modelpos.x * 0.002) * 1.5; a_modelpos.y += sin(u_timer * 0.1 + (a_modelpos.x + a_modelpos.z) * 0.001) * 2.0; + a_modelpos.xz -= u_waveOffset; vec3 pos3d = a_modelpos.xyz - u_cameraPos; diff --git a/src/animation/rigging.cpp b/src/animation/rigging.cpp index 7d5397c76..522ff7b12 100644 --- a/src/animation/rigging.cpp +++ b/src/animation/rigging.cpp @@ -8,6 +8,7 @@ #include "data/dv_util.hpp" #include "graphics/commons/Model.hpp" #include "graphics/render/ModelBatch.hpp" +#include "maths/util.hpp" using namespace rigging; @@ -160,13 +161,15 @@ void SkeletonConfig::update( Skeleton& skeleton, const glm::mat3& rotation, const glm::vec3& position, - const glm::vec3& scale + const glm::vec3& scale, + const glm::ivec3& origin ) const { glm::vec3 pos = position; const auto& interpolation = skeleton.interpolation; if (interpolation.isEnabled() && interpolation.isRefreshed()) { pos = interpolation.getCurrent(); } + pos = util::to_local(pos, origin); glm::mat3 rot = rotation; const auto& rotationInterpolation = skeleton.rotationInterpolation; if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) { @@ -253,18 +256,25 @@ void SkeletonConfig::render( const glm::mat3& rotation, const glm::vec3& position, const glm::vec3& scale, + const glm::ivec3& origin, bool translucent ) const { if (skeleton.config->root == nullptr) { return; } - update(skeleton, rotation, position, scale); + update(skeleton, rotation, position, scale, origin); if (!skeleton.visible) { return; } processModels( - assets, skeleton, position, scale, &batch, lightingMode, translucent + assets, + skeleton, + util::to_local(position, origin), + scale, + &batch, + lightingMode, + translucent ); } @@ -273,16 +283,17 @@ void SkeletonConfig::updateBounds( Skeleton& skeleton, const glm::mat3& rotation, const glm::vec3& position, - const glm::vec3& scale + const glm::vec3& scale, + const glm::ivec3& origin ) const { if (skeleton.config->root == nullptr) { return; } - update(skeleton, rotation, position, scale); + update(skeleton, rotation, position, scale, origin); processModels( assets, skeleton, - position, + util::to_local(position, origin), scale, nullptr, ModelLightingMode::SOLID, diff --git a/src/animation/rigging.hpp b/src/animation/rigging.hpp index a35650a70..939e7eaf4 100644 --- a/src/animation/rigging.hpp +++ b/src/animation/rigging.hpp @@ -152,7 +152,8 @@ namespace rigging { Skeleton& skeleton, const glm::mat3& rotation, const glm::vec3& position, - const glm::vec3& scale + const glm::vec3& scale, + const glm::ivec3& origin ) const; void render( @@ -163,6 +164,7 @@ namespace rigging { const glm::mat3& rotation, const glm::vec3& position, const glm::vec3& scale, + const glm::ivec3& origin, bool translucent = false ) const; @@ -171,7 +173,8 @@ namespace rigging { Skeleton& skeleton, const glm::mat3& rotation, const glm::vec3& position, - const glm::vec3& scale + const glm::vec3& scale, + const glm::ivec3& origin ) const; Skeleton instance() const { diff --git a/src/graphics/core/PostProcessing.cpp b/src/graphics/core/PostProcessing.cpp index 3a0b538fd..8be4410e3 100644 --- a/src/graphics/core/PostProcessing.cpp +++ b/src/graphics/core/PostProcessing.cpp @@ -109,7 +109,7 @@ void PostProcessing::configureEffect( shader.uniform1i("u_noise", TARGET_SSAO); // used in SSAO pass shader.uniform1i("u_ssao", TARGET_SSAO); shader.uniform2i("u_screenSize", viewport / downsample); - shader.uniform3f("u_cameraPos", camera.position); + shader.uniform3f("u_cameraPos", camera.getLocalPosition()); shader.uniform1f("u_timer", timer); shader.uniformMatrix("u_projection", camera.getProjection()); const auto view = camera.getView(); diff --git a/src/graphics/core/Shadows.cpp b/src/graphics/core/Shadows.cpp index 8defa40f8..240471fbf 100644 --- a/src/graphics/core/Shadows.cpp +++ b/src/graphics/core/Shadows.cpp @@ -95,7 +95,17 @@ void Shadows::setQuality(int quality) { this->quality = quality; } -void Shadows::setup(Shader& shader, const Weather& weather) { +static glm::mat4 calc_shadows_matrix( + const Camera& shadowCamera, const glm::ivec3& origin +) { + return glm::translate( + shadowCamera.getProjView(), glm::vec3(origin - shadowCamera.getOrigin()) + ); +} + +void Shadows::setup( + Shader& shader, const Camera& camera, const Weather& weather +) { if (!shadows) { return; } @@ -106,8 +116,13 @@ void Shadows::setup(Shader& shader, const Weather& weather) { glm::mod((worldInfo.daytime + 0.5f) * 2.0f, 1.0f) * 2.0f - 1.0f )); shader.uniform1i("u_screen", 0); - shader.uniformMatrix("u_shadowsMatrix[0]", shadowCamera.getProjView()); - shader.uniformMatrix("u_shadowsMatrix[1]", wideShadowCamera.getProjView()); + const glm::ivec3 origin = camera.getOrigin(); + shader.uniformMatrix( + "u_shadowsMatrix[0]", calc_shadows_matrix(shadowCamera, origin) + ); + shader.uniformMatrix( + "u_shadowsMatrix[1]", calc_shadows_matrix(wideShadowCamera, origin) + ); shader.uniform3f("u_sunDir", shadowCamera.front); shader.uniform1i("u_shadowsRes", shadowMap->getResolution()); shader.uniform1f("u_shadowsOpacity", shadowsOpacity); // TODO: make it configurable @@ -197,7 +212,7 @@ void Shadows::generateShadowsMap( auto view = shadowCamera.getView(); - auto currentPos = shadowCamera.position; + auto currentPos = shadowCamera.getLocalPosition(); auto topRight = shadowCamera.right + shadowCamera.up; auto min = view * glm::vec4(currentPos - topRight * shadowMapSize * 0.5f, 1.0f); auto max = view * glm::vec4(currentPos + topRight * shadowMapSize * 0.5f, 1.0f); diff --git a/src/graphics/core/Shadows.hpp b/src/graphics/core/Shadows.hpp index e387b6e88..5a22675ae 100644 --- a/src/graphics/core/Shadows.hpp +++ b/src/graphics/core/Shadows.hpp @@ -19,7 +19,7 @@ public: Shadows(const Level& level); ~Shadows(); - void setup(Shader& shader, const Weather& weather); + void setup(Shader& shader, const Camera& camera, const Weather& weather); void setQuality(int quality); void refresh( const Camera& camera, diff --git a/src/graphics/render/BlockWrapsRenderer.cpp b/src/graphics/render/BlockWrapsRenderer.cpp index d892605e0..0d566e50f 100644 --- a/src/graphics/render/BlockWrapsRenderer.cpp +++ b/src/graphics/render/BlockWrapsRenderer.cpp @@ -10,6 +10,7 @@ #include "lighting/Lightmap.hpp" #include "voxels/Block.hpp" #include "voxels/Chunks.hpp" +#include "window/Camera.hpp" #include @@ -24,7 +25,9 @@ BlockWrapsRenderer::BlockWrapsRenderer( BlockWrapsRenderer::~BlockWrapsRenderer() = default; -void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) { +void BlockWrapsRenderer::draw( + BlockWrapper& wrapper, const Texture* texture, const glm::ivec3& origin +) { if (wrapper.cullingBits == 0x0) { return; } @@ -60,7 +63,7 @@ void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) { switch (wrapper.modelType) { case BlockModelType::BLOCK: batch->cube( - glm::vec3(wrapper.position) + glm::vec3(0.5f), + glm::vec3(wrapper.position - origin) + glm::vec3(0.5f), glm::vec3(1.01f), wrapper.uvRegions, light, @@ -73,7 +76,7 @@ void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) { const auto& aabb = def.getHitboxes(vox->state).at(0); const auto& size = aabb.size(); batch->cube( - glm::vec3(wrapper.position) + aabb.center(), + glm::vec3(wrapper.position - origin) + aabb.center(), size * glm::vec3(1.01f), wrapper.uvRegions, light, @@ -134,8 +137,9 @@ void BlockWrapsRenderer::refreshWrapper(BlockWrapper& wrapper) { } } -void BlockWrapsRenderer::draw(const DrawContext& pctx) { +void BlockWrapsRenderer::draw(const DrawContext& pctx, const Camera& camera) { auto ctx = pctx.sub(); + const glm::ivec3 origin = camera.getOrigin(); auto& shader = assets.require("entity"); shader.use(); @@ -151,7 +155,7 @@ void BlockWrapsRenderer::draw(const DrawContext& pctx) { } for (const auto& [texture, wrapper] : renderOrder) { batch->setTexture(texture); - draw(*wrapper, texture); + draw(*wrapper, texture, origin); } batch->flush(); } diff --git a/src/graphics/render/BlockWrapsRenderer.hpp b/src/graphics/render/BlockWrapsRenderer.hpp index fb4893877..16932e5bd 100644 --- a/src/graphics/render/BlockWrapsRenderer.hpp +++ b/src/graphics/render/BlockWrapsRenderer.hpp @@ -12,6 +12,7 @@ #include class Assets; +class Camera; class Content; class Chunks; class Texture; @@ -41,7 +42,9 @@ class BlockWrapsRenderer { std::unordered_map> wrappers; u64id_t nextWrapper = 1; - void draw(BlockWrapper& wrapper, const Texture* texture); + void draw( + BlockWrapper& wrapper, const Texture* texture, const glm::ivec3& origin + ); void refreshWrapper(BlockWrapper& wrapper); void clearOrder(const BlockWrapper* const wrapper); @@ -51,7 +54,7 @@ public: ); ~BlockWrapsRenderer(); - void draw(const DrawContext& ctx); + void draw(const DrawContext& ctx, const Camera& camera); u64id_t add( const glm::ivec3& position, diff --git a/src/graphics/render/BlocksRenderer.cpp b/src/graphics/render/BlocksRenderer.cpp index 7fbb09e82..37cab0e42 100644 --- a/src/graphics/render/BlocksRenderer.cpp +++ b/src/graphics/render/BlocksRenderer.cpp @@ -637,12 +637,7 @@ SortingMeshData BlocksRenderer::renderTranslucent( continue; } SortingMeshEntry entry { - glm::vec3( - x + chunk->x * CHUNK_W + 0.5f, - y + 0.5f, - z + chunk->z * CHUNK_D + 0.5f - ), - util::Buffer(indexCount), 0}; + glm::vec3(x, y, z), util::Buffer(indexCount), 0}; totalSize += entry.vertexData.size(); @@ -660,10 +655,6 @@ SortingMeshData BlocksRenderer::renderTranslucent( } else { aabb.addPoint(vertex.position); } - - vertex.position.x += chunk->x * CHUNK_W + 0.5f; - vertex.position.y += 0.5f; - vertex.position.z += chunk->z * CHUNK_D + 0.5f; } sortingMesh.entries.push_back(std::move(entry)); vertexCount = 0; diff --git a/src/graphics/render/ChunksRenderer.cpp b/src/graphics/render/ChunksRenderer.cpp index 6cccbe3fa..cf4956d23 100644 --- a/src/graphics/render/ChunksRenderer.cpp +++ b/src/graphics/render/ChunksRenderer.cpp @@ -12,6 +12,7 @@ #include "window/Camera.hpp" #include "maths/FrustumCulling.hpp" #include "maths/util.hpp" +#include "maths/voxmaths.hpp" #include "util/listutil.hpp" #include "util/ObjectsPool.hpp" #include "util/timeutil.hpp" @@ -241,6 +242,9 @@ void ChunksRenderer::drawShadowsPass( auto denseDistance = settings.graphics.denseRenderDistance.get(); auto denseDistance2 = denseDistance * denseDistance; + const glm::ivec3 origin = camera.getOrigin(); + const glm::vec3 playerPos = util::to_local(playerCamera.position, origin); + for (const auto& chunk : chunks.getChunks()) { if (chunk == nullptr) { continue; @@ -251,16 +255,12 @@ void ChunksRenderer::drawShadowsPass( continue; } - glm::vec3 coord( - pos.x * CHUNK_W + 0.5f, 0.5f, pos.y * CHUNK_D + 0.5f - ); + int x = pos.x * CHUNK_W - origin.x; + int z = pos.y * CHUNK_D - origin.z; + glm::vec3 coord(x + 0.5f, 0.5f, z + 0.5f); - glm::vec3 min(pos.x * CHUNK_W, chunk->bottom, pos.y * CHUNK_D); - glm::vec3 max( - pos.x * CHUNK_W + CHUNK_W, - chunk->top, - pos.y * CHUNK_D + CHUNK_D - ); + glm::vec3 min(x, chunk->bottom, z); + glm::vec3 max(x + CHUNK_W, chunk->top, z + CHUNK_D); if (!frustum.isBoxVisible(min, max)) { continue; @@ -268,7 +268,7 @@ void ChunksRenderer::drawShadowsPass( glm::mat4 model = glm::translate(glm::mat4(1.0f), coord); shader.uniformMatrix("u_model", model); found->second.mesh->draw(GL_TRIANGLES, - glm::distance2(playerCamera.position * glm::vec3(1, 0, 1), + glm::distance2(playerPos * glm::vec3(1, 0, 1), (min + max) * 0.5f * glm::vec3(1, 0, 1)) < denseDistance2); } } @@ -292,8 +292,13 @@ void ChunksRenderer::drawChunks( indices.push_back(ChunksSortEntry {i, 0}); } } - float px = camera.position.x / static_cast(CHUNK_W) - 0.5f; - float pz = camera.position.z / static_cast(CHUNK_D) - 0.5f; + const glm::ivec3 origin = camera.getOrigin(); + const glm::vec3 cameraPos = camera.getLocalPosition(); + + chunksOffsetX -= floordiv(origin.x); + chunksOffsetY -= floordiv(origin.z); + float px = cameraPos.x / static_cast(CHUNK_W) - 0.5f; + float pz = cameraPos.z / static_cast(CHUNK_D) - 0.5f; for (auto& index : indices) { float x = index.index % chunksWidth + chunksOffsetX - px; float z = index.index / chunksWidth + chunksOffsetY - pz; @@ -323,32 +328,28 @@ void ChunksRenderer::drawChunks( if (mesh.mesh == nullptr) { continue; } + int x = chunk->x * CHUNK_W - origin.x; + int z = chunk->z * CHUNK_D - origin.z; if (culling) { const auto& meshAABB = mesh.meshAABB; auto aabbMin = meshAABB.min(); auto aabbMax = meshAABB.max(); glm::vec3 min( - chunk->x * CHUNK_W + std::min(0.0f, aabbMin.x), + x + std::min(0.0f, aabbMin.x), chunk->bottom, - chunk->z * CHUNK_D + std::min(0.0f, aabbMin.z) - ); - glm::vec3 max( - chunk->x * CHUNK_W + aabbMax.x, - chunk->top, - chunk->z * CHUNK_D + aabbMax.z + z + std::min(0.0f, aabbMin.z) ); + glm::vec3 max(x + aabbMax.x, chunk->top, z + aabbMax.z); if (!frustum.isBoxVisible(min, max)) { continue; } } - glm::vec3 coord( - chunk->x * CHUNK_W + 0.5f, 0.5f, chunk->z * CHUNK_D + 0.5f - ); + glm::vec3 coord(x + 0.5f, 0.5f, z + 0.5f); glm::mat4 model = glm::translate(glm::mat4(1.0f), coord); shader.uniformMatrix("u_model", model); - mesh.mesh->draw(GL_TRIANGLES, glm::distance2(camera.position * glm::vec3(1, 0, 1), + mesh.mesh->draw(GL_TRIANGLES, glm::distance2(cameraPos * glm::vec3(1, 0, 1), (coord + glm::vec3(CHUNK_W * 0.5f, 0.0f, CHUNK_D * 0.5f))) < denseDistance2); visibleChunks++; } @@ -375,12 +376,12 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) { bool culling = settings.graphics.frustumCulling.get(); const auto& chunks = this->chunks.getChunks(); - const auto& cameraPos = camera.position; + const glm::ivec3 origin = camera.getOrigin(); + const glm::vec3 cameraPos = camera.getLocalPosition(); const auto& atlas = assets.require("blocks"); shader.use(); atlas.getTexture()->bind(); - shader.uniformMatrix("u_model", glm::mat4(1.0f)); shader.uniform1i("u_alphaClip", false); for (const auto& index : indices) { @@ -393,16 +394,18 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) { continue; } + int x = chunk->x * CHUNK_W - origin.x; + int z = chunk->z * CHUNK_D - origin.z; if (culling) { - glm::vec3 min(chunk->x * CHUNK_W, chunk->bottom, chunk->z * CHUNK_D); - glm::vec3 max( - chunk->x * CHUNK_W + CHUNK_W, - chunk->top, - chunk->z * CHUNK_D + CHUNK_D - ); + glm::vec3 min(x, chunk->bottom, z); + glm::vec3 max(x + CHUNK_W, chunk->top, z + CHUNK_D); if (!frustum.isBoxVisible(min, max)) continue; } + glm::vec3 coord(x + 0.5f, 0.5f, z + 0.5f); + shader.uniformMatrix( + "u_model", glm::translate(glm::mat4(1.0f), coord) + ); auto& chunkEntries = found->second.sortingMeshData.entries; @@ -418,7 +421,7 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) { } for (auto& entry : chunkEntries) { entry.distance = static_cast( - glm::distance2(entry.position, cameraPos) + glm::distance2(entry.position, cameraPos - coord) ); } if (found->second.sortedMesh == nullptr || diff --git a/src/graphics/render/CloudsRenderer.cpp b/src/graphics/render/CloudsRenderer.cpp index bfc53e4bb..0bb9690b8 100755 --- a/src/graphics/render/CloudsRenderer.cpp +++ b/src/graphics/render/CloudsRenderer.cpp @@ -25,6 +25,7 @@ static debug::Logger logger("clouds-render"); static inline constexpr int MAP_SIZE = 512; static inline constexpr float CLOUD_VOXEL_SCALE = 8.0f; static inline constexpr float CLOUDS_SPEED = 4.0f; +static inline constexpr double CLOUDS_WAVE_PERIOD = glm::two_pi() * 1e3; class CloudsMap { public: @@ -269,8 +270,15 @@ void CloudsRenderer::draw( float scale = CLOUD_VOXEL_SCALE; int totalDiameter = layer.segmentSize * scale; - int gcellX = floordiv(camera.position.x, totalDiameter); - int gcellZ = floordiv(camera.position.z, totalDiameter); + const glm::ivec3 origin = camera.getOrigin(); + const glm::vec3 cameraPos = camera.getLocalPosition(); + + int gcellX = floordiv( + origin.x + static_cast(glm::floor(cameraPos.x)), totalDiameter + ); + int gcellZ = floordiv( + origin.z + static_cast(glm::floor(cameraPos.z)), totalDiameter + ); float speed = CLOUDS_SPEED; float speedX = glm::sin(layerId * 0.3f + 0.4f) * speed / (layerId + 1); @@ -283,10 +291,10 @@ void CloudsRenderer::draw( int lcellX = gcellX - floordiv(glm::floor(timer * speedX), totalDiameter); int lcellZ = gcellZ - floordiv(glm::floor(timer * speedZ), totalDiameter); glm::vec3 position( - -128 * scale + (x + gcellX) * layer.segmentSize * scale + + -128 * scale + ((x + gcellX) * totalDiameter - origin.x) + glm::mod(timer * speedX, static_cast(totalDiameter)), 250 + layerId * 200, - -128 * scale + (z + gcellZ) * layer.segmentSize * scale + + -128 * scale + ((z + gcellZ) * totalDiameter - origin.z) + glm::mod(timer * speedZ, static_cast(totalDiameter)) ); if (glm::distance2( @@ -294,7 +302,7 @@ void CloudsRenderer::draw( position.x + totalDiameter * 0.5f, position.z + totalDiameter * 0.5f ), - glm::vec2(camera.position.x, camera.position.z) + glm::vec2(cameraPos.x, cameraPos.z) ) > 4e6) { continue; } @@ -331,6 +339,13 @@ void CloudsRenderer::draw( shader.uniform1f("u_fogFactor", fogFactor * 0.03f); shader.uniform1f("u_fogCurve", 0.4f); + const glm::ivec3 origin = camera.getOrigin(); + shader.uniform2f( + "u_waveOffset", + std::fmod(origin.x, CLOUDS_WAVE_PERIOD), + std::fmod(origin.z, CLOUDS_WAVE_PERIOD) + ); + for (int i = 0; i < std::min(quality, layers.size()); i++) { draw(layers[i], frustum, shader, camera, timer, i); } diff --git a/src/graphics/render/DebugLinesRenderer.cpp b/src/graphics/render/DebugLinesRenderer.cpp index 3750b2cd0..d5056fc6f 100644 --- a/src/graphics/render/DebugLinesRenderer.cpp +++ b/src/graphics/render/DebugLinesRenderer.cpp @@ -11,15 +11,17 @@ bool DebugLinesRenderer::showPaths = false; -static void draw_route(LineBatch& batch, const voxels::Agent& agent) { +static void draw_route( + LineBatch& batch, const voxels::Agent& agent, const glm::ivec3& origin +) { const auto& route = agent.route; if (!route.found) return; batch.lineWidth(1.0f); for (int i = 1; i < route.nodes.size(); i++) { - const auto& a = glm::vec3(route.nodes.at(i - 1).pos); - const auto& b = glm::vec3(route.nodes.at(i).pos); + const auto& a = glm::vec3(route.nodes.at(i - 1).pos - origin); + const auto& b = glm::vec3(route.nodes.at(i).pos - origin); glm::vec3 a_base = a + glm::vec3(0.5); glm::vec3 b_base = b + glm::vec3(0.5); @@ -99,10 +101,12 @@ void DebugLinesRenderer::render( Shader& linesShader, bool showChunkBorders ) { + const glm::ivec3 origin = camera.getOrigin(); + // In-world lines if (showPaths) { for (const auto& [_, agent] : level.pathfinding->getAgents()) { - draw_route(linesBatch, agent); + draw_route(linesBatch, agent, origin); } } DrawContext ctx = pctx.sub(&linesBatch); @@ -122,12 +126,12 @@ void DebugLinesRenderer::render( drawBorders( linesBatch, - cx * CHUNK_W, + cx * CHUNK_W - origin.x, 0, - cz * CHUNK_D, - (cx + 1) * CHUNK_W, + cz * CHUNK_D - origin.z, + (cx + 1) * CHUNK_W - origin.x, CHUNK_H, - (cz + 1) * CHUNK_D + (cz + 1) * CHUNK_D - origin.z ); } diff --git a/src/graphics/render/EntitiesRenderer.cpp b/src/graphics/render/EntitiesRenderer.cpp index 9cbc82dcf..70b51e8b0 100644 --- a/src/graphics/render/EntitiesRenderer.cpp +++ b/src/graphics/render/EntitiesRenderer.cpp @@ -5,6 +5,7 @@ #include "graphics/core/DrawContext.hpp" #include "graphics/core/LineBatch.hpp" #include "maths/FrustumCulling.hpp" +#include "maths/util.hpp" #include "objects/Entities.hpp" #include "objects/Entity.hpp" #include "objects/EntityDef.hpp" @@ -46,10 +47,12 @@ static bool check_frustum( const Frustum& frustum, const Transform& transform, const Rigidbody& rigidbody, - const rigging::Skeleton& skeleton + const rigging::Skeleton& skeleton, + const glm::ivec3& origin ) { + glm::vec3 pos = util::to_local(transform.pos, origin); glm::vec3 ext = calc_extent(transform, rigidbody, skeleton); - return frustum.isBoxVisible(transform.pos - ext, transform.pos + ext); + return frustum.isBoxVisible(pos - ext, pos + ext); } EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities) @@ -57,8 +60,12 @@ EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities) } void EntitiesRenderer::render( - ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity + ModelBatch& batch, + const glm::ivec3& origin, + const Frustum* frustum, + entityid_t fpsEntity ) { + batch.setLightsOffset(origin); for (const auto& [uid, entity] : entities.getEntities()) { if (!entity->getSkeleton() || uid == fpsEntity) { continue; @@ -73,12 +80,17 @@ void EntitiesRenderer::render( if (rigConfig == nullptr) { continue; } - if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { + if (frustum && + !check_frustum(*frustum, transform, rigidbody, skeleton, origin)) { if (!skeleton.boundsDirty || !skeleton.visible) { continue; } - rigConfig->updateBounds(assets, skeleton, transform.rot, pos, size); - if (!check_frustum(*frustum, transform, rigidbody, skeleton)) { + rigConfig->updateBounds( + assets, skeleton, transform.rot, pos, size, origin + ); + if (!check_frustum( + *frustum, transform, rigidbody, skeleton, origin + )) { continue; } } @@ -90,6 +102,7 @@ void EntitiesRenderer::render( transform.rot, pos, size, + origin, def.translucent ); } @@ -97,6 +110,7 @@ void EntitiesRenderer::render( void EntitiesRenderer::renderDebug( LineBatch& batch, + const glm::ivec3& origin, const Frustum* frustum, const DrawContext& pctx, entityid_t fpsEntity @@ -113,20 +127,27 @@ void EntitiesRenderer::renderDebug( const auto& rigidbody = entity->getRigidbody(); const auto& skeleton = *entity->getSkeleton(); const auto& hitbox = rigidbody.hitbox; - if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { + if (frustum && + !check_frustum( + *frustum, transform, rigidbody, skeleton, origin + )) { continue; } batch.box( - hitbox.position, hitbox.getHalfSize() * 2.0f, glm::vec4(1.0f) + util::to_local(hitbox.position, origin), + hitbox.getHalfSize() * 2.0f, + glm::vec4(1.0f) ); glm::vec3 ext = calc_extent(transform, rigidbody, skeleton); batch.box( - transform.pos, ext * 2.0f, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f) + util::to_local(transform.pos, origin), + ext * 2.0f, + glm::vec4(0.0f, 0.0f, 1.0f, 1.0f) ); for (auto& sensor : rigidbody.sensors) { if (sensor.type != SensorType::AABB) continue; batch.box( - sensor.calculated.aabb.center(), + util::to_local(sensor.calculated.aabb.center(), origin), sensor.calculated.aabb.size(), glm::vec4(1.0f, 1.0f, 0.0f, 1.0f) ); @@ -149,7 +170,10 @@ void EntitiesRenderer::renderDebug( if (config == nullptr) { continue; } - if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { + if (frustum && + !check_frustum( + *frustum, transform, rigidbody, skeleton, origin + )) { continue; } auto bone = config->getRoot(); @@ -159,7 +183,7 @@ void EntitiesRenderer::renderDebug( } void EntitiesRenderer::updateCulling( - const Frustum* frustum, entityid_t fpsEntity + const glm::ivec3& origin, const Frustum* frustum, entityid_t fpsEntity ) { for (const auto& [uid, entity] : entities.getEntities()) { if (!entity->getSkeleton()) { @@ -171,7 +195,11 @@ void EntitiesRenderer::updateCulling( continue; } skeleton.culled = !check_frustum( - *frustum, entity->getTransform(), entity->getRigidbody(), skeleton + *frustum, + entity->getTransform(), + entity->getRigidbody(), + skeleton, + origin ); } } diff --git a/src/graphics/render/EntitiesRenderer.hpp b/src/graphics/render/EntitiesRenderer.hpp index 8a91ad3ce..045c7be09 100644 --- a/src/graphics/render/EntitiesRenderer.hpp +++ b/src/graphics/render/EntitiesRenderer.hpp @@ -2,6 +2,8 @@ #include "typedefs.hpp" +#include + class Assets; class DrawContext; class Entities; @@ -16,15 +18,21 @@ public: EntitiesRenderer(const Assets& assets, Entities& entities); void render( - ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity + ModelBatch& batch, + const glm::ivec3& origin, + const Frustum* frustum, + entityid_t fpsEntity ); void renderDebug( LineBatch& batch, + const glm::ivec3& origin, const Frustum* frustum, const DrawContext& ctx, entityid_t fpsEntity ); - void updateCulling(const Frustum* frustum, entityid_t fpsEntity); + void updateCulling( + const glm::ivec3& origin, const Frustum* frustum, entityid_t fpsEntity + ); }; diff --git a/src/graphics/render/HandsRenderer.cpp b/src/graphics/render/HandsRenderer.cpp index 27e43a078..c3c790ae6 100644 --- a/src/graphics/render/HandsRenderer.cpp +++ b/src/graphics/render/HandsRenderer.cpp @@ -33,7 +33,8 @@ void HandsRenderer::render(const Camera& camera) { ModelLightingMode::SOLID, glm::mat3(1.0f), glm::vec3(), - glm::vec3(1.0f) + glm::vec3(1.0f), + glm::ivec3() ); modelBatch.render(); diff --git a/src/graphics/render/MainBatch.cpp b/src/graphics/render/MainBatch.cpp index 70d4af6f7..f6d983e61 100644 --- a/src/graphics/render/MainBatch.cpp +++ b/src/graphics/render/MainBatch.cpp @@ -63,11 +63,11 @@ void MainBatch::prepare(int vertices) { } glm::vec4 MainBatch::sampleLight( - const glm::vec3 &pos, const Chunks &chunks, bool backlight + const glm::dvec3 &pos, const Chunks &chunks, bool backlight ) { light_t light = chunks.getLight( std::floor(pos.x), - std::floor(std::min(CHUNK_H - 1.0f, pos.y)), + std::floor(std::min(CHUNK_H - 1.0, pos.y)), std::floor(pos.z)); light_t minIntensity = backlight ? 1 : 0; return { diff --git a/src/graphics/render/MainBatch.hpp b/src/graphics/render/MainBatch.hpp index d51b2d05b..b5cc4ca7f 100644 --- a/src/graphics/render/MainBatch.hpp +++ b/src/graphics/render/MainBatch.hpp @@ -46,7 +46,7 @@ public: void flush(); static glm::vec4 sampleLight( - const glm::vec3& pos, const Chunks& chunks, bool backlight + const glm::dvec3& pos, const Chunks& chunks, bool backlight ); inline void vertex( diff --git a/src/graphics/render/ModelBatch.cpp b/src/graphics/render/ModelBatch.cpp index 958f2bc0d..5de723b3d 100644 --- a/src/graphics/render/ModelBatch.cpp +++ b/src/graphics/render/ModelBatch.cpp @@ -106,8 +106,8 @@ void ModelBatch::draw( auto& queue = translucent || tint.a < 1.0f ? translucentEntries : entries; const auto& gpuModel = upload(model); - glm::vec3 lightSamplePos = - glm::vec3(matrix[3]) + lightsOffset + lightSampleOffset; + glm::dvec3 lightSamplePos = + glm::dvec3(matrix[3]) + lightsOffset + glm::dvec3(lightSampleOffset); for (size_t i = 0; i < model->meshes.size(); i++) { const auto& mesh = model->meshes[i]; if (mesh.vertices.empty()) { @@ -219,6 +219,6 @@ void ModelBatch::renderTranslucent(const glm::vec3& cameraPosition) { finishFrame(); } -void ModelBatch::setLightsOffset(const glm::vec3& offset) { +void ModelBatch::setLightsOffset(const glm::dvec3& offset) { lightsOffset = offset; } diff --git a/src/graphics/render/ModelBatch.hpp b/src/graphics/render/ModelBatch.hpp index d75131c43..57536ba6c 100644 --- a/src/graphics/render/ModelBatch.hpp +++ b/src/graphics/render/ModelBatch.hpp @@ -50,13 +50,13 @@ public: void renderTranslucent(const glm::vec3& cameraPosition); - void setLightsOffset(const glm::vec3& offset); + void setLightsOffset(const glm::dvec3& offset); private: const Assets& assets; const Chunks& chunks; const EngineSettings& settings; - glm::vec3 lightsOffset {}; + glm::dvec3 lightsOffset {}; struct Vertex { glm::vec3 coord; @@ -103,7 +103,7 @@ private: struct DrawEntry { const Texture* texture; const Mesh* mesh; - glm::vec3 lightSamplePos; + glm::dvec3 lightSamplePos; bool shading; Instance instance; }; diff --git a/src/graphics/render/ParticlesRenderer.cpp b/src/graphics/render/ParticlesRenderer.cpp index ea449479c..d283389e0 100644 --- a/src/graphics/render/ParticlesRenderer.cpp +++ b/src/graphics/render/ParticlesRenderer.cpp @@ -154,7 +154,7 @@ void ParticlesRenderer::renderParticle( camera.front * rotatedUp.z; } batch->quad( - particle.position, + util::to_local(particle.position, camera.getOrigin()), localRight, localUp, -camera.front, diff --git a/src/graphics/render/PrecipitationRenderer.cpp b/src/graphics/render/PrecipitationRenderer.cpp index 6b2735d54..40d5ff9bb 100644 --- a/src/graphics/render/PrecipitationRenderer.cpp +++ b/src/graphics/render/PrecipitationRenderer.cpp @@ -67,7 +67,7 @@ static constexpr float K = 21.41149; static constexpr glm::ivec2 FACE_SIZE {1, 16}; static UVRegion calc_uv( - const glm::vec3& pos, + const glm::ivec3& pos, const glm::vec3& right, float timer, const WeatherPreset& weather @@ -84,8 +84,10 @@ static UVRegion calc_uv( } random.setSeed(uz); float hspeed = (random.randFloat() * 2.0f - 1.0f) * weather.fall.hspeed; - float u1 = ux * scale + timer * hspeed * -m; - float v1 = timer * weather.fall.vspeed + pos.y * scale + uz * K; + float u1 = + glm::fract(ux * static_cast(scale)) + timer * hspeed * -m; + float v1 = timer * weather.fall.vspeed + pos.y * scale + + glm::fract(uz * static_cast(K)); return {u1, v1, u1 + m * scale, v1 + FACE_SIZE.y * scale}; } @@ -104,6 +106,8 @@ void PrecipitationRenderer::render( int y = glm::floor(camera.position.y); int z = glm::floor(camera.position.z); + const glm::ivec3 origin = camera.getOrigin(); + util::CentredMatrix heights; heights.setCenter(x, z); for (int z = heights.beginY(); z < heights.endY(); z++) { @@ -135,17 +139,16 @@ void PrecipitationRenderer::render( for (int lx = -radius; lx <= radius; lx++) { for (int lz = depth; lz > 0; lz--) { // Position calculations - glm::vec3 pos = face.right * static_cast(lx) + - face.front * static_cast(lz); - pos += glm::vec3(x, 0, z); + glm::ivec3 pos = + glm::ivec3(face.right) * lx + glm::ivec3(face.front) * lz; + pos += glm::ivec3(x, 0, z); pos.y = glm::max(y - FACE_SIZE.y / 2, heights.at(pos.x, pos.z)) + FACE_SIZE.y / 2 + 1; - pos += glm::vec3(0.5f, 0.0f, 0.5f); // Draw batch->quad( - pos, + glm::vec3(pos - origin) + glm::vec3(0.5f, 0.0f, 0.5f), face.right, {0, 1, 0}, glm::cross(glm::vec3(0, 1, 0), face.right), diff --git a/src/graphics/render/TextsRenderer.cpp b/src/graphics/render/TextsRenderer.cpp index 8c3afb6e3..2cd0cc575 100644 --- a/src/graphics/render/TextsRenderer.cpp +++ b/src/graphics/render/TextsRenderer.cpp @@ -44,7 +44,10 @@ void TextsRenderer::renderNote( } } - if (util::distance2(pos, camera.position) > + pos = util::to_local(pos, camera.getOrigin()); + const glm::vec3 cameraPos = camera.getLocalPosition(); + + if (util::distance2(pos, cameraPos) > util::sqr(preset.renderDistance / camera.zoom)) { return; } @@ -70,7 +73,7 @@ void TextsRenderer::renderNote( int height = font.getLineHeight(); if (preset.displayMode == NoteDisplayMode::Y_FREE_BILLBOARD || preset.displayMode == NoteDisplayMode::XY_FREE_BILLBOARD) { - xvec = camera.position - pos; + xvec = cameraPos - pos; xvec.y = 0; std::swap(xvec.x, xvec.z); xvec.z *= -1; @@ -80,9 +83,7 @@ void TextsRenderer::renderNote( } float scale = (1.0f - preset.perspective) * - glm::pow( - glm::distance(camera.position, pos), 1.0f - preset.perspective - ); + glm::pow(glm::distance(cameraPos, pos), 1.0f - preset.perspective); xvec *= 1.0f + scale; yvec *= 1.0f + scale; } @@ -91,7 +92,7 @@ void TextsRenderer::renderNote( float scale = 1.0f; if (glm::abs(preset.perspective) > 0.0001f) { float scale2 = - scale / (glm::distance(camera.position, pos) * camera.zoom * + scale / (glm::distance(cameraPos, pos) * camera.zoom * glm::sqrt(glm::tan(camera.getFov() * 0.5f))); scale = scale2 * preset.perspective + scale * (1.0f - preset.perspective); diff --git a/src/graphics/render/WorldRenderer.cpp b/src/graphics/render/WorldRenderer.cpp index 54d5b3b2b..9c1639c7a 100644 --- a/src/graphics/render/WorldRenderer.cpp +++ b/src/graphics/render/WorldRenderer.cpp @@ -42,6 +42,7 @@ #include "items/ItemStack.hpp" #include "logic/PlayerController.hpp" #include "maths/FrustumCulling.hpp" +#include "maths/util.hpp" #include "maths/voxmaths.hpp" #include "objects/Entities.hpp" #include "objects/Player.hpp" @@ -213,7 +214,7 @@ static void setup_camera(Shader& shader, const Camera& camera) { shader.uniformMatrix("u_model", glm::mat4(1.0f)); shader.uniformMatrix("u_proj", camera.getProjection()); shader.uniformMatrix("u_view", camera.getView()); - shader.uniform3f("u_cameraPos", camera.position); + shader.uniform3f("u_cameraPos", camera.getLocalPosition()); } void WorldRenderer::setupWorldShader( @@ -226,7 +227,7 @@ void WorldRenderer::setupWorldShader( setup_camera(shader, camera); setup_weather(shader, weather); - shadowMapping->setup(shader, weather); + shadowMapping->setup(shader, camera, weather); shader.uniform1f("u_timer", timer); shader.uniform1f("u_gamma", settings.graphics.gamma.get()); @@ -283,6 +284,7 @@ void WorldRenderer::renderOpaque( setup_entity_pass(modelShader, {0.5f, true, false, false, 1.0f}); entitiesRenderer->render( *modelBatch, + camera.getOrigin(), culling ? frustumCulling.get() : nullptr, player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0 @@ -297,7 +299,7 @@ void WorldRenderer::renderOpaque( setupWorldShader(mainShader, camera, settings, fogFactor); chunksRenderer->drawChunks(camera, mainShader); - blockWraps->draw(ctx); + blockWraps->draw(ctx, camera); if (level.environment.sky.clouds) { int cloudsQuality = settings.graphics.cloudsQuality.get(); @@ -315,13 +317,14 @@ void WorldRenderer::renderOpaque( } } -void WorldRenderer::renderBlockSelection() { +void WorldRenderer::renderBlockSelection(const Camera& camera) { const auto& selection = player.selection; auto indices = level.content.getIndices(); blockid_t id = selection.vox.id; auto& block = indices->blocks.require(id); + const glm::ivec3 origin = camera.getOrigin(); const glm::ivec3 pos = player.selection.position; - const glm::vec3 point = selection.hitPosition; + const glm::vec3 point = util::to_local(selection.hitPosition, origin); const glm::vec3 norm = selection.normal; const auto& hitboxes = block.getHitboxes( @@ -330,7 +333,7 @@ void WorldRenderer::renderBlockSelection() { lineBatch->lineWidth(2.0f); for (auto& hitbox : hitboxes) { - const glm::vec3 center = glm::vec3(pos) + hitbox.center(); + const glm::vec3 center = glm::vec3(pos - origin) + hitbox.center(); const glm::vec3 size = hitbox.size(); lineBatch->box( center, size + glm::vec3(0.01), glm::vec4(0.f, 0.f, 0.f, 1.0f) @@ -350,13 +353,16 @@ void WorldRenderer::renderInWorldLines( linesShader.use(); linesShader.uniformMatrix("u_projview", camera.getProjView()); if (player.selection.vox.id != BLOCK_VOID) { - renderBlockSelection(); + renderBlockSelection(camera); } if (debug && showEntitiesDebug) { auto ctx = pctx.sub(lineBatch.get()); bool culling = engine.getSettings().graphics.frustumCulling.get(); entitiesRenderer->renderDebug( - *lineBatch, culling ? frustumCulling.get() : nullptr, ctx, + *lineBatch, + camera.getOrigin(), + culling ? frustumCulling.get() : nullptr, + ctx, player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0 ); } @@ -368,6 +374,7 @@ void WorldRenderer::updateEntitiesCulling(const Camera& camera) { frustumCulling->update(camera.getProjView()); } entitiesRenderer->updateCulling( + camera.getOrigin(), culling ? frustumCulling.get() : nullptr, player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0 @@ -587,7 +594,7 @@ void WorldRenderer::renderTranslucency( auto& shader = assets.require("model"); setupWorldShader(shader, camera, settings, fogFactor); setup_entity_pass(shader, {0.002f, false, true, true, 1.0f}); - modelBatch->renderTranslucent(camera.position); + modelBatch->renderTranslucent(camera.getLocalPosition()); } { auto lctx = ctx.sub(); diff --git a/src/graphics/render/WorldRenderer.hpp b/src/graphics/render/WorldRenderer.hpp index c302a4819..20a8688e4 100644 --- a/src/graphics/render/WorldRenderer.hpp +++ b/src/graphics/render/WorldRenderer.hpp @@ -91,7 +91,7 @@ private: bool dirtySettings = true; /// @brief Render block selection lines - void renderBlockSelection(); + void renderBlockSelection(const Camera& camera); /// @brief Render lines (selection and debug) /// @param camera active camera diff --git a/src/maths/util.hpp b/src/maths/util.hpp index c35450719..ae5107a98 100644 --- a/src/maths/util.hpp +++ b/src/maths/util.hpp @@ -17,6 +17,10 @@ namespace util { constexpr inline float EPSILON = 1e-6f; + inline glm::vec3 to_local(const glm::vec3& pos, const glm::ivec3& origin) { + return glm::dvec3(pos) - glm::dvec3(origin); + } + class PseudoRandom { uint32_t seed; diff --git a/src/window/Camera.cpp b/src/window/Camera.cpp index a8b2e6431..bb88e1279 100644 --- a/src/window/Camera.cpp +++ b/src/window/Camera.cpp @@ -3,6 +3,8 @@ #include #include +inline constexpr double ORIGIN_STEP = 1024.0; + Camera::Camera(glm::vec3 position, float fov) : fov(fov), position(position) { updateVectors(); } @@ -40,10 +42,22 @@ glm::mat4 Camera::getProjection() const { } } +glm::ivec3 Camera::getOrigin() const { + return glm::ivec3( + std::round(position.x / ORIGIN_STEP) * ORIGIN_STEP, + 0, + std::round(position.z / ORIGIN_STEP) * ORIGIN_STEP + ); +} + +glm::vec3 Camera::getLocalPosition() const { + return glm::dvec3(position) - glm::dvec3(getOrigin()); +} + glm::mat4 Camera::getView(bool pos) const { glm::mat4 view = glm::lookAt(glm::vec3(0.0f), front, up); if (pos) { - view = glm::translate(view, -position); + view = glm::translate(view, -getLocalPosition()); } return view; } diff --git a/src/window/Camera.hpp b/src/window/Camera.hpp index 677e0ede7..040721bbc 100644 --- a/src/window/Camera.hpp +++ b/src/window/Camera.hpp @@ -32,6 +32,11 @@ public: void updateVectors(); void rotate(float x, float y, float z); + /// @brief Get origin of the rendering coordinate system: an integer point + /// near the camera, getView() is relative to it + glm::ivec3 getOrigin() const; + glm::vec3 getLocalPosition() const; + glm::mat4 getProjection() const; glm::mat4 getView(bool position = true) const; glm::mat4 getProjView(bool position = true) const; diff --git a/test/window/Camera.cpp b/test/window/Camera.cpp index 51c80b14e..0015bc93d 100644 --- a/test/window/Camera.cpp +++ b/test/window/Camera.cpp @@ -29,3 +29,24 @@ TEST(Camera, ViewRotationFarFromOrigin) { } } } + +TEST(Camera, ViewRelativeToOrigin) { + for (float coord : {0.0f, 500.0f, -1e5f, 1e6f, 3e7f}) { + Camera camera(glm::vec3(coord, 64.0f, -coord), 1.0f); + camera.rotate(glm::radians(-20.0f), glm::radians(35.0f), 0.0f); + + glm::dvec3 origin = camera.getOrigin(); + glm::vec3 local = camera.getLocalPosition(); + EXPECT_LE(glm::abs(local.x), 512.0f) << "at " << coord; + EXPECT_LE(glm::abs(local.z), 512.0f) << "at " << coord; + EXPECT_EQ(glm::dvec3(camera.position), origin + glm::dvec3(local)); + + glm::dvec3 point = + glm::dvec3(camera.position) + glm::dvec3(camera.front) * 10.0; + glm::vec4 viewPoint = + camera.getView() * glm::vec4(glm::vec3(point - origin), 1.0f); + EXPECT_NEAR(viewPoint.x, 0.0f, 1e-3f) << "at " << coord; + EXPECT_NEAR(viewPoint.y, 0.0f, 1e-3f) << "at " << coord; + EXPECT_NEAR(viewPoint.z, -10.0f, 1e-3f) << "at " << coord; + } +} From ad69663b2e96b45c261fe466a64614f0f9c4a890 Mon Sep 17 00:00:00 2001 From: ostermine Date: Thu, 12 Nov 2026 00:58:10 +0300 Subject: [PATCH 3/8] use double precision for camera position and ray casts A float position has a step of 6 cm at 1M blocks and of 2 m at 30M: the camera moved by jumps and rays started not where the camera is. worldvec3 (glm::dvec3) is the type of a position in the world. Camera::position, the start and the end of block and entity ray casts and the hit position of the player selection use it. Lua numbers are doubles already, so cameras.set_pos/get_pos, block.raycast, entities.raycast and world.raycast only stop rounding to float. Entities::rayCast intersects a hitbox in the coordinates relative to its position instead of a float AABB in the world space. --- src/graphics/core/Shadows.cpp | 12 +++++------ src/graphics/render/DebugLinesRenderer.cpp | 2 +- src/graphics/render/Decorator.cpp | 4 ++-- src/logic/PlayerController.cpp | 14 ++++++------- src/logic/scripting/lua/libs/libblock.cpp | 6 +++--- src/logic/scripting/lua/libs/libcamera.cpp | 10 +++++---- src/logic/scripting/lua/libs/libentity.cpp | 17 +++++++-------- src/maths/util.hpp | 6 ++++-- src/objects/Entities.cpp | 8 ++++++-- src/objects/Entities.hpp | 2 +- src/objects/Player.hpp | 2 +- src/typedefs.hpp | 4 ++++ src/voxels/Chunks.cpp | 20 +++++++++--------- src/voxels/Chunks.hpp | 8 ++++---- src/voxels/blocks_agent.cpp | 24 +++++++++++----------- src/voxels/blocks_agent.hpp | 8 ++++---- src/window/Camera.cpp | 4 ++-- src/window/Camera.hpp | 6 ++++-- 18 files changed, 86 insertions(+), 71 deletions(-) diff --git a/src/graphics/core/Shadows.cpp b/src/graphics/core/Shadows.cpp index 240471fbf..abf4beea0 100644 --- a/src/graphics/core/Shadows.cpp +++ b/src/graphics/core/Shadows.cpp @@ -180,10 +180,10 @@ void Shadows::generateShadowsMap( float shadowMapScale = 0.32f / (1 << glm::max(0, quality)) * scale; float shadowMapSize = resolution * shadowMapScale; - glm::vec3 basePos = glm::floor(camera.position / 4.0f) * 4.0f; - glm::vec3 prevPos = shadowCamera.position; + worldvec3 basePos = glm::floor(camera.position / 4.0) * 4.0; + worldvec3 prevPos = shadowCamera.position; shadowCamera = Camera( - glm::distance2(prevPos, basePos) > 25.0f ? basePos : prevPos, + glm::distance2(prevPos, basePos) > 25.0 ? basePos : prevPos, shadowMapSize ); shadowCamera.near = 0.1f; @@ -206,9 +206,9 @@ void Shadows::generateShadowsMap( glm::radians(0.0f) ); - shadowCamera.position -= shadowCamera.front * 500.0f; - shadowCamera.position += shadowCamera.up * 0.0f; - shadowCamera.position += camera.front * 0.0f; + shadowCamera.position -= worldvec3(shadowCamera.front * 500.0f); + shadowCamera.position += worldvec3(shadowCamera.up * 0.0f); + shadowCamera.position += worldvec3(camera.front * 0.0f); auto view = shadowCamera.getView(); diff --git a/src/graphics/render/DebugLinesRenderer.cpp b/src/graphics/render/DebugLinesRenderer.cpp index d5056fc6f..1ea817761 100644 --- a/src/graphics/render/DebugLinesRenderer.cpp +++ b/src/graphics/render/DebugLinesRenderer.cpp @@ -118,7 +118,7 @@ void DebugLinesRenderer::render( if (showChunkBorders) { linesShader.uniformMatrix("u_projview", camera.getProjView()); - glm::vec3 coord = camera.position; + worldvec3 coord = camera.position; if (coord.x < 0) coord.x--; if (coord.z < 0) coord.z--; int cx = floordiv(static_cast(coord.x), CHUNK_W); diff --git a/src/graphics/render/Decorator.cpp b/src/graphics/render/Decorator.cpp index dfe86b289..f94dc20cc 100644 --- a/src/graphics/render/Decorator.cpp +++ b/src/graphics/render/Decorator.cpp @@ -120,7 +120,7 @@ void Decorator::updateAcoustics(const Camera& camera) { glm::vec3 dir = { r * std::cos(phi), r * std::sin(phi), z }; dir = glm::normalize(dir); - glm::vec3 end; + worldvec3 end; glm::ivec3 norm; glm::ivec3 iend; blocks_agent::RaycastSettings raycast {}; @@ -128,7 +128,7 @@ void Decorator::updateAcoustics(const Camera& camera) { if (vox == nullptr) { continue; } - auto distance = glm::distance(start, end); + float distance = glm::distance(start, end); if (distance >= length * 0.98f) { continue; } diff --git a/src/logic/PlayerController.cpp b/src/logic/PlayerController.cpp index 9d515d533..e75370ce5 100644 --- a/src/logic/PlayerController.cpp +++ b/src/logic/PlayerController.cpp @@ -200,7 +200,7 @@ void CameraControl::update( refreshPosition(); auto castRay = [](Player& player, Camera& camera, const glm::vec3& front) - -> glm::vec3 { + -> worldvec3 { auto blockEnd = player.chunks->rayCastToObstacle(camera.position, front, 3.0f); Entities::RaycastSettings raycast {}; @@ -212,7 +212,7 @@ void CameraControl::update( ); if (entityRay.has_value() && entityRay->distance < glm::distance(camera.position, blockEnd)) { - return (camera.position + front * entityRay->distance); + return camera.position + worldvec3(front * entityRay->distance); } else { return blockEnd; } @@ -220,14 +220,14 @@ void CameraControl::update( camera->updateVectors(); if (player.currentCamera == spCamera) { - spCamera->position = - castRay(player, *camera, camera->front) - 0.4f * camera->front; + spCamera->position = castRay(player, *camera, camera->front) - + worldvec3(0.4f * camera->front); spCamera->dir = -camera->dir; spCamera->front = -camera->front; spCamera->right = -camera->right; } else if (player.currentCamera == tpCamera) { tpCamera->position = castRay(player, *camera, camera->front * -1.0f) + - 0.4f * camera->front; + worldvec3(0.4f * camera->front); tpCamera->dir = camera->dir; tpCamera->front = camera->front; tpCamera->right = camera->right; @@ -366,7 +366,7 @@ voxel* PlayerController::updateSelection(float maxDistance) { auto camera = player.fpCamera.get(); auto& selection = player.selection; - glm::vec3 end; + worldvec3 end; glm::ivec3 iend; glm::ivec3 norm; voxel* vox = chunks.rayCast( @@ -393,7 +393,7 @@ voxel* PlayerController::updateSelection(float maxDistance) { )) { selection.entity = result->entity; selection.hitPosition = - camera->position + camera->front * result->distance; + camera->position + worldvec3(camera->front * result->distance); selection.position = selection.hitPosition; selection.actualPosition = selection.position; selection.normal = result->normal; diff --git a/src/logic/scripting/lua/libs/libblock.cpp b/src/logic/scripting/lua/libs/libblock.cpp index 6958d811d..aff5af7c5 100644 --- a/src/logic/scripting/lua/libs/libblock.cpp +++ b/src/logic/scripting/lua/libs/libblock.cpp @@ -548,7 +548,7 @@ static int l_destruct(lua::State* L) { static int l_raycast(lua::State* L) { const auto& level = require_level(); - auto start = lua::tovec<3>(L, 1); + auto start = lua::tovec<3, double>(L, 1); auto dir = lua::tovec<3>(L, 2); auto maxDistance = lua::tonumber(L, 3); @@ -576,7 +576,7 @@ static int l_raycast(lua::State* L) { if (luaStackSize >= 6) { raycast.includeNonSelectable = lua::toboolean(L, 6); } - glm::vec3 end; + worldvec3 end; glm::ivec3 normal; glm::ivec3 iend; @@ -589,7 +589,7 @@ static int l_raycast(lua::State* L) { lua::createtable(L, 0, 5); } - lua::pushvec3(L, end); + lua::pushvec(L, end); lua::setfield(L, "endpoint"); lua::pushvec3(L, normal); diff --git a/src/logic/scripting/lua/libs/libcamera.cpp b/src/logic/scripting/lua/libs/libcamera.cpp index c45d2740a..7bd2bb339 100644 --- a/src/logic/scripting/lua/libs/libcamera.cpp +++ b/src/logic/scripting/lua/libs/libcamera.cpp @@ -47,11 +47,11 @@ static int l_name(lua::State* L) { } static int getter_pos(lua::State* L, const Camera& camera) { - return lua::pushvec3(L, camera.position); + return lua::pushvec(L, camera.position); } static void setter_pos(lua::State* L, Camera& camera, int idx) { - camera.position = lua::tovec<3>(L, idx); + camera.position = lua::tovec<3, double>(L, idx); } static int getter_rot(lua::State* L, const Camera& camera) { @@ -104,9 +104,11 @@ static int getter_up(lua::State* L, const Camera& camera) { static int l_look_at(lua::State* L) { size_t index = static_cast(lua::tointeger(L, 1)); auto& camera = *require_level().cameras.at(index); - auto center = lua::tovec<3>(L, 2); + auto center = lua::tovec<3, double>(L, 2); auto matrix = glm::inverse( - glm::lookAt(glm::vec3(), center - camera.position, glm::vec3(0, 1, 0)) + glm::lookAt( + glm::vec3(), glm::vec3(center - camera.position), glm::vec3(0, 1, 0) + ) ); if (lua::isnumber(L, 3)) { matrix = glm::mat4_cast(glm::slerp( diff --git a/src/logic/scripting/lua/libs/libentity.cpp b/src/logic/scripting/lua/libs/libentity.cpp index 02e66991b..96e26f2f8 100644 --- a/src/logic/scripting/lua/libs/libentity.cpp +++ b/src/logic/scripting/lua/libs/libentity.cpp @@ -160,9 +160,9 @@ static int l_push_ray( lua::State* L, const std::optional& ray, blockid_t block, - const glm::vec3& start, + const worldvec3& start, const glm::vec3& dir, - const glm::vec3& end, + const worldvec3& end, const glm::ivec3& iend, const glm::ivec3& normal ) { @@ -175,7 +175,7 @@ static int l_push_ray( lua::createtable(L, 0, 6); } - lua::pushvec3(L, ray ? (start + dir * ray->distance) : end); + lua::pushvec(L, ray ? (start + worldvec3(dir * ray->distance)) : end); lua::setfield(L, "endpoint"); lua::pushvec3(L, ray ? ray->normal : normal); @@ -202,14 +202,14 @@ static int l_push_ray( static int l_raycast( lua::State* L, - const glm::vec3& start, + const worldvec3& start, const glm::vec3& dir, float maxDistance, const blocks_agent::RaycastSettings& voxelRaycast, const Entities::RaycastSettings& entityRaycast, bool entities ) { - glm::vec3 end; + worldvec3 end; glm::ivec3 normal; glm::ivec3 iend; @@ -276,7 +276,8 @@ static int l_world_raycast(lua::State* L) { std::set filteredBlocks {}; std::set filteredEntities {}; - glm::vec3 start, dir; + worldvec3 start; + glm::vec3 dir; float maxDistance; bool entities = true; @@ -285,7 +286,7 @@ static int l_world_raycast(lua::State* L) { } lua::requirefield(L, "start", 1); - start = lua::tovec3(L, -1); + start = lua::tovec<3, double>(L, -1); lua::requirefield(L, "dir", 1); dir = lua::tovec3(L, -1); @@ -341,7 +342,7 @@ static int l_raycast(lua::State* L) { std::set filteredBlocks {}; const int luaStackSize = lua::gettop(L); - glm::vec3 start = lua::tovec<3>(L, 1); + worldvec3 start = lua::tovec<3, double>(L, 1); glm::vec3 dir = lua::tovec<3>(L, 2); float maxDistance = lua::tonumber(L, 3); diff --git a/src/maths/util.hpp b/src/maths/util.hpp index ae5107a98..5738cfb27 100644 --- a/src/maths/util.hpp +++ b/src/maths/util.hpp @@ -1,5 +1,7 @@ #pragma once +#include "typedefs.hpp" + #include #include @@ -17,8 +19,8 @@ namespace util { constexpr inline float EPSILON = 1e-6f; - inline glm::vec3 to_local(const glm::vec3& pos, const glm::ivec3& origin) { - return glm::dvec3(pos) - glm::dvec3(origin); + inline glm::vec3 to_local(const worldvec3& pos, const glm::ivec3& origin) { + return glm::vec3(pos - worldvec3(origin)); } class PseudoRandom { diff --git a/src/objects/Entities.cpp b/src/objects/Entities.cpp index d02ede8d8..68b08cbb3 100644 --- a/src/objects/Entities.cpp +++ b/src/objects/Entities.cpp @@ -159,7 +159,7 @@ void Entities::loadEntity(const dv::value& map, Entity& entity) { } std::optional Entities::rayCast( - glm::vec3 start, + worldvec3 start, glm::vec3 dir, float maxDistance, const RaycastSettings& settings @@ -187,7 +187,11 @@ std::optional Entities::rayCast( glm::ivec3 normal; double distance; if (ray.intersectAABB( - glm::vec3(), hitbox.getAABB(), maxDistance, normal, distance + hitbox.position, + AABB(-hitbox.halfsize, hitbox.halfsize), + maxDistance, + normal, + distance ) > RayRelation::None) { foundUID = eid.uid; foundNormal = normal; diff --git a/src/objects/Entities.hpp b/src/objects/Entities.hpp index c92aa990f..f6810c13d 100644 --- a/src/objects/Entities.hpp +++ b/src/objects/Entities.hpp @@ -84,7 +84,7 @@ public: /// @param maxDistance Max ray length /// @return An optional structure containing entity, normal and distance std::optional rayCast( - glm::vec3 start, + worldvec3 start, glm::vec3 dir, float maxDistance, const RaycastSettings& settings diff --git a/src/objects/Player.hpp b/src/objects/Player.hpp index 57e7cb4b2..13eedb180 100644 --- a/src/objects/Player.hpp +++ b/src/objects/Player.hpp @@ -38,7 +38,7 @@ struct CursorSelection { glm::ivec3 position {}; glm::ivec3 actualPosition {}; glm::ivec3 normal {}; - glm::vec3 hitPosition; + worldvec3 hitPosition; entityid_t entity = ENTITY_NONE; }; diff --git a/src/typedefs.hpp b/src/typedefs.hpp index 6984a943f..004cb0ca3 100644 --- a/src/typedefs.hpp +++ b/src/typedefs.hpp @@ -2,6 +2,7 @@ #include #include +#include using scriptenv = std::shared_ptr; @@ -12,6 +13,9 @@ using integer_t = int64_t; /// @brief dynamic floating-point type (64 bit floating point) using number_t = double; +/// @brief position in the world (64 bit floating point components) +using worldvec3 = glm::dvec3; + using uint = unsigned int; using u64id_t = uint64_t; diff --git a/src/voxels/Chunks.cpp b/src/voxels/Chunks.cpp index 60bac04d5..906aad91b 100644 --- a/src/voxels/Chunks.cpp +++ b/src/voxels/Chunks.cpp @@ -211,10 +211,10 @@ void Chunks::set( } voxel* Chunks::rayCast( - const glm::vec3& start, + const worldvec3& start, const glm::vec3& dir, float maxDist, - glm::vec3& end, + worldvec3& end, glm::ivec3& norm, glm::ivec3& iend, const blocks_agent::RaycastSettings& settings @@ -224,12 +224,12 @@ voxel* Chunks::rayCast( ); } -glm::vec3 Chunks::rayCastToObstacle( - const glm::vec3& start, const glm::vec3& dir, float maxDist +worldvec3 Chunks::rayCastToObstacle( + const worldvec3& start, const glm::vec3& dir, float maxDist ) const { - const float px = start.x; - const float py = start.y; - const float pz = start.z; + const double px = start.x; + const double py = start.y; + const double pz = start.z; float dx = dir.x; float dy = dir.y; @@ -286,11 +286,11 @@ glm::vec3 Chunks::rayCastToObstacle( norm, distance ) > RayRelation::None) { - return start + (dir * glm::vec3(distance)); + return start + worldvec3(dir) * distance; } } } else { - return glm::vec3(px + t * dx, py + t * dy, pz + t * dz); + return worldvec3(px + t * dx, py + t * dy, pz + t * dz); } } } @@ -316,7 +316,7 @@ glm::vec3 Chunks::rayCastToObstacle( } } } - return glm::vec3(px + maxDist * dx, py + maxDist * dy, pz + maxDist * dz); + return worldvec3(px + maxDist * dx, py + maxDist * dy, pz + maxDist * dz); } void Chunks::setCenter(int32_t x, int32_t z) { diff --git a/src/voxels/Chunks.hpp b/src/voxels/Chunks.hpp index 8b94026cb..0d3f2072f 100644 --- a/src/voxels/Chunks.hpp +++ b/src/voxels/Chunks.hpp @@ -110,17 +110,17 @@ public: void setRotation(int32_t x, int32_t y, int32_t z, uint8_t rotation); voxel* rayCast( - const glm::vec3& start, + const worldvec3& start, const glm::vec3& dir, float maxLength, - glm::vec3& end, + worldvec3& end, glm::ivec3& norm, glm::ivec3& iend, const blocks_agent::RaycastSettings& settings ) const; - glm::vec3 rayCastToObstacle( - const glm::vec3& start, const glm::vec3& dir, float maxDist + worldvec3 rayCastToObstacle( + const worldvec3& start, const glm::vec3& dir, float maxDist ) const; const AABB* isObstacleAt(float x, float y, float z) const; diff --git a/src/voxels/blocks_agent.cpp b/src/voxels/blocks_agent.cpp index 360862c22..cd594e910 100644 --- a/src/voxels/blocks_agent.cpp +++ b/src/voxels/blocks_agent.cpp @@ -217,18 +217,18 @@ bool blocks_agent::set( template static inline voxel* raycast_blocks( const Storage& chunks, - const glm::vec3& start, + const worldvec3& start, const glm::vec3& dir, float maxDist, - glm::vec3& end, + worldvec3& end, glm::ivec3& norm, glm::ivec3& iend, const RaycastSettings& settings ) { const auto& blocks = chunks.getContentIndices().blocks; - float px = start.x; - float py = start.y; - float pz = start.z; + double px = start.x; + double py = start.y; + double pz = start.z; float dx = dir.x; float dy = dir.y; @@ -271,7 +271,7 @@ static inline voxel* raycast_blocks( (def.selectable || includeNonSelectable) && ((filter == nullptr || filter->find(def.rt.id) == filter->end()) == settings.blocksFilterExcludeMode)) { - end = start + t * dir; + end = start + worldvec3(t * dir); iend = {ix, iy, iz}; if (!def.rt.solid) { @@ -301,7 +301,7 @@ static inline voxel* raycast_blocks( hit = true; distance = boxDistance; norm = boxNorm; - end = start + (dir * glm::vec3(distance)); + end = start + worldvec3(dir) * distance; } } @@ -342,17 +342,17 @@ static inline voxel* raycast_blocks( } } iend = {ix, iy, iz}; - end = start + t * dir; + end = start + worldvec3(t * dir); norm = {0, 0, 0}; return nullptr; } voxel* blocks_agent::raycast( const Chunks& chunks, - const glm::vec3& start, + const worldvec3& start, const glm::vec3& dir, float maxDist, - glm::vec3& end, + worldvec3& end, glm::ivec3& norm, glm::ivec3& iend, const RaycastSettings& settings @@ -362,10 +362,10 @@ voxel* blocks_agent::raycast( voxel* blocks_agent::raycast( const GlobalChunks& chunks, - const glm::vec3& start, + const worldvec3& start, const glm::vec3& dir, float maxDist, - glm::vec3& end, + worldvec3& end, glm::ivec3& norm, glm::ivec3& iend, const RaycastSettings& settings diff --git a/src/voxels/blocks_agent.hpp b/src/voxels/blocks_agent.hpp index 810e4f1b4..a4e27a0b5 100644 --- a/src/voxels/blocks_agent.hpp +++ b/src/voxels/blocks_agent.hpp @@ -447,10 +447,10 @@ struct RaycastSettings { /// @return voxel pointer or nullptr voxel* raycast( const Chunks& chunks, - const glm::vec3& start, + const worldvec3& start, const glm::vec3& dir, float maxDist, - glm::vec3& end, + worldvec3& end, glm::ivec3& norm, glm::ivec3& iend, const RaycastSettings& settings @@ -469,10 +469,10 @@ voxel* raycast( /// @return voxel pointer or nullptr voxel* raycast( const GlobalChunks& chunks, - const glm::vec3& start, + const worldvec3& start, const glm::vec3& dir, float maxDist, - glm::vec3& end, + worldvec3& end, glm::ivec3& norm, glm::ivec3& iend, const RaycastSettings& settings diff --git a/src/window/Camera.cpp b/src/window/Camera.cpp index bb88e1279..b3ec0db2c 100644 --- a/src/window/Camera.cpp +++ b/src/window/Camera.cpp @@ -5,7 +5,7 @@ inline constexpr double ORIGIN_STEP = 1024.0; -Camera::Camera(glm::vec3 position, float fov) : fov(fov), position(position) { +Camera::Camera(worldvec3 position, float fov) : fov(fov), position(position) { updateVectors(); } @@ -51,7 +51,7 @@ glm::ivec3 Camera::getOrigin() const { } glm::vec3 Camera::getLocalPosition() const { - return glm::dvec3(position) - glm::dvec3(getOrigin()); + return glm::vec3(position - worldvec3(getOrigin())); } glm::mat4 Camera::getView(bool pos) const { diff --git a/src/window/Camera.hpp b/src/window/Camera.hpp index 040721bbc..900594b90 100644 --- a/src/window/Camera.hpp +++ b/src/window/Camera.hpp @@ -1,5 +1,7 @@ #pragma once +#include "typedefs.hpp" + #define GLM_FORCE_RADIANS #include @@ -12,7 +14,7 @@ public: glm::vec3 right {}; glm::vec3 dir {}; - glm::vec3 position {}; + worldvec3 position {}; float zoom = 1.0f; glm::mat4 rotation {1.0f}; @@ -27,7 +29,7 @@ public: Camera() { updateVectors(); } - Camera(glm::vec3 position, float fov); + Camera(worldvec3 position, float fov); void updateVectors(); void rotate(float x, float y, float z); From cb39ed464a9d5c9355b9d5905efec054a93b2339 Mon Sep 17 00:00:00 2001 From: ostermine Date: Thu, 12 Nov 2026 01:10:30 +0300 Subject: [PATCH 4/8] use double precision for positions of entities and players Transform::pos, Hitbox::position and Player::position were floats. At 65k blocks the float step is 8 mm, at 1M it is 6-12 cm, at 30M it is 2 m. The physics moves a body by 3 cm or less per substep and pushes it out of a wall by 10 cm or less: steps got rounded to the grid (the body changed its speed, then stopped), the AABB of a body was off by a float step and gave false collisions with the blocks around. Positions of bodies, entity transforms, players, spawn points and the skeleton position interpolation are worldvec3 now. Collisions are still calculated in floats, but in the coordinates relative to the block the body is in: the solver takes the origin, block lookups and hitboxes of other bodies are shifted by it, the result is added back in doubles. So the precision of the physics is the same anywhere in the world. A calculated sensor is stored relative to the position of its entity. Entities::getAllInside takes the corners in doubles, Entities::hasBlockingInside takes the origin of the AABB. The save format does not change: positions are written as numbers (float64) as before, saves are compatible in both directions. Lua functions keep their signatures, they only stop rounding to float. --- src/animation/rigging.cpp | 16 +-- src/animation/rigging.hpp | 8 +- src/data/dv_util.hpp | 4 +- src/frontend/debug_panel.cpp | 2 +- src/graphics/render/EntitiesRenderer.cpp | 6 +- src/logic/LevelController.cpp | 4 +- src/logic/PlayerController.cpp | 5 +- .../scripting/lua/libs/lib__transform.cpp | 6 +- src/logic/scripting/lua/libs/libentity.cpp | 10 +- src/logic/scripting/lua/libs/libplayer.cpp | 8 +- src/logic/scripting/lua/lua_util.hpp | 4 +- src/objects/Entities.cpp | 34 ++++-- src/objects/Entities.hpp | 8 +- src/objects/Entity.cpp | 4 +- src/objects/Entity.hpp | 4 +- src/objects/Player.cpp | 14 +-- src/objects/Player.hpp | 14 +-- src/objects/Players.cpp | 6 +- src/objects/Players.hpp | 6 +- src/objects/Transform.cpp | 4 +- src/objects/Transform.hpp | 12 ++- src/physics/BroadPhase.hpp | 4 +- src/physics/Hitbox.cpp | 2 +- src/physics/Hitbox.hpp | 16 +-- src/physics/SpatialGrid.cpp | 20 ++-- src/physics/SpatialGrid.hpp | 6 +- src/physics/collisions.cpp | 102 ++++++++++++------ src/physics/scheduling.hpp | 5 +- src/physics/sensors.cpp | 10 +- src/voxels/GlobalChunks.cpp | 8 +- src/voxels/GlobalChunks.hpp | 4 +- src/voxels/blocks_agent.hpp | 23 ++-- src/world/Level.cpp | 2 +- 33 files changed, 224 insertions(+), 157 deletions(-) diff --git a/src/animation/rigging.cpp b/src/animation/rigging.cpp index 522ff7b12..47996b426 100644 --- a/src/animation/rigging.cpp +++ b/src/animation/rigging.cpp @@ -160,22 +160,26 @@ static glm::mat4 build_matrix( void SkeletonConfig::update( Skeleton& skeleton, const glm::mat3& rotation, - const glm::vec3& position, + const worldvec3& position, const glm::vec3& scale, const glm::ivec3& origin ) const { - glm::vec3 pos = position; + worldvec3 pos = position; const auto& interpolation = skeleton.interpolation; if (interpolation.isEnabled() && interpolation.isRefreshed()) { pos = interpolation.getCurrent(); } - pos = util::to_local(pos, origin); glm::mat3 rot = rotation; const auto& rotationInterpolation = skeleton.rotationInterpolation; if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) { rot = glm::mat3_cast(rotationInterpolation.getCurrent()); } - update(0, skeleton, root.get(), build_matrix(rot, pos, scale)); + update( + 0, + skeleton, + root.get(), + build_matrix(rot, util::to_local(pos, origin), scale) + ); } static float max_component(const glm::vec3& v) { @@ -254,7 +258,7 @@ void SkeletonConfig::render( Skeleton& skeleton, ModelLightingMode lightingMode, const glm::mat3& rotation, - const glm::vec3& position, + const worldvec3& position, const glm::vec3& scale, const glm::ivec3& origin, bool translucent @@ -282,7 +286,7 @@ void SkeletonConfig::updateBounds( const Assets& assets, Skeleton& skeleton, const glm::mat3& rotation, - const glm::vec3& position, + const worldvec3& position, const glm::vec3& scale, const glm::ivec3& origin ) const { diff --git a/src/animation/rigging.hpp b/src/animation/rigging.hpp index 939e7eaf4..65d77eec7 100644 --- a/src/animation/rigging.hpp +++ b/src/animation/rigging.hpp @@ -104,7 +104,7 @@ namespace rigging { glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f}; std::vector boneTints; - util::VecInterpolation<3, float> interpolation {false}; + util::VecInterpolation<3, double> interpolation {false}; util::RotationInterpolation rotationInterpolation {false}; Skeleton(std::shared_ptr config); @@ -151,7 +151,7 @@ namespace rigging { void update( Skeleton& skeleton, const glm::mat3& rotation, - const glm::vec3& position, + const worldvec3& position, const glm::vec3& scale, const glm::ivec3& origin ) const; @@ -162,7 +162,7 @@ namespace rigging { Skeleton& skeleton, ModelLightingMode lightingMode, const glm::mat3& rotation, - const glm::vec3& position, + const worldvec3& position, const glm::vec3& scale, const glm::ivec3& origin, bool translucent = false @@ -172,7 +172,7 @@ namespace rigging { const Assets& assets, Skeleton& skeleton, const glm::mat3& rotation, - const glm::vec3& position, + const worldvec3& position, const glm::vec3& scale, const glm::ivec3& origin ) const; diff --git a/src/data/dv_util.hpp b/src/data/dv_util.hpp index ffec61dd2..cf48fed03 100644 --- a/src/data/dv_util.hpp +++ b/src/data/dv_util.hpp @@ -34,8 +34,8 @@ namespace dv { return values; } - template - void get_vec(const dv::value& list, glm::vec& vec) { + template + void get_vec(const dv::value& list, glm::vec& vec) { for (size_t i = 0; i < n; i++) { vec[i] = list[i].asNumber(); } diff --git a/src/frontend/debug_panel.cpp b/src/frontend/debug_panel.cpp index 2e10d55c4..5e79a7f6c 100644 --- a/src/frontend/debug_panel.cpp +++ b/src/frontend/debug_panel.cpp @@ -292,7 +292,7 @@ std::shared_ptr create_debug_panel( if (allowDebugCheats) { box->setTextConsumer([&player, ax](const std::wstring& text) { try { - glm::vec3 position = player.getPosition(); + worldvec3 position = player.getPosition(); position[ax] = std::stoi(text); player.teleport(position); } catch (std::exception& _) { diff --git a/src/graphics/render/EntitiesRenderer.cpp b/src/graphics/render/EntitiesRenderer.cpp index 70b51e8b0..a94f6ac16 100644 --- a/src/graphics/render/EntitiesRenderer.cpp +++ b/src/graphics/render/EntitiesRenderer.cpp @@ -147,7 +147,11 @@ void EntitiesRenderer::renderDebug( for (auto& sensor : rigidbody.sensors) { if (sensor.type != SensorType::AABB) continue; batch.box( - util::to_local(sensor.calculated.aabb.center(), origin), + util::to_local( + sensor.position + + worldvec3(sensor.calculated.aabb.center()), + origin + ), sensor.calculated.aabb.size(), glm::vec4(1.0f, 1.0f, 0.0f, 1.0f) ); diff --git a/src/logic/LevelController.cpp b/src/logic/LevelController.cpp index edc57959e..f064a9494 100644 --- a/src/logic/LevelController.cpp +++ b/src/logic/LevelController.cpp @@ -59,7 +59,7 @@ LevelController::LevelController( confirmed++; continue; } - glm::vec3 position = player->getPosition(); + const auto& position = player->getPosition(); player->chunks->configure( std::floor(position.x), std::floor(position.z), 1 ); @@ -82,7 +82,7 @@ void LevelController::update(float delta, bool pause) { continue; } player->rotationInterpolation.updateTimer(delta); - glm::vec3 position = player->getPosition(); + const auto& position = player->getPosition(); player->chunks->configure( glm::floor(position.x), glm::floor(position.z), diff --git a/src/logic/PlayerController.cpp b/src/logic/PlayerController.cpp index e75370ce5..81d6cc50a 100644 --- a/src/logic/PlayerController.cpp +++ b/src/logic/PlayerController.cpp @@ -54,7 +54,7 @@ CameraControl::CameraControl( } void CameraControl::refreshPosition() { - camera->position = player.getPosition() + offset; + camera->position = player.getPosition() + worldvec3(offset); } void CameraControl::refreshRotation() { @@ -461,8 +461,7 @@ void PlayerController::processRightClick( if (def.obstacle) { const auto& hitboxes = def.getHitboxes(state); for (const AABB& blockAABB : hitboxes) { - if (level.entities->hasBlockingInside(blockAABB.translated(coord) - )) { + if (level.entities->hasBlockingInside(coord, blockAABB)) { return; } } diff --git a/src/logic/scripting/lua/libs/lib__transform.cpp b/src/logic/scripting/lua/libs/lib__transform.cpp index dbe2d8c75..0f2c6345d 100644 --- a/src/logic/scripting/lua/libs/lib__transform.cpp +++ b/src/logic/scripting/lua/libs/lib__transform.cpp @@ -2,7 +2,7 @@ #include "maths/util.hpp" -static void check_valid(const glm::vec3& vec) { +static void check_valid(const worldvec3& vec) { if (util::is_nan_or_inf(vec)) { throw std::invalid_argument( "invalid vector: " + std::to_string(vec.x) + ", " + @@ -21,14 +21,14 @@ static void check_valid(const glm::mat3& vec) { static int l_get_pos(lua::State* L) { if (auto entity = get_entity(L, 1)) { - return lua::pushvec3(L, entity->getTransform().pos); + return lua::pushvec(L, entity->getTransform().pos); } return 0; } static int l_set_pos(lua::State* L) { if (auto entity = get_entity(L, 1)) { - auto vec = lua::tovec3(L, 2); + auto vec = lua::tovec<3, double>(L, 2); check_valid(vec); entity->getTransform().setPos(vec); entity->getRigidbody().hitbox.setPos(vec); diff --git a/src/logic/scripting/lua/libs/libentity.cpp b/src/logic/scripting/lua/libs/libentity.cpp index 96e26f2f8..cc889c023 100644 --- a/src/logic/scripting/lua/libs/libentity.cpp +++ b/src/logic/scripting/lua/libs/libentity.cpp @@ -72,7 +72,7 @@ static int l_spawn(lua::State* L) { auto level = controller->getLevel(); auto defname = lua::require_string(L, 1); auto& def = content->entities.require(defname); - auto pos = lua::tovec3(L, 2); + auto pos = lua::tovec<3, double>(L, 2); dv::value args = nullptr; if (lua::gettop(L) > 2) { args = lua::tovalue(L, 3); @@ -133,9 +133,9 @@ static int l_set_skeleton(lua::State* L) { } static int l_get_all_in_box(lua::State* L) { - auto pos = lua::tovec<3>(L, 1); - auto size = lua::tovec<3>(L, 2); - auto found = level->entities->getAllInside(AABB(pos, pos + size)); + auto pos = lua::tovec<3, double>(L, 1); + auto size = lua::tovec<3, double>(L, 2); + auto found = level->entities->getAllInside(pos, pos + size); lua::createtable(L, found.size(), 0); for (size_t i = 0; i < found.size(); i++) { lua::pushinteger(L, found[i]->getUID()); @@ -145,7 +145,7 @@ static int l_get_all_in_box(lua::State* L) { } static int l_get_all_in_radius(lua::State* L) { - auto pos = lua::tovec<3>(L, 1); + auto pos = lua::tovec<3, double>(L, 1); auto radius = lua::tonumber(L, 2); auto found = level->entities->getAllInRadius(pos, radius); lua::createtable(L, found.size(), 0); diff --git a/src/logic/scripting/lua/libs/libplayer.cpp b/src/logic/scripting/lua/libs/libplayer.cpp index 2ad96e7b2..e76d39007 100644 --- a/src/logic/scripting/lua/libs/libplayer.cpp +++ b/src/logic/scripting/lua/libs/libplayer.cpp @@ -47,7 +47,7 @@ static int l_set_pos(lua::State* L) { auto x = lua::tonumber(L, 2); auto y = lua::tonumber(L, 3); auto z = lua::tonumber(L, 4); - player->teleport(glm::vec3(x, y, z)); + player->teleport(worldvec3(x, y, z)); return 0; } @@ -256,7 +256,7 @@ static int l_set_spawnpoint(lua::State* L) { auto x = lua::tonumber(L, 2); auto y = lua::tonumber(L, 3); auto z = lua::tonumber(L, 4); - player->setSpawnPoint(glm::vec3(x, y, z)); + player->setSpawnPoint(worldvec3(x, y, z)); } return 0; } @@ -359,7 +359,7 @@ static int l_set_suspended(lua::State* L) { static int l_get_all_in_radius(lua::State* L) { auto& level = require_level(); - auto center = lua::tovec3(L, 1); + auto center = lua::tovec<3, double>(L, 1); auto radius = static_cast(lua::tonumber(L, 2)); auto players = level.players->getAllInRadius(center, radius); @@ -383,7 +383,7 @@ static int l_get_all(lua::State* L) { static int l_get_nearest(lua::State* L) { auto& level = require_level(); - auto position = lua::tovec3(L, 1); + auto position = lua::tovec<3, double>(L, 1); if (auto player = level.players->getNearest(position)) { lua::pushinteger(L, player->getId()); return 1; diff --git a/src/logic/scripting/lua/lua_util.hpp b/src/logic/scripting/lua/lua_util.hpp index 690fcb32d..8a716faaa 100644 --- a/src/logic/scripting/lua/lua_util.hpp +++ b/src/logic/scripting/lua/lua_util.hpp @@ -100,8 +100,8 @@ namespace lua { return 1; } - template - inline int pushvec_stack(lua::State* L, const glm::vec& vec) { + template + inline int pushvec_stack(lua::State* L, const glm::vec& vec) { for (int i = 0; i < n; i++) { pushnumber(L, vec[i]); } diff --git a/src/objects/Entities.cpp b/src/objects/Entities.cpp index 68b08cbb3..6a0392d18 100644 --- a/src/objects/Entities.cpp +++ b/src/objects/Entities.cpp @@ -43,7 +43,7 @@ Entity* Entities::get(entityid_t id) { entityid_t Entities::spawn( const EntityDef& def, - glm::vec3 position, + worldvec3 position, dv::value args, dv::value saved, entityid_t uid @@ -272,17 +272,22 @@ void Entities::updateSensors( sensor.nextEntered.clear(); switch (sensor.type) { - case SensorType::AABB: + case SensorType::AABB: { + glm::mat4 matrix = tsf.combined; + matrix[3] = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); sensor.calculated.aabb = sensor.params.aabb; - sensor.calculated.aabb.transform(tsf.combined); + sensor.calculated.aabb.transform(matrix); + sensor.position = tsf.displayPos; break; + } case SensorType::RADIUS: sensor.calculated.radial = glm::vec4( - body.hitbox.position.x, - body.hitbox.position.y, - body.hitbox.position.z, + 0.0f, + 0.0f, + 0.0f, sensor.params.radial.w * sensor.params.radial.w ); + sensor.position = body.hitbox.position; break; } sensors.push_back(&sensor); @@ -409,10 +414,10 @@ void Entities::update(float delta) { } } -bool Entities::hasBlockingInside(AABB aabb) { +bool Entities::hasBlockingInside(const worldvec3& origin, AABB aabb) { constexpr float eps = 0.05f; for (const auto& [uid, entity] : entities) { - AABB bodyAABB(entity->getRigidbody().hitbox.getAABB()); + AABB bodyAABB(entity->getRigidbody().hitbox.getAABB(origin)); bodyAABB.scale(glm::vec3(1.0f - eps)); if (entity->getID().def.blocking && aabb.intersects(bodyAABB)) { return true; @@ -421,17 +426,24 @@ bool Entities::hasBlockingInside(AABB aabb) { return false; } -std::vector Entities::getAllInside(AABB aabb) { +std::vector Entities::getAllInside( + const worldvec3& a, const worldvec3& b +) { + const worldvec3 min = glm::min(a, b); + const worldvec3 max = glm::max(a, b); std::vector collected; for (const auto& [uid, entity] : entities) { - if (!entity->getID().destroyFlag && aabb.contains(entity->getTransform().pos)) { + const auto& pos = entity->getTransform().pos; + if (!entity->getID().destroyFlag && + glm::all(glm::greaterThanEqual(pos, min)) && + glm::all(glm::lessThan(pos, max))) { collected.push_back(entity.get()); } } return collected; } -std::vector Entities::getAllInRadius(glm::vec3 center, float radius) { +std::vector Entities::getAllInRadius(worldvec3 center, float radius) { std::vector collected; for (const auto& [uid, entity] : entities) { if (glm::distance2(entity->getTransform().pos, center) <= radius * radius) { diff --git a/src/objects/Entities.hpp b/src/objects/Entities.hpp index f6810c13d..24767ce9e 100644 --- a/src/objects/Entities.hpp +++ b/src/objects/Entities.hpp @@ -52,7 +52,7 @@ public: entityid_t spawn( const EntityDef& def, - glm::vec3 position, + worldvec3 position, dv::value args = nullptr, dv::value saved = nullptr, entityid_t uid = 0 @@ -94,9 +94,9 @@ public: void loadEntity(const dv::value& map); void loadEntity(const dv::value& map, Entity& entity); void onSave(const Entity& entity); - bool hasBlockingInside(AABB aabb); - std::vector getAllInside(AABB aabb); - std::vector getAllInRadius(glm::vec3 center, float radius); + bool hasBlockingInside(const worldvec3& origin, AABB aabb); + std::vector getAllInside(const worldvec3& a, const worldvec3& b); + std::vector getAllInRadius(worldvec3 center, float radius); void despawn(entityid_t id); void despawn(const std::vector& entities); dv::value serialize(const std::vector& entities); diff --git a/src/objects/Entity.cpp b/src/objects/Entity.cpp index a5aa4eeec..b4b6e5f66 100644 --- a/src/objects/Entity.cpp +++ b/src/objects/Entity.cpp @@ -26,13 +26,13 @@ Entity::Entity( Entity::~Entity() = default; -void Entity::setInterpolatedPosition(const glm::vec3& position) { +void Entity::setInterpolatedPosition(const worldvec3& position) { if (skeleton) { skeleton->interpolation.refresh(position); } } -glm::vec3 Entity::getInterpolatedPosition() const { +worldvec3 Entity::getInterpolatedPosition() const { if (skeleton) { const auto& interpolation = skeleton->interpolation; if (interpolation.isEnabled() && interpolation.isRefreshed()) { diff --git a/src/objects/Entity.hpp b/src/objects/Entity.hpp index f7c7c3b5d..102756be4 100644 --- a/src/objects/Entity.hpp +++ b/src/objects/Entity.hpp @@ -104,9 +104,9 @@ public: void setPlayer(int64_t player); - void setInterpolatedPosition(const glm::vec3& position); + void setInterpolatedPosition(const worldvec3& position); - glm::vec3 getInterpolatedPosition() const; + worldvec3 getInterpolatedPosition() const; void setInterpolatedRotation(const glm::quat& rotation); diff --git a/src/objects/Player.cpp b/src/objects/Player.cpp index 760b14ef7..ee8ff4011 100644 --- a/src/objects/Player.cpp +++ b/src/objects/Player.cpp @@ -31,7 +31,7 @@ Player::Player( Level& level, int64_t id, const std::wstring& name, - glm::vec3 position, + worldvec3 position, float speed, std::shared_ptr inv, entityid_t eid @@ -121,7 +121,7 @@ void Player::postUpdate() { } } -void Player::teleport(glm::vec3 position) { +void Player::teleport(worldvec3 position) { this->position = position; if (auto entity = level.entities->get(eid)) { @@ -138,7 +138,7 @@ void Player::attemptToChooseSpawnpoint() { int minHeight = generatorDef.playerMinSpawnHeight; int maxHeight = generatorDef.playerMaxSpawnHeight; - glm::vec3 newpos {0.0f, random.randFloat() * (maxHeight - minHeight + 1) + minHeight, 0.0f}; + worldvec3 newpos {0.0f, random.randFloat() * (maxHeight - minHeight + 1) + minHeight, 0.0f}; double angle = random.randDouble() * glm::two_pi(); double radius = glm::sqrt(random.randDouble()); newpos.x += glm::cos(angle) * generatorDef.playerSpawnRadius * radius; @@ -154,7 +154,7 @@ void Player::attemptToChooseSpawnpoint() { headvox == nullptr || headvox->id != 0) { return; } - spawnpoint = newpos + glm::vec3(0.5f, 0.0f, 0.5f); + spawnpoint = newpos + worldvec3(0.5, 0.0, 0.5); teleport(spawnpoint); } @@ -259,11 +259,11 @@ const std::shared_ptr& Player::getInventory() const { return inventory; } -void Player::setSpawnPoint(glm::vec3 spawnpoint) { +void Player::setSpawnPoint(worldvec3 spawnpoint) { this->spawnpoint = spawnpoint; } -glm::vec3 Player::getSpawnPoint() const { +worldvec3 Player::getSpawnPoint() const { return spawnpoint; } @@ -324,7 +324,7 @@ void Player::deserialize(const dv::value& src) { dv::get_vec(rotarr, rotation); const auto& sparr = src["spawnpoint"]; - setSpawnPoint(glm::vec3( + setSpawnPoint(worldvec3( sparr[0].asNumber(), sparr[1].asNumber(), sparr[2].asNumber())); src.at("interaction-distance").get(interactionDistance); diff --git a/src/objects/Player.hpp b/src/objects/Player.hpp index 13eedb180..537e2816e 100644 --- a/src/objects/Player.hpp +++ b/src/objects/Player.hpp @@ -50,8 +50,8 @@ class Player : public Serializable { int chosenSlot; int hotbarSize; - glm::vec3 position; - glm::vec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")}; + worldvec3 position; + worldvec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")}; std::shared_ptr inventory; bool suspended = false; bool flight = false; @@ -81,14 +81,14 @@ public: Level& level, int64_t id, const std::wstring& name, - glm::vec3 position, + worldvec3 position, float speed, std::shared_ptr inv, entityid_t eid ); ~Player(); - void teleport(glm::vec3 position); + void teleport(worldvec3 position); void updateEntity(); void updateSelectedEntity(); void postUpdate(); @@ -134,7 +134,7 @@ public: const std::shared_ptr& getInventory() const; - const glm::vec3& getPosition() const { + const worldvec3& getPosition() const { return position; } @@ -142,8 +142,8 @@ public: Hitbox* getHitbox() const; - void setSpawnPoint(glm::vec3 point); - glm::vec3 getSpawnPoint() const; + void setSpawnPoint(worldvec3 point); + worldvec3 getSpawnPoint() const; glm::vec3 getRotation(bool interpolated=false) const; void setRotation(const glm::vec3& rotation); diff --git a/src/objects/Players.cpp b/src/objects/Players.cpp index 04c1aa2aa..47bdf1fd3 100644 --- a/src/objects/Players.cpp +++ b/src/objects/Players.cpp @@ -25,7 +25,7 @@ Player* Players::get(int64_t id) const { } std::vector Players::getAllInRadius( - const glm::vec3& center, float radius + const worldvec3& center, float radius ) const { std::vector foundPlayers; @@ -48,9 +48,9 @@ std::vector Players::getAll() const { return allPlayers; } -Player* Players::getNearest(const glm::vec3& position) const { +Player* Players::getNearest(const worldvec3& position) const { Player* nearest = nullptr; - float nearestDist2 = std::numeric_limits::max(); + double nearestDist2 = std::numeric_limits::max(); for (const auto& pair : players) { auto player = pair.second.get(); if (player->isSuspended()) { diff --git a/src/objects/Players.hpp b/src/objects/Players.hpp index 168033409..74c3d1240 100644 --- a/src/objects/Players.hpp +++ b/src/objects/Players.hpp @@ -36,9 +36,11 @@ public: void remove(int64_t id); - std::vector getAllInRadius(const glm::vec3& center, float radius) const; + std::vector getAllInRadius( + const worldvec3& center, float radius + ) const; std::vector getAll() const; - Player* getNearest(const glm::vec3& position) const; + Player* getNearest(const worldvec3& position) const; dv::value serialize() const override; diff --git a/src/objects/Transform.cpp b/src/objects/Transform.cpp index c398c48e7..5d5522825 100644 --- a/src/objects/Transform.cpp +++ b/src/objects/Transform.cpp @@ -11,7 +11,7 @@ static debug::Logger logger("entity-transform"); void Transform::refresh() { combined = glm::mat4(1.0f); - combined = glm::translate(combined, pos); + combined = glm::translate(combined, glm::vec3(pos)); combined = combined * glm::mat4(rot); combined = glm::scale(combined, size); displayPos = pos; @@ -37,7 +37,7 @@ void Transform::deserialize(const dv::value& root) { dv::get_mat(root, "rot", rot); } -bool Transform::checkValue(const glm::vec3& vector, std::string_view name) { +bool Transform::checkValue(const worldvec3& vector, std::string_view name) { if (util::is_nan_or_inf(vector)) { auto message = "invalid vector attempted set to " + std::string(name) + " : " + std::to_string(vector.x) + ", " + diff --git a/src/objects/Transform.hpp b/src/objects/Transform.hpp index 5cea5c83c..e27461f29 100644 --- a/src/objects/Transform.hpp +++ b/src/objects/Transform.hpp @@ -2,6 +2,8 @@ #define GLM_ENABLE_EXPERIMENTAL +#include "typedefs.hpp" + #include #include #include @@ -10,13 +12,13 @@ struct Transform { static inline constexpr float EPSILON = 1e-7f; - glm::vec3 pos; + worldvec3 pos; glm::vec3 size; glm::mat3 rot; glm::mat4 combined; bool dirty = true; - glm::vec3 displayPos {}; + worldvec3 displayPos {}; glm::vec3 displaySize {}; dv::value serialize() const; @@ -33,7 +35,7 @@ struct Transform { } inline void setSize(const glm::vec3& v) { - if (!checkValue(v, "size")) { + if (!checkValue(worldvec3(v), "size")) { return; } if (glm::distance2(displaySize, v) >= EPSILON) { @@ -42,7 +44,7 @@ struct Transform { size = v; } - inline void setPos(const glm::vec3& v) { + inline void setPos(const worldvec3& v) { if (!checkValue(v, "position")) { return; } @@ -52,6 +54,6 @@ struct Transform { pos = v; } - static bool checkValue(const glm::vec3& v, std::string_view name); + static bool checkValue(const worldvec3& v, std::string_view name); static bool checkValue(const glm::mat3& v, std::string_view name); }; diff --git a/src/physics/BroadPhase.hpp b/src/physics/BroadPhase.hpp index 7b9eabbc6..ec9c0a665 100644 --- a/src/physics/BroadPhase.hpp +++ b/src/physics/BroadPhase.hpp @@ -29,10 +29,10 @@ private: glm::vec3 gravity; SpatialGrid grid; std::vector> nearbySolids; - std::vector nearbyOrigins; + std::vector nearbyOrigins; std::vector nearbyBudgets; std::vector nearbyReaches; - std::vector solidOrigins; + std::vector solidOrigins; std::vector solidBudgets; std::vector candidates; std::vector solidStamps; diff --git a/src/physics/Hitbox.cpp b/src/physics/Hitbox.cpp index f49e0c2b8..cc206a399 100644 --- a/src/physics/Hitbox.cpp +++ b/src/physics/Hitbox.cpp @@ -1,7 +1,7 @@ #include "Hitbox.hpp" Hitbox::Hitbox( - entityid_t entity, BodyType type, glm::vec3 position, glm::vec3 halfsize + entityid_t entity, BodyType type, worldvec3 position, glm::vec3 halfsize ) : entity(entity), type(type), diff --git a/src/physics/Hitbox.hpp b/src/physics/Hitbox.hpp index 01e657236..e1a9a4904 100644 --- a/src/physics/Hitbox.hpp +++ b/src/physics/Hitbox.hpp @@ -19,7 +19,7 @@ enum class SensorType { union SensorParams { AABB aabb; - glm::vec4 radial; // x,y,z calculated entity coords + w - radius + glm::vec4 radial; // w - radius constexpr SensorParams() : aabb() { } @@ -38,6 +38,7 @@ struct Sensor { std::set nextEntered; sensorcallback enterCallback; sensorcallback exitCallback; + worldvec3 position {}; }; enum class BodyType { @@ -53,7 +54,7 @@ VC_ENUM_END struct Hitbox { entityid_t entity; BodyType type; - glm::vec3 position; + worldvec3 position; glm::vec3 halfsize; glm::vec3 velocity; glm::vec3 scale {1.0f, 1.0f, 1.0f}; @@ -70,7 +71,7 @@ struct Hitbox { std::string groundMaterial; glm::vec3 groundVelocity {}; - glm::vec3 prevPosition {}; + worldvec3 prevPosition {}; glm::vec3 prevVelocity {}; bool prevGrounded = false; float substepTime = 0.0f; @@ -80,18 +81,19 @@ struct Hitbox { static inline constexpr float TELEPORT_THRESOLD_SQR = 0.5f; Hitbox( - entityid_t entity, BodyType type, glm::vec3 position, glm::vec3 halfsize + entityid_t entity, BodyType type, worldvec3 position, glm::vec3 halfsize ); - AABB getAABB() const { - return AABB(position - halfsize, position + halfsize); + AABB getAABB(const worldvec3& origin) const { + glm::vec3 pos(position - origin); + return AABB(pos - halfsize, pos + halfsize); } glm::vec3 getHalfSize() const { return halfsize * scale; } - void setPos(const glm::vec3& vec) { + void setPos(const worldvec3& vec) { position = vec; if (glm::distance2(position, prevPosition) >= TELEPORT_THRESOLD_SQR) { prevPosition = vec; diff --git a/src/physics/SpatialGrid.cpp b/src/physics/SpatialGrid.cpp index ad686500f..23cf49035 100644 --- a/src/physics/SpatialGrid.cpp +++ b/src/physics/SpatialGrid.cpp @@ -2,9 +2,9 @@ #include -inline constexpr float GRID_CELL_SIZE = 4.0f; -inline constexpr float GRID_PADDING = 0.01f; -inline constexpr float GRID_MAX_COORD = 1e9f; +inline constexpr double GRID_CELL_SIZE = 4.0; +inline constexpr double GRID_PADDING = 0.01; +inline constexpr double GRID_MAX_COORD = 1e9; inline constexpr int GRID_MAX_CELLS = 64; void SpatialGrid::clear() { @@ -13,7 +13,7 @@ void SpatialGrid::clear() { } void SpatialGrid::insert( - uint id, const glm::vec3& center, const glm::vec3& extents + uint id, const worldvec3& center, const glm::vec3& extents ) { glm::ivec2 min, max; if (!calcRange(center, extents, min, max)) { @@ -37,20 +37,20 @@ uint64_t SpatialGrid::calcKey(int x, int z) { } bool SpatialGrid::calcRange( - const glm::vec3& center, + const worldvec3& center, const glm::vec3& extents, glm::ivec2& min, glm::ivec2& max ) { - glm::vec2 c(center.x, center.z); - glm::vec2 e = glm::vec2(extents.x, extents.z) + GRID_PADDING; - glm::vec2 a = glm::floor((c - e) / GRID_CELL_SIZE); - glm::vec2 b = glm::floor((c + e) / GRID_CELL_SIZE); + glm::dvec2 c(center.x, center.z); + glm::dvec2 e = glm::dvec2(extents.x, extents.z) + GRID_PADDING; + glm::dvec2 a = glm::floor((c - e) / GRID_CELL_SIZE); + glm::dvec2 b = glm::floor((c + e) / GRID_CELL_SIZE); if (!(glm::abs(a.x) < GRID_MAX_COORD && glm::abs(a.y) < GRID_MAX_COORD && glm::abs(b.x) < GRID_MAX_COORD && glm::abs(b.y) < GRID_MAX_COORD)) { return false; } - if ((b.x - a.x + 1.0f) * (b.y - a.y + 1.0f) > GRID_MAX_CELLS) { + if ((b.x - a.x + 1.0) * (b.y - a.y + 1.0) > GRID_MAX_CELLS) { return false; } min = glm::ivec2(a); diff --git a/src/physics/SpatialGrid.hpp b/src/physics/SpatialGrid.hpp index d35e94786..d48cc5c93 100644 --- a/src/physics/SpatialGrid.hpp +++ b/src/physics/SpatialGrid.hpp @@ -10,13 +10,13 @@ class SpatialGrid { public: void clear(); - void insert(uint id, const glm::vec3& center, const glm::vec3& extents); + void insert(uint id, const worldvec3& center, const glm::vec3& extents); void build(); template bool query( - const glm::vec3& center, const glm::vec3& extents, const Func& func + const worldvec3& center, const glm::vec3& extents, const Func& func ) const { glm::ivec2 min, max; if (!calcRange(center, extents, min, max)) { @@ -46,7 +46,7 @@ private: static uint64_t calcKey(int x, int z); static bool calcRange( - const glm::vec3& center, + const worldvec3& center, const glm::vec3& extents, glm::ivec2& min, glm::ivec2& max diff --git a/src/physics/collisions.cpp b/src/physics/collisions.cpp index bac65c9e5..84936e3d3 100644 --- a/src/physics/collisions.cpp +++ b/src/physics/collisions.cpp @@ -2,6 +2,7 @@ #include "scheduling.hpp" #include "maths/aabb.hpp" +#include "maths/util.hpp" #include "voxels/GlobalChunks.hpp" #define GLM_ENABLE_EXPERIMENTAL @@ -28,6 +29,7 @@ static glm::vec3 calc_collsion_velocity_result( static float calc_step_height( const GlobalChunks& chunks, const glm::vec3& pos, + const glm::ivec3& origin, const glm::vec3& half, float stepHeight ) { @@ -41,7 +43,9 @@ static float calc_step_height( float x = (pos.x - half.x) + ix; for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { float z = (pos.z - half.z) + iz; - if (chunks.isObstacleAt(x, pos.y + half.y + stepHeight, z, aabb)) { + if (chunks.isObstacleAt( + origin, x, pos.y + half.y + stepHeight, z, aabb + )) { return 0.0f; } } @@ -54,18 +58,20 @@ static float calc_step_height( template static void calc_collision( Hitbox& hitbox, + glm::vec3& pos, + const glm::ivec3& origin, const GlobalChunks& chunks, const std::vector& solidHitboxes, const glm::vec3& half, float stepHeight, uint wakeSubstep ) { - auto& pos = hitbox.position; auto& vel = hitbox.velocity; glm::vec3 offset(0.0f, stepHeight + E, 0.0f); for (auto box : solidHitboxes) { - if (glm::distance2(box->position, pos) < E) { + glm::vec3 boxpos = util::to_local(box->position, origin); + if (glm::distance2(boxpos, pos) < E) { continue; } auto boxhalf = box->getHalfSize(); @@ -77,12 +83,13 @@ static void calc_collision( aabb = aabb + offset; aabb.b.y -= stepHeight + E * 2; - if ((box->position[nx] - pos[nx]) * sign <= 0.0f || !box->getAABB().intersects(aabb)) { + if ((boxpos[nx] - pos[nx]) * sign <= 0.0f || + !box->getAABB(origin).intersects(aabb)) { continue; } - float newnegx = box->position[nx] - boxhalf[nx] - half[nx]; - float newposx = box->position[nx] + boxhalf[nx] + half[nx]; + float newnegx = boxpos[nx] - boxhalf[nx] - half[nx]; + float newposx = boxpos[nx] + boxhalf[nx] + half[nx]; float newx; if ((glm::abs(newnegx - pos[nx]) - glm::abs(newposx - pos[nx]))*sign < 0.0f) { newx = sign > 0 ? newnegx : newposx; @@ -116,7 +123,9 @@ static void calc_collision( aabb = aabb + offset; aabb.b.y -= stepHeight + E * 2; - if (const auto obstacle = chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) { + if (const auto obstacle = chunks.isObstacleAt( + origin, coord.x, coord.y, coord.z, aabb + )) { float newx = std::floor(coord[nx]) - half[nx] * sign + (sign > 0 ? obstacle->min() : obstacle->max())[nx]; if ((pos[nx] - newx) * sign > 0.0f && glm::abs(pos[nx] - newx) < MAX_FIX) { @@ -130,15 +139,19 @@ static void calc_collision( } static bool calc_collision_neg_y( - Hitbox& hitbox, const glm::vec3& half, const CollisionContext& ctx + Hitbox& hitbox, + glm::vec3& pos, + const glm::ivec3& origin, + const glm::vec3& half, + const CollisionContext& ctx ) { const auto& chunks = ctx.chunks; const auto& solids = ctx.solids; - auto& pos = hitbox.position; auto& vel = hitbox.velocity; for (auto box : solids) { - if (glm::distance2(box->position, pos) < E) { + glm::vec3 boxpos = util::to_local(box->position, origin); + if (glm::distance2(boxpos, pos) < E) { continue; } auto aabb = AABB(pos - half, pos + half); @@ -148,8 +161,8 @@ static bool calc_collision_neg_y( aabb.scale(scale); auto boxhalf = box->getHalfSize(); - if (box->position.y < pos.y && box->getAABB().intersects(aabb)) { - float newy = box->position.y + boxhalf.y + half.y; + if (boxpos.y < pos.y && box->getAABB(origin).intersects(aabb)) { + float newy = boxpos.y + boxhalf.y + half.y; if (pos.y < newy && glm::abs(pos.y - newy) < boxhalf.y) { pos.y = newy; } @@ -158,7 +171,8 @@ static bool calc_collision_neg_y( auto velB = calc_collsion_velocity_result(*box, hitbox); float boxdt = box->substepTime > 0.0f ? box->substepTime : ctx.dt; - hitbox.groundVelocity = (box->position - box->prevPosition) / boxdt; + hitbox.groundVelocity = + glm::vec3(box->position - box->prevPosition) / boxdt; if (vel.y < hitbox.groundVelocity.y) { vel.y = velA.y; push_body(*box, 1, velB.y, ctx.wakeSubstep); @@ -185,8 +199,9 @@ static bool calc_collision_neg_y( scale.z = 1.0f - E * 4.0f; aabb.scale(scale); - if (const auto obstacle = - chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) { + if (const auto obstacle = chunks.isObstacleAt( + origin, coord.x, coord.y, coord.z, aabb + )) { float newy = std::floor(coord.y) + half.y + obstacle->max().y; if (newy >= pos.y) { @@ -203,6 +218,8 @@ static bool calc_collision_neg_y( static void calc_collisions( Hitbox& hitbox, + glm::vec3& pos, + const glm::ivec3& origin, const glm::vec3& half, float stepHeight, const CollisionContext& ctx @@ -210,32 +227,31 @@ static void calc_collisions( const auto& chunks = ctx.chunks; const auto& solids = ctx.solids; uint wakeSubstep = ctx.wakeSubstep; - auto& pos = hitbox.position; auto& vel = hitbox.velocity; - stepHeight = calc_step_height(chunks, pos, half, stepHeight); + stepHeight = calc_step_height(chunks, pos, origin, half, stepHeight); auto prevPos = pos; calc_collision<0, 1, 2, -1>( - hitbox, chunks, solids, half, stepHeight, wakeSubstep + hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep ); calc_collision<0, 1, 2, 1>( - hitbox, chunks, solids, half, stepHeight, wakeSubstep + hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep ); float xpos = pos.x; pos.x = prevPos.x; calc_collision<2, 1, 0, -1>( - hitbox, chunks, solids, half, stepHeight, wakeSubstep + hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep ); calc_collision<2, 1, 0, 1>( - hitbox, chunks, solids, half, stepHeight, wakeSubstep + hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep ); pos.x = xpos; - if (calc_collision_neg_y(hitbox, half, ctx)) { + if (calc_collision_neg_y(hitbox, pos, origin, half, ctx)) { hitbox.grounded = true; } @@ -249,7 +265,7 @@ static void calc_collisions( for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { float z = (pos.z - half.z + E) + iz; float y = (pos.y + half.y + E) - E; - if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) { + if (auto aabb = chunks.isObstacleAt(origin, x, y, z, boxAABB)) { float bottom = std::floor(y) + aabb->min().y; float newy = bottom - half.y - E; if (pos.y >= newy && pos.y - half.y < bottom) { @@ -261,12 +277,13 @@ static void calc_collisions( } } for (auto box : solids) { - if (glm::distance2(box->position, pos) < E) { + glm::vec3 boxpos = util::to_local(box->position, origin); + if (glm::distance2(boxpos, pos) < E) { continue; } auto boxhalf = box->getHalfSize(); - if (box->position.y > pos.y && box->getAABB().intersects(boxAABB)) { - float newy = box->position.y - boxhalf.y - half.y; + if (boxpos.y > pos.y && box->getAABB(origin).intersects(boxAABB)) { + float newy = boxpos.y - boxhalf.y - half.y; if (pos.y > newy && glm::abs(pos.y - newy) < 0.5f) { pos.y = newy; } @@ -290,7 +307,7 @@ static void calc_collisions( for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { float z = (pos.z - half.z) + iz; float y = (pos.y - half.y + E) + E; - if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) { + if (auto aabb = chunks.isObstacleAt(origin, x, y, z, boxAABB)) { if (vel.y < 0.0f) { vel.y = 0.0f; } @@ -303,13 +320,14 @@ static void calc_collisions( } } for (auto box : solids) { - if (glm::distance2(box->position, pos) < E) { + glm::vec3 boxpos = util::to_local(box->position, origin); + if (glm::distance2(boxpos, pos) < E) { continue; } auto boxhalf = box->getHalfSize(); - if (box->getAABB().intersects(boxAABB)) { + if (box->getAABB(origin).intersects(boxAABB)) { vel.y = 0.0f; - float newy = box->position.y + boxhalf.y + half.y; + float newy = boxpos.y + boxhalf.y + half.y; if (std::abs(newy - pos.y) <= stepHeight + E * 4) { pos.y = newy; } @@ -318,12 +336,16 @@ static void calc_collisions( } } -void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) { +static void calc_local_substep( + Hitbox& hitbox, + glm::vec3& pos, + const glm::ivec3& origin, + const CollisionContext& ctx +) { const auto& chunks = ctx.chunks; const auto& solids = ctx.solids; const auto& gravity = ctx.gravity; float dt = ctx.dt; - auto& pos = hitbox.position; auto& vel = hitbox.velocity; auto initpos = pos; @@ -333,6 +355,8 @@ void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) { if (hitbox.type == BodyType::DYNAMIC) { calc_collisions( hitbox, + pos, + origin, half, (hitbox.prevGrounded && gravityScale > 0.0f) ? hitbox.stepHeight : 0.0f, @@ -361,17 +385,18 @@ void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) { float x = (pos.x - half.x + E) + ix; for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++){ float z = (pos.z - half.z + E) + iz; - if (chunks.isObstacleAt(x, y, z, boxAABB)){ + if (chunks.isObstacleAt(origin, x, y, z, boxAABB)) { hitbox.grounded = true; break; } } } for (auto box : solids) { - if (glm::distance2(box->position, pos) < E) { + glm::vec3 boxpos = util::to_local(box->position, origin); + if (glm::distance2(boxpos, pos) < E) { continue; } - if (box->position.y < pos.y && box->getAABB().intersects(boxAABB)) { + if (boxpos.y < pos.y && box->getAABB(origin).intersects(boxAABB)) { hitbox.grounded = true; break; } @@ -383,3 +408,10 @@ void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) { } hitbox.grounded = true; } + +void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) { + const glm::ivec3 origin = glm::floor(hitbox.position); + glm::vec3 pos = util::to_local(hitbox.position, origin); + calc_local_substep(hitbox, pos, origin, ctx); + hitbox.position = worldvec3(origin) + worldvec3(pos); +} diff --git a/src/physics/scheduling.hpp b/src/physics/scheduling.hpp index 1caf69ac5..e320feadd 100644 --- a/src/physics/scheduling.hpp +++ b/src/physics/scheduling.hpp @@ -13,8 +13,9 @@ namespace physics { ) { float n = static_cast(substeps); auto accel = gravity * box.gravityScale; - box.position += box.velocity * (dt * n) + - accel * (dt * dt * n * (n + 2.0f) * 0.5f); + box.position += worldvec3( + box.velocity * (dt * n) + accel * (dt * dt * n * (n + 2.0f) * 0.5f) + ); box.velocity += accel * (dt * n); } diff --git a/src/physics/sensors.cpp b/src/physics/sensors.cpp index 641d1c09b..c71880a84 100644 --- a/src/physics/sensors.cpp +++ b/src/physics/sensors.cpp @@ -3,8 +3,6 @@ void physics::update_sensors( Hitbox& hitbox, const std::vector& sensors ) { - auto aabb = hitbox.getAABB(); - for (size_t i = 0; i < sensors.size(); i++) { auto& sensor = *sensors[i]; if (sensor.entity == hitbox.entity) { @@ -13,12 +11,12 @@ void physics::update_sensors( bool triggered = false; switch (sensor.type) { case SensorType::AABB: - triggered = aabb.intersects(sensor.calculated.aabb); + triggered = hitbox.getAABB(sensor.position) + .intersects(sensor.calculated.aabb); break; case SensorType::RADIUS: - triggered = glm::distance2( - hitbox.position, glm::vec3(sensor.calculated.radial)) - < sensor.calculated.radial.w; + triggered = glm::distance2(hitbox.position, sensor.position) < + sensor.calculated.radial.w; break; } if (!triggered) { diff --git a/src/voxels/GlobalChunks.cpp b/src/voxels/GlobalChunks.cpp index c081a6a5b..d4bdd0100 100644 --- a/src/voxels/GlobalChunks.cpp +++ b/src/voxels/GlobalChunks.cpp @@ -191,7 +191,7 @@ void GlobalChunks::save(Chunk* chunk) { return; } AABB aabb = chunk->getAABB(); - auto entities = level.entities->getAllInside(aabb); + auto entities = level.entities->getAllInside(aabb.a, aabb.b); auto root = dv::object(); root["data"] = level.entities->serialize(entities); if (!entities.empty()) { @@ -214,6 +214,8 @@ void GlobalChunks::putChunk(std::shared_ptr chunk) { chunksMap[keyfrom(chunk->x, chunk->z)] = std::move(chunk); } -std::optional GlobalChunks::isObstacleAt(float x, float y, float z, const AABB& aabb) const { - return blocks_agent::is_obstacle_at(*this, x, y, z, aabb); +std::optional GlobalChunks::isObstacleAt( + const glm::ivec3& origin, float x, float y, float z, const AABB& aabb +) const { + return blocks_agent::is_obstacle_at(*this, origin, x, y, z, aabb); } diff --git a/src/voxels/GlobalChunks.hpp b/src/voxels/GlobalChunks.hpp index de62cbc58..81c7a3ab2 100644 --- a/src/voxels/GlobalChunks.hpp +++ b/src/voxels/GlobalChunks.hpp @@ -58,7 +58,9 @@ public: void putChunk(std::shared_ptr chunk); - std::optional isObstacleAt(float x, float y, float z, const AABB& aabb) const; + std::optional isObstacleAt( + const glm::ivec3& origin, float x, float y, float z, const AABB& aabb + ) const; inline Chunk* getChunk(int cx, int cz) const { const auto& found = chunksMap.find(keyfrom(cx, cz)); diff --git a/src/voxels/blocks_agent.hpp b/src/voxels/blocks_agent.hpp index a4e27a0b5..fe90d6c83 100644 --- a/src/voxels/blocks_agent.hpp +++ b/src/voxels/blocks_agent.hpp @@ -488,14 +488,20 @@ void get_voxels( template inline std::optional is_obstacle_at( - const Storage& chunks, float x, float y, float z, const AABB& aabb + const Storage& chunks, + const glm::ivec3& origin, + float x, + float y, + float z, + const AABB& aabb ) { int ix = std::floor(x); int iy = std::floor(y); int iz = std::floor(z); - voxel* v = get(chunks, ix, iy, iz); + glm::ivec3 point = origin + glm::ivec3(ix, iy, iz); + voxel* v = get(chunks, point.x, point.y, point.z); if (v == nullptr) { - if (iy >= CHUNK_H) { + if (point.y >= CHUNK_H) { return std::nullopt; } else { return AABB(); @@ -508,10 +514,9 @@ inline std::optional is_obstacle_at( glm::ivec3 offset {}; blockstate state = v->state; if (state.segment) { - glm::ivec3 point(ix, iy, iz); - auto origin = seek_origin(chunks, point, def, state); - offset = origin - point; - state = hitbox_state(chunks, origin, state); + auto blockOrigin = seek_origin(chunks, point, def, state); + offset = blockOrigin - point; + state = hitbox_state(chunks, blockOrigin, state); } const auto& boxes = def.getHitboxes(state); @@ -525,7 +530,9 @@ inline std::optional is_obstacle_at( template inline std::optional is_obstacle_at(const Storage& chunks, float x, float y, float z) { - return is_obstacle_at(chunks, x, y, z, AABB({x, y, z}, {x + 1, y + 1, z + 1})); + return is_obstacle_at( + chunks, {}, x, y, z, AABB({x, y, z}, {x + 1, y + 1, z + 1}) + ); } /// @brief Check block grounding diff --git a/src/world/Level.cpp b/src/world/Level.cpp index 308604ca9..71a3eac0e 100644 --- a/src/world/Level.cpp +++ b/src/world/Level.cpp @@ -64,7 +64,7 @@ Level::Level( chunks->setOnUnload([this](Chunk& chunk) { events->trigger(LevelEventType::CHUNK_UNLOAD, &chunk); AABB aabb = chunk.getAABB(); - entities->despawn(entities->getAllInside(aabb)); + entities->despawn(entities->getAllInside(aabb.a, aabb.b)); }); inventories = std::make_unique(*this); } From d012f0530b10232cd6ddf6380824b9cb49ba5525 Mon Sep 17 00:00:00 2001 From: ostermine Date: Thu, 12 Nov 2026 01:13:45 +0300 Subject: [PATCH 5/8] use double precision for particles, emitters and 3D texts Positions of particles, of static emitters and of text notes are worldvec3. gfx.particles, gfx.text3d, gfx.blockwraps, pathfinding and generation.create_fragment read positions from Lua as doubles: a float can not hold an odd block coordinate above 16.7M, the object went to a neighbour block. --- src/graphics/render/Decorator.cpp | 8 ++++---- src/graphics/render/Emitter.cpp | 10 +++++----- src/graphics/render/Emitter.hpp | 8 ++++---- src/graphics/render/ParticlesRenderer.cpp | 7 ++++--- src/graphics/render/TextNote.cpp | 6 +++--- src/graphics/render/TextNote.hpp | 8 ++++---- src/graphics/render/TextsRenderer.cpp | 6 +++--- src/logic/scripting/lua/libs/libblockwraps.cpp | 4 ++-- src/logic/scripting/lua/libs/libgeneration.cpp | 4 ++-- src/logic/scripting/lua/libs/libparticles.cpp | 8 ++++---- src/logic/scripting/lua/libs/libpathfinding.cpp | 8 ++++---- src/logic/scripting/lua/libs/libtext3d.cpp | 4 ++-- src/voxels/Chunks.cpp | 2 +- src/voxels/Chunks.hpp | 4 ++-- 14 files changed, 44 insertions(+), 43 deletions(-) diff --git a/src/graphics/render/Decorator.cpp b/src/graphics/render/Decorator.cpp index f94dc20cc..fd32b56ba 100644 --- a/src/graphics/render/Decorator.cpp +++ b/src/graphics/render/Decorator.cpp @@ -83,7 +83,7 @@ void Decorator::addParticles(const Block& def, const glm::ivec3& pos) { ); blockEmitters[pos] = renderer.particles->add(std::make_unique( level, - glm::vec3{pos.x + 0.5, pos.y + 0.5, pos.z + 0.5}, + worldvec3 {pos.x + 0.5, pos.y + 0.5, pos.z + 0.5}, *def.particles, treg.texture, treg.region, @@ -205,7 +205,7 @@ void Decorator::updateRandom( ); renderer.particles->add(std::make_unique( level, - glm::vec3 { + worldvec3 { pos.x + random.randFloat(), pos.y + 1.1, pos.z + random.randFloat()}, @@ -308,11 +308,11 @@ void Decorator::updateTextNotes() { renderer.texts->remove(textsIter->second); textsIter = playerTexts.erase(textsIter); } else { - glm::vec3 position = player->getPosition(); + worldvec3 position = player->getPosition(); if (auto entity = level.entities->get(player->getEntity())) { position = entity->getInterpolatedPosition(); } - note->setPosition(position + glm::vec3(0, 1, 0)); + note->setPosition(position + worldvec3(0, 1, 0)); if (note->getText() != player->getName()) { note->setText(player->getName()); } diff --git a/src/graphics/render/Emitter.cpp b/src/graphics/render/Emitter.cpp index aa817b354..7fe636192 100644 --- a/src/graphics/render/Emitter.cpp +++ b/src/graphics/render/Emitter.cpp @@ -14,7 +14,7 @@ Emitter::Emitter( const Level& level, - std::variant origin, + EmitterOrigin origin, ParticlesPreset preset, const Texture* texture, const UVRegion& region, @@ -50,15 +50,15 @@ static inline glm::vec3 generate_coord(ParticleSpawnShape shape) { void Emitter::update( float delta, - const glm::vec3& cameraPosition, + const worldvec3& cameraPosition, std::vector& particles ) { const float spawnInterval = preset.spawnInterval; if (count == 0 || (count == -1 && spawnInterval < FLT_EPSILON)) { return; } - glm::vec3 position {}; - if (auto staticPos = std::get_if(&origin)) { + worldvec3 position {}; + if (auto staticPos = std::get_if(&origin)) { position = *staticPos; } else if (auto entityId = std::get_if(&origin)) { if (auto entity = level.entities->get(*entityId)) { @@ -105,7 +105,7 @@ void Emitter::update( spawnOffset *= preset.spawnSpread; spawnOffset += preset.spawnOffset; - particle.position = position + spawnOffset; + particle.position = position + worldvec3(spawnOffset); particle.lifetime *= 1.0f - preset.lifetimeSpread * random.randFloat(); particle.velocity += glm::ballRand(1.0f) * preset.explosion; if (preset.randomSubUV < 1.0f) { diff --git a/src/graphics/render/Emitter.hpp b/src/graphics/render/Emitter.hpp index ce1ec8f47..61b1941df 100644 --- a/src/graphics/render/Emitter.hpp +++ b/src/graphics/render/Emitter.hpp @@ -20,7 +20,7 @@ struct Particle { /// @brief Some random integer for visuals configuration. int random; /// @brief Global position - glm::vec3 position; + worldvec3 position; /// @brief Linear velocity glm::vec3 velocity; /// @brief Remaining life time @@ -35,7 +35,7 @@ struct Particle { class Texture; -using EmitterOrigin = std::variant; +using EmitterOrigin = std::variant; class Emitter { const Level& level; @@ -61,7 +61,7 @@ public: Emitter( const Level& level, - std::variant origin, + EmitterOrigin origin, ParticlesPreset preset, const Texture* texture, const UVRegion& region, @@ -79,7 +79,7 @@ public: /// @param particles destination particles vector void update( float delta, - const glm::vec3& cameraPosition, + const worldvec3& cameraPosition, std::vector& particles ); diff --git a/src/graphics/render/ParticlesRenderer.cpp b/src/graphics/render/ParticlesRenderer.cpp index d283389e0..b5cf3b63c 100644 --- a/src/graphics/render/ParticlesRenderer.cpp +++ b/src/graphics/render/ParticlesRenderer.cpp @@ -38,10 +38,10 @@ static inline void update_particle( auto& angle = particle.angle; vel += delta * preset.acceleration; - if (preset.collision && chunks.isObstacleAt(pos + vel * delta)) { + if (preset.collision && chunks.isObstacleAt(pos + worldvec3(vel * delta))) { vel *= 0.0f; } - pos += vel * delta; + pos += worldvec3(vel * delta); angle += particle.angularVelocity * delta; particle.lifetime -= delta; } @@ -114,7 +114,8 @@ static inline glm::vec4 calc_lights( light = glm::max( light, MainBatch::sampleLight( - particle.position - size * glm::vec3(x, y, z), + particle.position - + worldvec3(size * glm::vec3(x, y, z)), chunks, backlight ) diff --git a/src/graphics/render/TextNote.cpp b/src/graphics/render/TextNote.cpp index 7c4797fd3..48881196d 100644 --- a/src/graphics/render/TextNote.cpp +++ b/src/graphics/render/TextNote.cpp @@ -1,6 +1,6 @@ #include "TextNote.hpp" -TextNote::TextNote(std::wstring text, NotePreset preset, glm::vec3 position) +TextNote::TextNote(std::wstring text, NotePreset preset, worldvec3 position) : text(std::move(text)), preset(std::move(preset)), position(std::move(position)) { @@ -30,11 +30,11 @@ void TextNote::updatePreset(const dv::value& data) { preset.deserialize(data); } -void TextNote::setPosition(const glm::vec3& position) { +void TextNote::setPosition(const worldvec3& position) { this->position = position; } -const glm::vec3& TextNote::getPosition() const { +const worldvec3& TextNote::getPosition() const { return position; } diff --git a/src/graphics/render/TextNote.hpp b/src/graphics/render/TextNote.hpp index 0fc8f4afd..c05d14465 100644 --- a/src/graphics/render/TextNote.hpp +++ b/src/graphics/render/TextNote.hpp @@ -7,13 +7,13 @@ class TextNote { std::wstring text; NotePreset preset; - glm::vec3 position; + worldvec3 position; entityid_t entity = ENTITY_NONE; glm::vec3 xAxis {1, 0, 0}; glm::vec3 yAxis {0, 1, 0}; public: - TextNote(std::wstring text, NotePreset preset, glm::vec3 position); + TextNote(std::wstring text, NotePreset preset, worldvec3 position); void setText(std::wstring_view text); void setEntity(entityid_t eid); @@ -25,8 +25,8 @@ public: void updatePreset(const dv::value& data); - void setPosition(const glm::vec3& position); - const glm::vec3& getPosition() const; + void setPosition(const worldvec3& position); + const worldvec3& getPosition() const; const glm::vec3& getAxisX() const; const glm::vec3& getAxisY() const; diff --git a/src/graphics/render/TextsRenderer.cpp b/src/graphics/render/TextsRenderer.cpp index 2cd0cc575..2b9c7b027 100644 --- a/src/graphics/render/TextsRenderer.cpp +++ b/src/graphics/render/TextsRenderer.cpp @@ -35,16 +35,16 @@ void TextsRenderer::renderNote( ) { const auto& text = note.getText(); const auto& preset = note.getPreset(); - auto pos = note.getPosition(); + auto worldPos = note.getPosition(); entityid_t eid = note.getEntity(); if (eid != ENTITY_NONE) { if (auto entity = level.entities->get(eid)) { - pos += entity->getTransform().displayPos; + worldPos += entity->getTransform().displayPos; } } - pos = util::to_local(pos, camera.getOrigin()); + glm::vec3 pos = util::to_local(worldPos, camera.getOrigin()); const glm::vec3 cameraPos = camera.getLocalPosition(); if (util::distance2(pos, cameraPos) > diff --git a/src/logic/scripting/lua/libs/libblockwraps.cpp b/src/logic/scripting/lua/libs/libblockwraps.cpp index a6eba3e8f..baa4ac17c 100644 --- a/src/logic/scripting/lua/libs/libblockwraps.cpp +++ b/src/logic/scripting/lua/libs/libblockwraps.cpp @@ -7,7 +7,7 @@ using namespace scripting; static int l_wrap(lua::State* L) { - auto position = lua::tovec3(L, 1); + auto position = lua::tovec<3, double>(L, 1); std::string texture = lua::require_string(L, 2); float emission = lua::isnumber(L, 3) ? lua::tonumber(L, 3) : 1.0f; glm::vec4 tint = @@ -31,7 +31,7 @@ static int l_unwrap(lua::State* L) { static int l_set_pos(lua::State* L) { if (auto wrapper = renderer->blockWraps->get(lua::tointeger(L, 1))) { - wrapper->position = lua::tovec3(L, 2); + wrapper->position = lua::tovec<3, double>(L, 2); } return 0; } diff --git a/src/logic/scripting/lua/libs/libgeneration.cpp b/src/logic/scripting/lua/libs/libgeneration.cpp index 2e872ec7c..218788330 100644 --- a/src/logic/scripting/lua/libs/libgeneration.cpp +++ b/src/logic/scripting/lua/libs/libgeneration.cpp @@ -24,8 +24,8 @@ static int l_save_fragment(lua::State* L) { } static int l_create_fragment(lua::State* L) { - auto pointA = lua::tovec<3>(L, 1); - auto pointB = lua::tovec<3>(L, 2); + auto pointA = lua::tovec<3, double>(L, 1); + auto pointB = lua::tovec<3, double>(L, 2); bool crop = lua::toboolean(L, 3); bool saveEntities = lua::toboolean(L, 4); diff --git a/src/logic/scripting/lua/libs/libparticles.cpp b/src/logic/scripting/lua/libs/libparticles.cpp index 563f2f2e0..f7c8cf68a 100644 --- a/src/logic/scripting/lua/libs/libparticles.cpp +++ b/src/logic/scripting/lua/libs/libparticles.cpp @@ -9,7 +9,7 @@ using namespace scripting; static int l_emit(lua::State* L) { EmitterOrigin origin; if (lua::istable(L, 1)) { - origin = lua::tovec3(L, 1); + origin = lua::tovec<3, double>(L, 1); } else { origin = static_cast(lua::tointeger(L, 1)); } @@ -47,8 +47,8 @@ static int l_get_origin(lua::State* L) { u64id_t id = lua::touinteger(L, 1); if (auto emitter = renderer->particles->getEmitter(id)) { const auto& origin = emitter->getOrigin(); - if (auto pos = std::get_if(&origin)) { - return lua::pushvec3(L, *pos); + if (auto pos = std::get_if(&origin)) { + return lua::pushvec(L, *pos); } else if (auto entityid = std::get_if(&origin)) { return lua::pushinteger(L, *entityid); } @@ -60,7 +60,7 @@ static int l_set_origin(lua::State* L) { u64id_t id = lua::touinteger(L, 1); if (auto emitter = renderer->particles->getEmitter(id)) { if (lua::istable(L, 2)) { - emitter->setOrigin(lua::tovec3(L, 2)); + emitter->setOrigin(lua::tovec<3, double>(L, 2)); } else { emitter->setOrigin(static_cast(lua::tointeger(L, 2))); } diff --git a/src/logic/scripting/lua/libs/libpathfinding.cpp b/src/logic/scripting/lua/libs/libpathfinding.cpp index d702633e3..55f5a3fc3 100644 --- a/src/logic/scripting/lua/libs/libpathfinding.cpp +++ b/src/logic/scripting/lua/libs/libpathfinding.cpp @@ -46,8 +46,8 @@ static int push_route(lua::State* L, const voxels::Route& route) { static int l_make_route(lua::State* L) { if (auto agent = get_agent(L)) { - auto start = lua::tovec3(L, 2); - auto target = lua::tovec3(L, 3); + auto start = lua::tovec<3, double>(L, 2); + auto target = lua::tovec<3, double>(L, 3); agent->state = {}; agent->start = glm::floor(start); agent->target = target; @@ -62,8 +62,8 @@ static int l_make_route(lua::State* L) { static int l_make_route_async(lua::State* L) { if (auto agent = get_agent(L)) { - auto start = lua::tovec3(L, 2); - auto target = lua::tovec3(L, 3); + auto start = lua::tovec<3, double>(L, 2); + auto target = lua::tovec<3, double>(L, 3); agent->state = {}; agent->start = glm::floor(start); agent->target = target; diff --git a/src/logic/scripting/lua/libs/libtext3d.cpp b/src/logic/scripting/lua/libs/libtext3d.cpp index 0c3957cce..90be4c23e 100644 --- a/src/logic/scripting/lua/libs/libtext3d.cpp +++ b/src/logic/scripting/lua/libs/libtext3d.cpp @@ -6,7 +6,7 @@ using namespace scripting; static int l_show(lua::State* L) { - auto position = lua::tovec3(L, 1); + auto position = lua::tovec<3, double>(L, 1); auto text = lua::require_wstring(L, 2); auto preset = lua::tovalue(L, 3); auto extension = lua::tovalue(L, 4); @@ -47,7 +47,7 @@ static int l_get_pos(lua::State* L) { } static int l_set_pos(lua::State* L) { if (auto note = renderer->texts->get(lua::tointeger(L, 1))) { - note->setPosition(lua::tovec3(L, 2)); + note->setPosition(lua::tovec<3, double>(L, 2)); } return 0; } diff --git a/src/voxels/Chunks.cpp b/src/voxels/Chunks.cpp index 906aad91b..04c946c4f 100644 --- a/src/voxels/Chunks.cpp +++ b/src/voxels/Chunks.cpp @@ -52,7 +52,7 @@ voxel& Chunks::require(int32_t x, int32_t y, int32_t z) const { return blocks_agent::require(*this, x, y, z); } -const AABB* Chunks::isObstacleAt(float x, float y, float z) const { +const AABB* Chunks::isObstacleAt(double x, double y, double z) const { int ix = std::floor(x); int iy = std::floor(y); int iz = std::floor(z); diff --git a/src/voxels/Chunks.hpp b/src/voxels/Chunks.hpp index 0d3f2072f..7e4f66a7a 100644 --- a/src/voxels/Chunks.hpp +++ b/src/voxels/Chunks.hpp @@ -123,9 +123,9 @@ public: const worldvec3& start, const glm::vec3& dir, float maxDist ) const; - const AABB* isObstacleAt(float x, float y, float z) const; + const AABB* isObstacleAt(double x, double y, double z) const; - const AABB* isObstacleAt(const glm::vec3& pos) const { + const AABB* isObstacleAt(const worldvec3& pos) const { return isObstacleAt(pos.x, pos.y, pos.z); } From 56ab3de5148081fb8510cd5166fbd6ff80da9528 Mon Sep 17 00:00:00 2001 From: ostermine Date: Thu, 12 Nov 2026 01:19:21 +0300 Subject: [PATCH 6/8] make audio positions relative to the listener OpenAL takes positions as floats. Positions of the listener and of the speakers were passed in the world space, so far from the world origin both were rounded to the float step (2 m at 30M blocks): a sound next to the player came from a wrong side and with a wrong volume. A speaker keeps its position as worldvec3, the listener stays in the OpenAL origin, and a source is placed at "speaker - listener". Sources are refreshed in the speaker update, once per frame. --- src/audio/AL/ALAudio.cpp | 20 ++++++++++++++----- src/audio/AL/ALAudio.hpp | 11 ++++++++--- src/audio/NoAudio.hpp | 2 +- src/audio/audio.cpp | 8 ++++---- src/audio/audio.hpp | 14 ++++++------- src/frontend/LevelFrontend.cpp | 4 ++-- src/logic/scripting/lua/libs/libaudio.cpp | 24 ++++------------------- 7 files changed, 41 insertions(+), 42 deletions(-) diff --git a/src/audio/AL/ALAudio.cpp b/src/audio/AL/ALAudio.cpp index 1aaeb8f1a..8458a2b4b 100644 --- a/src/audio/AL/ALAudio.cpp +++ b/src/audio/AL/ALAudio.cpp @@ -342,6 +342,7 @@ void ALSpeaker::update(const Channel* channel) { if (source == 0) return; float gain = this->volume * channel->getVolume(); AL_CHECK(alSourcef(source, AL_GAIN, gain)); + refreshPosition(); if (!paused) { if (isPaused() && !channel->isPaused()) { @@ -451,12 +452,18 @@ void ALSpeaker::setTime(duration_t time) { AL_CHECK(alSourcef(source, AL_SEC_OFFSET, static_cast(time))); } -void ALSpeaker::setPosition(glm::vec3 pos) { +void ALSpeaker::refreshPosition() { + glm::vec3 pos(relative ? position : position - al->listenerPosition); AL_CHECK(alSource3f(source, AL_POSITION, pos.x, pos.y, pos.z)); } -glm::vec3 ALSpeaker::getPosition() const { - return AL::getSource3f(source, AL_POSITION); +void ALSpeaker::setPosition(worldvec3 pos) { + position = pos; + refreshPosition(); +} + +worldvec3 ALSpeaker::getPosition() const { + return position; } void ALSpeaker::setVelocity(glm::vec3 vel) { @@ -468,9 +475,11 @@ glm::vec3 ALSpeaker::getVelocity() const { } void ALSpeaker::setRelative(bool relative) { + this->relative = relative; AL_CHECK( alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE) ); + refreshPosition(); } bool ALSpeaker::isRelative() const { @@ -782,11 +791,12 @@ void ALAudio::freeBuffer(uint buffer) { } void ALAudio::setListener( - glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up + worldvec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up ) { ALfloat listenerOri[] = {at.x, at.y, at.z, up.x, up.y, up.z}; - AL_CHECK(alListener3f(AL_POSITION, position.x, position.y, position.z)); + listenerPosition = position; + AL_CHECK(alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f)); AL_CHECK(alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z)); AL_CHECK(alListenerfv(AL_ORIENTATION, listenerOri)); AL_CHECK(alListenerf(AL_GAIN, get_channel(0)->getVolume())); diff --git a/src/audio/AL/ALAudio.hpp b/src/audio/AL/ALAudio.hpp index b405d1473..3ca08c671 100644 --- a/src/audio/AL/ALAudio.hpp +++ b/src/audio/AL/ALAudio.hpp @@ -121,6 +121,10 @@ namespace audio { int priority; int channel; float volume = 0.0f; + worldvec3 position {}; + bool relative = false; + + void refreshPosition(); public: ALStream* stream = nullptr; bool manuallyStopped = true; @@ -153,8 +157,8 @@ namespace audio { duration_t getDuration() const override; void setTime(duration_t time) override; - void setPosition(glm::vec3 pos) override; - glm::vec3 getPosition() const override; + void setPosition(worldvec3 pos) override; + worldvec3 getPosition() const override; void setVelocity(glm::vec3 vel) override; glm::vec3 getVelocity() const override; @@ -188,6 +192,7 @@ namespace audio { std::array filters; bool useEffects; + worldvec3 listenerPosition {}; ALAudio( ALCdevice* device, @@ -221,7 +226,7 @@ namespace audio { std::vector getInputDeviceNames() override; void setListener( - glm::vec3 position, + worldvec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up diff --git a/src/audio/NoAudio.hpp b/src/audio/NoAudio.hpp index c97794f36..c4e803c23 100644 --- a/src/audio/NoAudio.hpp +++ b/src/audio/NoAudio.hpp @@ -97,7 +97,7 @@ namespace audio { } void setListener( - glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up + worldvec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up ) override { } diff --git a/src/audio/audio.cpp b/src/audio/audio.cpp index a20020ced..370991f55 100644 --- a/src/audio/audio.cpp +++ b/src/audio/audio.cpp @@ -352,7 +352,7 @@ void audio::set_input_device(const std::string& deviceName) { } void audio::set_listener( - glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up + worldvec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up ) { backend->setListener(position, velocity, lookAt, up); } @@ -380,7 +380,7 @@ void remove_lower_priority_speaker(int priority) { speakerid_t audio::play( Sound* sound, - glm::vec3 position, + worldvec3 position, bool relative, float volume, float pitch, @@ -419,7 +419,7 @@ speakerid_t audio::play( speakerid_t audio::play( const std::shared_ptr& stream, - glm::vec3 position, + worldvec3 position, bool relative, float volume, float pitch, @@ -451,7 +451,7 @@ speakerid_t audio::play( speakerid_t audio::play_stream( const io::path& file, - glm::vec3 position, + worldvec3 position, bool relative, float volume, float pitch, diff --git a/src/audio/audio.hpp b/src/audio/audio.hpp index 9af27dde1..a9c035274 100644 --- a/src/audio/audio.hpp +++ b/src/audio/audio.hpp @@ -331,11 +331,11 @@ namespace audio { /// @brief Set speaker 3D position in the world /// @param pos new position - virtual void setPosition(glm::vec3 pos) = 0; + virtual void setPosition(worldvec3 pos) = 0; /// @brief Get speaker 3D position in the world /// @return position - virtual glm::vec3 getPosition() const = 0; + virtual worldvec3 getPosition() const = 0; /// @brief Set speaker movement velocity used for Doppler effect /// @param vel velocity vector @@ -391,7 +391,7 @@ namespace audio { uint bitsPerSample ) = 0; virtual void setListener( - glm::vec3 position, + worldvec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up @@ -482,7 +482,7 @@ namespace audio { /// @param lookAt point the listener look at /// @param up camera up vector void set_listener( - glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up + worldvec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up ); /// @brief Play 3D sound in the world @@ -498,7 +498,7 @@ namespace audio { /// @return speaker id or 0 speakerid_t play( Sound* sound, - glm::vec3 position, + worldvec3 position, bool relative, float volume, float pitch, @@ -518,7 +518,7 @@ namespace audio { /// @return speaker id or 0 speakerid_t play( const std::shared_ptr& stream, - glm::vec3 position, + worldvec3 position, bool relative, float volume, float pitch, @@ -537,7 +537,7 @@ namespace audio { /// @return speaker id or 0 speakerid_t play_stream( const io::path& file, - glm::vec3 position, + worldvec3 position, bool relative, float volume, float pitch, diff --git a/src/frontend/LevelFrontend.cpp b/src/frontend/LevelFrontend.cpp index 2143a4778..b5b640a62 100644 --- a/src/frontend/LevelFrontend.cpp +++ b/src/frontend/LevelFrontend.cpp @@ -74,7 +74,7 @@ LevelFrontend::LevelFrontend( } auto sound = assets.get(material->stepsSound); - glm::vec3 pos {}; + worldvec3 pos {}; auto soundsCamera = currentPlayer.currentCamera.get(); if (currentPlayer.isCurrentCameraBuiltin()) { soundsCamera = currentPlayer.fpCamera.get(); @@ -117,7 +117,7 @@ LevelFrontend::LevelFrontend( } audio::play( sound, - glm::vec3(pos.x, pos.y, pos.z) + 0.5f, + worldvec3(pos.x, pos.y, pos.z) + 0.5, false, 1.0f, 1.0f + (rand() % 6 - 3) * 0.05f, diff --git a/src/logic/scripting/lua/libs/libaudio.cpp b/src/logic/scripting/lua/libs/libaudio.cpp index bda2784e8..ce5d3b307 100644 --- a/src/logic/scripting/lua/libs/libaudio.cpp +++ b/src/logic/scripting/lua/libs/libaudio.cpp @@ -42,9 +42,7 @@ static audio::speakerid_t play_sound( } return audio::play( sound, - glm::vec3( - static_cast(x), static_cast(y), static_cast(z) - ), + worldvec3(x, y, z), relative, volume, pitch, @@ -75,11 +73,7 @@ static audio::speakerid_t play_stream( if (stream) { return audio::play( audio::open_stream(std::move(stream), true), - glm::vec3( - static_cast(x), - static_cast(y), - static_cast(z) - ), + worldvec3(x, y, z), relative, volume, pitch, @@ -96,15 +90,7 @@ static audio::speakerid_t play_stream( file = paths.find(filename); } return audio::play_stream( - file, - glm::vec3( - static_cast(x), static_cast(y), static_cast(z) - ), - relative, - volume, - pitch, - loop, - channel + file, worldvec3(x, y, z), relative, volume, pitch, loop, channel ); } @@ -277,9 +263,7 @@ static int l_audio_set_position(lua::State* L) { auto x = lua::tonumber(L, 2); auto y = lua::tonumber(L, 3); auto z = lua::tonumber(L, 4); - speaker->setPosition(glm::vec3( - static_cast(x), static_cast(y), static_cast(z) - )); + speaker->setPosition(worldvec3(x, y, z)); } return 0; } From ebd506de0946ed8e1e65717aa5225971515571d4 Mon Sep 17 00:00:00 2001 From: ostermine Date: Thu, 12 Nov 2026 01:19:22 +0300 Subject: [PATCH 7/8] fix block positions rounded to float in ray casts and routes iendpoint of block.raycast, entities.raycast and world.raycast and nodes of a pathfinding route are integer block positions, but they were pushed to Lua through glm::vec3. An odd coordinate above 16.7M came back as a neighbour block. --- src/logic/scripting/lua/libs/libblock.cpp | 2 +- src/logic/scripting/lua/libs/libentity.cpp | 2 +- src/logic/scripting/lua/libs/libpathfinding.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/logic/scripting/lua/libs/libblock.cpp b/src/logic/scripting/lua/libs/libblock.cpp index aff5af7c5..cdde30d18 100644 --- a/src/logic/scripting/lua/libs/libblock.cpp +++ b/src/logic/scripting/lua/libs/libblock.cpp @@ -598,7 +598,7 @@ static int l_raycast(lua::State* L) { lua::pushnumber(L, glm::distance(start, end)); lua::setfield(L, "length"); - lua::pushvec3(L, iend); + lua::pushvec(L, iend); lua::setfield(L, "iendpoint"); lua::pushinteger(L, voxel->id); diff --git a/src/logic/scripting/lua/libs/libentity.cpp b/src/logic/scripting/lua/libs/libentity.cpp index cc889c023..a809b3d4b 100644 --- a/src/logic/scripting/lua/libs/libentity.cpp +++ b/src/logic/scripting/lua/libs/libentity.cpp @@ -184,7 +184,7 @@ static int l_push_ray( lua::pushnumber(L, ray ? ray->distance : glm::distance(start, end)); lua::setfield(L, "length"); - lua::pushvec3(L, iend); + lua::pushvec(L, iend); lua::setfield(L, "iendpoint"); lua::pushinteger(L, block); diff --git a/src/logic/scripting/lua/libs/libpathfinding.cpp b/src/logic/scripting/lua/libs/libpathfinding.cpp index 55f5a3fc3..c1831be9c 100644 --- a/src/logic/scripting/lua/libs/libpathfinding.cpp +++ b/src/logic/scripting/lua/libs/libpathfinding.cpp @@ -36,7 +36,7 @@ static int l_is_enabled(lua::State* L) { static int push_route(lua::State* L, const voxels::Route& route) { lua::createtable(L, route.nodes.size(), 1); for (int i = 0; i < route.nodes.size(); i++) { - lua::pushvec3(L, route.nodes[i].pos); + lua::pushvec(L, route.nodes[i].pos); lua::rawseti(L, i + 1); } lua::pushinteger(L, route.totalVisited); From 95d2121318b3d54bf61eb7f42556a8a9de0cbd63 Mon Sep 17 00:00:00 2001 From: ostermine Date: Thu, 12 Nov 2026 01:19:23 +0300 Subject: [PATCH 8/8] add tests for positions far from the world origin dev/tests/far_coords.lua: at 1M and 30M blocks a position of a player, a spawn point and an entity is read back as it was set, a ray hits the block it is cast to, a body with a velocity moves the same way as at the world origin, and a position at 30M survives saving and loading of the world. test/physics/Hitbox.cpp checks the AABB of a hitbox far from the world origin, test/window/Camera.cpp checks the view relative to the rendering origin with positions in doubles. --- dev/tests/far_coords.lua | 94 ++++++++++++++++++++++++++++++++++++++++ test/physics/Hitbox.cpp | 30 +++++++++++++ test/window/Camera.cpp | 18 ++++---- 3 files changed, 133 insertions(+), 9 deletions(-) create mode 100644 dev/tests/far_coords.lua create mode 100644 test/physics/Hitbox.cpp diff --git a/dev/tests/far_coords.lua b/dev/tests/far_coords.lua new file mode 100644 index 000000000..57cfa8b5c --- /dev/null +++ b/dev/tests/far_coords.lua @@ -0,0 +1,94 @@ +local util = require "core:tests_util" + +util.create_demo_world("core:default") +app.set_setting("chunks.load-distance", 3) +app.set_setting("chunks.load-speed", 1) + +local pid = player.create("Xerxes") + +local function is_loaded(x, z) + return block.get(math.floor(x), 0, math.floor(z)) ~= -1 +end + +local function wait_chunk(x, z) + player.set_spawnpoint(pid, x, 100, z) + player.set_pos(pid, x, 100, z) + app.sleep_until(function () return is_loaded(x, z) end) +end + +local function spawn_drop(x, y, z) + return entities.spawn("base:drop", {x, y, z}, {base__drop={ + id=item.index("base:stone.item"), + count=1 + }}) +end + +local function move_body(coord) + local x, z = coord + 8.5, -coord - 8.5 + wait_chunk(x - 5, z) + local entity = spawn_drop(x, 50.5, z) + for _ = 1, 20 do + entity.rigidbody:set_vel({3, 0, -2}) + app.tick() + end + local pos = entity.transform:get_pos() + entity:despawn() + return {pos[1] - x, pos[2] - 50.5, pos[3] - z} +end + +local moved = move_body(0) +debug.print(moved) +assert(moved[1] > 1.0, "body didn't move") + +for _, coord in ipairs({1000000, 30000000}) do + local x, y, z = coord + 0.3, 100.6, -coord - 0.7 + + player.set_pos(pid, x, y, z) + util.check_vec3({x, y, z}, {player.get_pos(pid)}, "player.get_pos", 1e-6) + + player.set_spawnpoint(pid, x, y, z) + util.check_vec3( + {x, y, z}, {player.get_spawnpoint(pid)}, "player.get_spawnpoint", 1e-6 + ) + + wait_chunk(x, z) + + local entity = spawn_drop(x, y, z) + util.check_vec3({x, y, z}, entity.transform:get_pos(), "spawn pos", 1e-6) + entity.transform:set_pos({x + 0.25, y, z - 0.25}) + util.check_vec3( + {x + 0.25, y, z - 0.25}, entity.transform:get_pos(), "set_pos", 1e-6 + ) + entity:despawn() + + local ray = world.raycast({ + start = {x, 8, z}, + dir = {0, -1, 0}, + distance = 10, + }) + assert(ray, "ray didn't hit") + util.check_vec3({x, 1, z}, ray.endpoint, "ray.endpoint") + util.check_vec3( + {math.floor(x), 0, math.floor(z)}, ray.iendpoint, "ray.iendpoint" + ) + util.check_float(7, ray.length, "ray.length") + + local far_moved = move_body(coord) + debug.print(far_moved) + util.check_vec3(moved, far_moved, "body displacement", 1e-3) +end + +local x, z = 30000000.3, -30000000.7 +player.set_spawnpoint(pid, x, 100.6, z) +player.set_pos(pid, x, 100.6, z) +app.close_world(true) +app.open_world("demo") + +local px, _, pz = player.get_pos(pid) +util.check_float(x, px, "saved x", 1e-6) +util.check_float(z, pz, "saved z", 1e-6) +util.check_vec3( + {x, 100.6, z}, {player.get_spawnpoint(pid)}, "saved spawnpoint", 1e-6 +) +app.close_world(false) +app.delete_world("demo") diff --git a/test/physics/Hitbox.cpp b/test/physics/Hitbox.cpp new file mode 100644 index 000000000..e7923f97a --- /dev/null +++ b/test/physics/Hitbox.cpp @@ -0,0 +1,30 @@ +#include + +#include "physics/Hitbox.hpp" + +TEST(Hitbox, AABBRelativeToOrigin) { + for (double coord : {0.0, 1e6, 3e7}) { + worldvec3 position(coord + 0.3, 64.25, -coord - 0.7); + Hitbox hitbox( + 1, BodyType::DYNAMIC, position, glm::vec3(0.3f, 0.9f, 0.3f) + ); + AABB aabb = hitbox.getAABB(glm::floor(position)); + EXPECT_NEAR(aabb.a.x, 0.0f, 1e-6f) << "at " << coord; + EXPECT_NEAR(aabb.a.y, -0.65f, 1e-6f) << "at " << coord; + EXPECT_NEAR(aabb.a.z, 0.0f, 1e-6f) << "at " << coord; + EXPECT_NEAR(aabb.b.x, 0.6f, 1e-6f) << "at " << coord; + EXPECT_NEAR(aabb.b.y, 1.15f, 1e-6f) << "at " << coord; + EXPECT_NEAR(aabb.b.z, 0.6f, 1e-6f) << "at " << coord; + } +} + +TEST(Hitbox, SetPosFarFromOrigin) { + worldvec3 position(3e7 + 0.3, 64.25, -3e7 - 0.7); + Hitbox hitbox(1, BodyType::DYNAMIC, {}, glm::vec3(0.3f, 0.9f, 0.3f)); + hitbox.setPos(position); + EXPECT_EQ(hitbox.position, position); + EXPECT_EQ(hitbox.prevPosition, position); + + hitbox.setPos(position + worldvec3(0.05, 0.0, 0.0)); + EXPECT_EQ(hitbox.prevPosition, position); +} diff --git a/test/window/Camera.cpp b/test/window/Camera.cpp index 0015bc93d..354db1f30 100644 --- a/test/window/Camera.cpp +++ b/test/window/Camera.cpp @@ -31,18 +31,18 @@ TEST(Camera, ViewRotationFarFromOrigin) { } TEST(Camera, ViewRelativeToOrigin) { - for (float coord : {0.0f, 500.0f, -1e5f, 1e6f, 3e7f}) { - Camera camera(glm::vec3(coord, 64.0f, -coord), 1.0f); + for (double coord : {0.0, 500.3, -1e5 - 0.3, 1e6 + 0.3, 3e7 + 0.3}) { + Camera camera(worldvec3(coord, 64.0, -coord), 1.0f); camera.rotate(glm::radians(-20.0f), glm::radians(35.0f), 0.0f); - glm::dvec3 origin = camera.getOrigin(); - glm::vec3 local = camera.getLocalPosition(); - EXPECT_LE(glm::abs(local.x), 512.0f) << "at " << coord; - EXPECT_LE(glm::abs(local.z), 512.0f) << "at " << coord; - EXPECT_EQ(glm::dvec3(camera.position), origin + glm::dvec3(local)); + worldvec3 origin = camera.getOrigin(); + worldvec3 local = camera.getLocalPosition(); + EXPECT_LE(glm::abs(local.x), 512.0) << "at " << coord; + EXPECT_LE(glm::abs(local.z), 512.0) << "at " << coord; + EXPECT_NEAR(camera.position.x, origin.x + local.x, 1e-4) << coord; + EXPECT_NEAR(camera.position.z, origin.z + local.z, 1e-4) << coord; - glm::dvec3 point = - glm::dvec3(camera.position) + glm::dvec3(camera.front) * 10.0; + worldvec3 point = camera.position + worldvec3(camera.front) * 10.0; glm::vec4 viewPoint = camera.getView() * glm::vec4(glm::vec3(point - origin), 1.0f); EXPECT_NEAR(viewPoint.x, 0.0f, 1e-3f) << "at " << coord;