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.
This commit is contained in:
ostermine 2026-11-12 00:48:30 +03:00
parent e1f6daabb7
commit 89bdadd6aa
30 changed files with 283 additions and 127 deletions

View file

@ -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.

View file

@ -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.

View file

@ -11,14 +11,17 @@ layout (location = 3) in vec4 v_normal;
#include <sky>
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;

View file

@ -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,

View file

@ -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 {

View file

@ -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();

View file

@ -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);

View file

@ -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,

View file

@ -10,6 +10,7 @@
#include "lighting/Lightmap.hpp"
#include "voxels/Block.hpp"
#include "voxels/Chunks.hpp"
#include "window/Camera.hpp"
#include <algorithm>
@ -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<Shader>("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();
}

View file

@ -12,6 +12,7 @@
#include <map>
class Assets;
class Camera;
class Content;
class Chunks;
class Texture;
@ -41,7 +42,9 @@ class BlockWrapsRenderer {
std::unordered_map<u64id_t, std::unique_ptr<BlockWrapper>> 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,

View file

@ -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<ChunkVertex>(indexCount), 0};
glm::vec3(x, y, z), util::Buffer<ChunkVertex>(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;

View file

@ -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<float>(CHUNK_W) - 0.5f;
float pz = camera.position.z / static_cast<float>(CHUNK_D) - 0.5f;
const glm::ivec3 origin = camera.getOrigin();
const glm::vec3 cameraPos = camera.getLocalPosition();
chunksOffsetX -= floordiv<CHUNK_W>(origin.x);
chunksOffsetY -= floordiv<CHUNK_D>(origin.z);
float px = cameraPos.x / static_cast<float>(CHUNK_W) - 0.5f;
float pz = cameraPos.z / static_cast<float>(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<Atlas>("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<long long>(
glm::distance2(entry.position, cameraPos)
glm::distance2(entry.position, cameraPos - coord)
);
}
if (found->second.sortedMesh == nullptr ||

View file

@ -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<double>() * 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<int>(glm::floor(cameraPos.x)), totalDiameter
);
int gcellZ = floordiv(
origin.z + static_cast<int>(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<float>(totalDiameter)),
250 + layerId * 200,
-128 * scale + (z + gcellZ) * layer.segmentSize * scale +
-128 * scale + ((z + gcellZ) * totalDiameter - origin.z) +
glm::mod(timer * speedZ, static_cast<float>(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<int>(quality, layers.size()); i++) {
draw(layers[i], frustum, shader, camera, timer, i);
}

View file

@ -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
);
}

View file

@ -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
);
}
}

View file

@ -2,6 +2,8 @@
#include "typedefs.hpp"
#include <glm/vec3.hpp>
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
);
};

View file

@ -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();

View file

@ -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 {

View file

@ -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(

View file

@ -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;
}

View file

@ -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<Vertex>* mesh;
glm::vec3 lightSamplePos;
glm::dvec3 lightSamplePos;
bool shading;
Instance instance;
};

View file

@ -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,

View file

@ -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<double>(scale)) + timer * hspeed * -m;
float v1 = timer * weather.fall.vspeed + pos.y * scale +
glm::fract(uz * static_cast<double>(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<int, (depth + 1) * 2> 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<float>(lx) +
face.front * static_cast<float>(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),

View file

@ -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);

View file

@ -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<Shader>("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();

View file

@ -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

View file

@ -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;

View file

@ -3,6 +3,8 @@
#include <cmath>
#include <glm/ext.hpp>
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;
}

View file

@ -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;

View file

@ -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;
}
}