From cfdc8672ecb1e1bd1481b8ff1a53846892e28425 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 12 Nov 2026 22:13:38 +0300 Subject: [PATCH 1/8] add 'chunk.update-distance' setting --- src/io/settings_io.cpp | 1 + src/logic/BlocksController.cpp | 27 +++++++++++++++++++++++---- src/logic/BlocksController.hpp | 6 +++++- src/logic/LevelController.cpp | 2 +- src/settings.hpp | 2 ++ 5 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/io/settings_io.cpp b/src/io/settings_io.cpp index e72cb009d..301c25ec5 100644 --- a/src/io/settings_io.cpp +++ b/src/io/settings_io.cpp @@ -66,6 +66,7 @@ SettingsHandler::SettingsHandler(EngineSettings& settings) { builder.addSection("chunks"); builder.add("load-distance", &settings.chunks.loadDistance); builder.add("load-speed", &settings.chunks.loadSpeed); + builder.add("update-distance", &settings.chunks.updateDistance); builder.add("padding", &settings.chunks.padding); builder.addSection("graphics"); diff --git a/src/logic/BlocksController.cpp b/src/logic/BlocksController.cpp index 73951ff4b..b5e00d4d8 100644 --- a/src/logic/BlocksController.cpp +++ b/src/logic/BlocksController.cpp @@ -4,9 +4,7 @@ #include "items/Inventories.hpp" #include "items/Inventory.hpp" #include "lighting/Lighting.hpp" -#include "maths/fastmaths.hpp" #include "scripting/scripting.hpp" -#include "util/timeutil.hpp" #include "voxels/Block.hpp" #include "voxels/Chunk.hpp" #include "voxels/Chunks.hpp" @@ -17,15 +15,19 @@ #include "objects/Player.hpp" #include "objects/Players.hpp" #include "util/random.hpp" +#include "settings.hpp" #include static inline constexpr int CHUNK_RANDOM_TICK_SEGMENTS = 4; -BlocksController::BlocksController(const Level& level, Lighting* lighting) +BlocksController::BlocksController( + const Level& level, Lighting* lighting, const EngineSettings& settings +) : level(level), chunks(*level.chunks), lighting(lighting), + settings(settings), randTickClock(20, 3), blocksTickClock(20, 3), worldTickClock(20, 1) { @@ -189,6 +191,7 @@ void BlocksController::randomTick( std::shuffle(randomPattern.begin(), randomPattern.end(), randomEngine); } + int chunkRand = (chunk.x * 73856093) ^ (chunk.z * 19349663); for (int s = 0; s < segments; s++) { int repetions = 4; for (int i = 0; i < repetions; i++) { @@ -196,7 +199,9 @@ void BlocksController::randomTick( if (segmentY > chunk.top) { break; } - size_t index = randomPattern[(s * repetions + i + randomTickId) % randomPattern.size()]; + size_t index = randomPattern + [(s * repetions + i + randomTickId + chunkRand) % + randomPattern.size()]; int bx = index % CHUNK_W; int bz = (index / CHUNK_W) % CHUNK_D; int by = (index / (CHUNK_W * CHUNK_D)) + segmentY; @@ -214,13 +219,23 @@ void BlocksController::randomTick( } } +static long long calc_chunk_distance2( + const glm::vec3& pos, const Chunk& chunk +) { + int dx = chunk.x - static_cast(std::floor(pos.x / CHUNK_W)); + int dz = chunk.z - static_cast(std::floor(pos.z / CHUNK_D)); + return dx * dx + dz * dz; +} + void BlocksController::randomTick(int tickid, int parts, uint padding) { auto indices = level.content.getIndices(); + int updateDistance = settings.chunks.updateDistance.get(); for (const auto& [pid, player] : *level.players) { const auto& chunks = *player->chunks; int width = chunks.getWidth(); int height = chunks.getHeight(); + const auto& playerPos = player->getPosition(); for (uint z = padding; z < height - padding; z++) { for (uint x = padding; x < width - padding; x++) { @@ -232,6 +247,10 @@ void BlocksController::randomTick(int tickid, int parts, uint padding) { if (chunk == nullptr || !chunk->flags.ready) { continue; } + long long distance = calc_chunk_distance2(playerPos, *chunk); + if (distance > updateDistance * updateDistance) { + continue; + } if (chunk->lastRandomTickId == randomTickId) { continue; } diff --git a/src/logic/BlocksController.hpp b/src/logic/BlocksController.hpp index afd3f59f4..7e11470e3 100644 --- a/src/logic/BlocksController.hpp +++ b/src/logic/BlocksController.hpp @@ -15,6 +15,7 @@ class Chunks; class Lighting; class GlobalChunks; class ContentIndices; +struct EngineSettings; enum class BlockInteraction { step, destruction, placing }; @@ -27,13 +28,16 @@ class BlocksController { const Level& level; GlobalChunks& chunks; Lighting* lighting; + const EngineSettings& settings; util::Clock randTickClock; util::Clock blocksTickClock; util::Clock worldTickClock; std::vector blockInteractionCallbacks; uint64_t randomTickId = 0; public: - BlocksController(const Level& level, Lighting* lighting); + BlocksController( + const Level& level, Lighting* lighting, const EngineSettings& settings + ); void updateSides(int x, int y, int z); void updateSides(int x, int y, int z, int w, int h, int d); diff --git a/src/logic/LevelController.cpp b/src/logic/LevelController.cpp index edc57959e..1905745c7 100644 --- a/src/logic/LevelController.cpp +++ b/src/logic/LevelController.cpp @@ -46,7 +46,7 @@ LevelController::LevelController( ); } blocks = std::make_unique( - *level, chunks ? chunks->lighting.get() : nullptr + *level, chunks ? chunks->lighting.get() : nullptr, settings ); scripting::on_world_load(this); diff --git a/src/settings.hpp b/src/settings.hpp index 320d0fc8d..ad27034d2 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -45,6 +45,8 @@ struct ChunksSettings { IntegerSetting loadSpeed {4, 1, 32}; /// @brief Radius of chunks loading zone (chunk is unit) IntegerSetting loadDistance {22, 3, 80}; + /// @brief Radius of chunks update zone (chunk is unit) + IntegerSetting updateDistance {22, 3, 80}; /// @brief Buffer zone where chunks are not unloading (chunk is unit) IntegerSetting padding {2, 1, 8}; }; From 35e20c7dd4d1c68ddee5d7492efc81976a106b64 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 12 Nov 2026 22:28:06 +0300 Subject: [PATCH 2/8] cleanup WorldGenerator --- src/world/generator/WorldGenerator.cpp | 130 ++++++++++--------------- src/world/generator/WorldGenerator.hpp | 27 +---- 2 files changed, 53 insertions(+), 104 deletions(-) diff --git a/src/world/generator/WorldGenerator.cpp b/src/world/generator/WorldGenerator.cpp index 260a28e3c..e490fe349 100644 --- a/src/world/generator/WorldGenerator.cpp +++ b/src/world/generator/WorldGenerator.cpp @@ -1,8 +1,5 @@ #include "WorldGenerator.hpp" -#include -#include - #include "maths/util.hpp" #include "content/Content.hpp" #include "voxels/Block.hpp" @@ -15,6 +12,9 @@ #include "maths/util.hpp" #include "debug/Logger.hpp" +#include +#include + static debug::Logger logger("world-generator"); /// @brief Max number of biome parameters @@ -49,7 +49,7 @@ WorldGenerator::WorldGenerator( if (prototypes.find({x, z}) != prototypes.end()) { return; } - prototypes[{x, z}] = generatePrototype(x, z); + prototypes[{x, z}] = generatePrototype(); }); surroundMap.setLevelCallback(def.wideStructsChunksRadius + 1, [this](int const x, int const z) { @@ -144,9 +144,7 @@ static inline const Biome* choose_biome( return chosenBiome; } -std::unique_ptr WorldGenerator::generatePrototype( - int chunkX, int chunkZ -) { +std::unique_ptr WorldGenerator::generatePrototype() { return std::make_unique(); } @@ -237,21 +235,24 @@ void WorldGenerator::placeBlock(const BlockPlacement& block, int priority) { for (int cz = cza; cz <= czb; cz++) { for (int cx = cxa; cx <= cxb; cx++) { const auto& found = prototypes.find({cx, cz}); - if (found != prototypes.end()) { - // position becomes relative to prototype chunk - glm::ivec3 rel = block.position - glm::ivec3(cx * CHUNK_W, 0, cz * CHUNK_D); - bool owner = (cx == floordiv(block.position.x)) && (cz == floordiv(block.position.z)); - found->second->placements.emplace_back(priority, BlockPlacement{block.block, rel, block.rotation, !owner}); + if (found == prototypes.end()) { + continue; } + // position becomes relative to prototype chunk + glm::ivec3 rel = + block.position - glm::ivec3(cx * CHUNK_W, 0, cz * CHUNK_D); + bool owner = (cx == floordiv(block.position.x)) && + (cz == floordiv(block.position.z)); + found->second->placements.emplace_back( + priority, + BlockPlacement {block.block, rel, block.rotation, !owner} + ); } } } void WorldGenerator::placeStructures( - const std::vector& placements, - ChunkPrototype& prototype, - int chunkX, - int chunkZ + const std::vector& placements, int chunkX, int chunkZ ) { for (const auto& placement : placements) { if (auto sp = std::get_if(&placement.placement)) { @@ -278,7 +279,7 @@ void WorldGenerator::generateStructuresWide( auto placements = def.script->placeStructuresWide( {chunkX * CHUNK_W, chunkZ * CHUNK_D}, {CHUNK_W, CHUNK_D}, CHUNK_H ); - placeStructures(placements, prototype, chunkX, chunkZ); + placeStructures(placements, chunkX, chunkZ); prototype.level = ChunkPrototypeLevel::WIDE_STRUCTS; } @@ -296,7 +297,7 @@ void WorldGenerator::generateStructures( {chunkX * CHUNK_W, chunkZ * CHUNK_D}, {CHUNK_W, CHUNK_D}, heightmap, CHUNK_H ); - placeStructures(placements, prototype, chunkX, chunkZ); + placeStructures(placements, chunkX, chunkZ); util::PseudoRandom structsRand; structsRand.setSeed(chunkX, chunkZ); @@ -405,12 +406,7 @@ void WorldGenerator::update(int centerX, int centerY, int loadDistance) { } void WorldGenerator::generatePlants( - const ChunkPrototype& prototype, - float* heights, - voxel* voxels, - int chunkX, - int chunkZ, - const Biome** biomes + float* heights, voxel* voxels, int chunkX, int chunkZ, const Biome** biomes ) { const auto& indices = content.getIndices()->blocks; util::PseudoRandom plantsRand; @@ -447,12 +443,7 @@ void WorldGenerator::generatePlants( } void WorldGenerator::generateLand( - const ChunkPrototype& prototype, - float* values, - voxel* voxels, - int chunkX, - int chunkZ, - const Biome** biomes + float* values, voxel* voxels, const Biome** biomes ) { uint seaLevel = def.seaLevel; for (uint z = 0; z < CHUNK_D; z++) { @@ -477,27 +468,13 @@ void WorldGenerator::generate(voxel* voxels, int chunkX, int chunkZ) { const auto& prototype = requirePrototype(chunkX, chunkZ); const auto values = prototype.heightmap->getValues(); - uint seaLevel = def.seaLevel; - std::memset(voxels, 0, sizeof(voxel) * CHUNK_VOL); const auto& biomes = prototype.biomes.get(); - for (uint z = 0; z < CHUNK_D; z++) { - for (uint x = 0; x < CHUNK_W; x++) { - const Biome* biome = biomes[z * CHUNK_W + x]; - int height = values[z * CHUNK_W + x] * CHUNK_H; - height = std::max(0, height); - - const auto& groundLayers = biome->groundLayers; - const auto& seaLayers = biome->seaLayers; - - generate_pole(seaLayers, seaLevel, height, seaLevel, voxels, x, z); - generate_pole(groundLayers, height, 0, seaLevel, voxels, x, z); - } - } + generateLand(values, voxels, biomes); generatePlacements(prototype, voxels, chunkX, chunkZ); - generatePlants(prototype, values, voxels, chunkX, chunkZ, biomes); + generatePlants(values, voxels, chunkX, chunkZ, biomes); [[maybe_unused]] const auto& indices = content.getIndices()->blocks; for (uint i = 0; i < CHUNK_VOL; i++) { @@ -526,20 +503,17 @@ void WorldGenerator::generatePlacements( ); for (const auto& placement : placements) { if (auto structure = std::get_if(&placement.placement)) { - generateStructure(prototype, *structure, voxels, chunkX, chunkZ); + generateStructure(*structure, voxels); } else if (auto line = std::get_if(&placement.placement)) { - generateLine(prototype, *line, voxels, chunkX, chunkZ); + generateLine(*line, voxels, chunkX, chunkZ); } else if (auto block = std::get_if(&placement.placement)) { - generateBlock(prototype, *block, voxels, chunkX, chunkZ); + generateBlock(*block, voxels); } } } void WorldGenerator::generateStructure( - const ChunkPrototype& prototype, - const StructurePlacement& placement, - voxel* voxels, - int chunkX, int chunkZ + const StructurePlacement& placement, voxel* voxels ) { if (placement.structure < 0 || placement.structure >= def.structures.size()) { logger.error() << "invalid structure index " << placement.structure; @@ -577,10 +551,7 @@ void WorldGenerator::generateStructure( } void WorldGenerator::generateLine( - const ChunkPrototype& prototype, - const LinePlacement& line, - voxel* voxels, - int chunkX, int chunkZ + const LinePlacement& line, voxel* voxels, int chunkX, int chunkZ ) { const auto& indices = content.getIndices()->blocks; @@ -610,26 +581,26 @@ void WorldGenerator::generateLine( glm::ivec3 closest = util::closest_point_on_segment( a, b, point ); - if (y > 0 && - util::distance2(closest, point) <= radius * radius - ) { - auto& voxel = voxels[vox_index(x, y, z)]; - if (line.block != BLOCK_AIR) { - voxel = {line.block, {}}; - continue; - } - if (!indices.require(voxel.id).replaceable) { - voxel = {line.block, {}}; - } - auto& below = voxels[vox_index(x, y-1, z)]; - glm::ivec3 closest2 = util::closest_point_on_segment( - a, b, {gx, y-1, gz} - ); - if (util::distance2(closest2, {gx, y-1, gz}) > radius*radius) { - const auto& def = indices.require(below.id); - if (def.rt.surfaceReplacement != below.id) { - below = {def.rt.surfaceReplacement, {}}; - } + if (y <= 0 || util::distance2(closest, point) > radius * radius) { + continue; + } + auto& voxel = voxels[vox_index(x, y, z)]; + if (line.block != BLOCK_AIR) { + voxel = {line.block, {}}; + continue; + } + if (!indices.require(voxel.id).replaceable) { + voxel = {line.block, {}}; + } + auto& below = voxels[vox_index(x, y-1, z)]; + glm::ivec3 closest2 = util::closest_point_on_segment( + a, b, {gx, y-1, gz} + ); + if (util::distance2(closest2, {gx, y - 1, gz}) > + radius * radius) { + const auto& def = indices.require(below.id); + if (def.rt.surfaceReplacement != below.id) { + below = {def.rt.surfaceReplacement, {}}; } } } @@ -638,10 +609,7 @@ void WorldGenerator::generateLine( } void WorldGenerator::generateBlock( - const ChunkPrototype& prototype, - const BlockPlacement& placement, - voxel* voxels, - int chunkX, int chunkZ + const BlockPlacement& placement, voxel* voxels ) { const auto& indices = content.getIndices()->blocks; const auto& def = indices.require(placement.block); diff --git a/src/world/generator/WorldGenerator.hpp b/src/world/generator/WorldGenerator.hpp index 2dfa50b67..216f8d5fe 100644 --- a/src/world/generator/WorldGenerator.hpp +++ b/src/world/generator/WorldGenerator.hpp @@ -59,9 +59,7 @@ class WorldGenerator { SurroundMap surroundMap; /// @brief Generate chunk prototype (see ChunkPrototype) - /// @param x chunk position X divided by CHUNK_W - /// @param z chunk position Y divided by CHUNK_D - std::unique_ptr generatePrototype(int x, int z); + std::unique_ptr generatePrototype(); ChunkPrototype& requirePrototype(int x, int z); @@ -85,25 +83,13 @@ class WorldGenerator { const ChunkPrototype& prototype, voxel* voxels, int x, int z ); void generateLine( - const ChunkPrototype& prototype, const LinePlacement& placement, voxel* voxels, int x, int z ); - void generateBlock( - const ChunkPrototype& prototype, - const BlockPlacement& placement, - voxel* voxels, - int x, int z - ); - void generateStructure( - const ChunkPrototype& prototype, - const StructurePlacement& placement, - voxel* voxels, - int x, int z - ); + void generateBlock(const BlockPlacement& placement, voxel* voxels); + void generateStructure(const StructurePlacement& placement, voxel* voxels); void generatePlants( - const ChunkPrototype& prototype, float* values, voxel* voxels, int x, @@ -111,18 +97,13 @@ class WorldGenerator { const Biome** biomes ); void generateLand( - const ChunkPrototype& prototype, float* values, voxel* voxels, - int x, - int z, const Biome** biomes ); void placeStructures( - const std::vector& placements, - ChunkPrototype& prototype, - int x, int z + const std::vector& placements, int x, int z ); public: WorldGenerator( From 3895ef020c156e80e66ec10e110c93a89909e37c Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 12 Nov 2026 23:10:35 +0300 Subject: [PATCH 3/8] cleanup FrustumCulling.hpp --- src/maths/FrustumCulling.hpp | 125 +++++++++++++++-------------------- 1 file changed, 52 insertions(+), 73 deletions(-) diff --git a/src/maths/FrustumCulling.hpp b/src/maths/FrustumCulling.hpp index 27d62a52d..7c1b76de7 100644 --- a/src/maths/FrustumCulling.hpp +++ b/src/maths/FrustumCulling.hpp @@ -28,102 +28,81 @@ private: template glm::vec3 intersection(const glm::vec3* crosses) const; - glm::vec4 m_planes[Count]; - glm::vec3 m_points[8]; + glm::vec4 planes[Count]; + glm::vec3 points[8]; + glm::vec3 minPoint; + glm::vec3 maxPoint; }; inline void Frustum::update(glm::mat4 m) { m = glm::transpose(m); - m_planes[Left] = m[3] + m[0]; - m_planes[Right] = m[3] - m[0]; - m_planes[Bottom] = m[3] + m[1]; - m_planes[Top] = m[3] - m[1]; - m_planes[Near] = m[3] + m[2]; - m_planes[Far] = m[3] - m[2]; + planes[Left] = m[3] + m[0]; + planes[Right] = m[3] - m[0]; + planes[Bottom] = m[3] + m[1]; + planes[Top] = m[3] - m[1]; + planes[Near] = m[3] + m[2]; + planes[Far] = m[3] - m[2]; glm::vec3 crosses[Combinations] = { - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Right])), - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Bottom])), - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Top])), - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Near])), - glm::cross(glm::vec3(m_planes[Left]), glm::vec3(m_planes[Far])), - glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Bottom])), - glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Top])), - glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Near])), - glm::cross(glm::vec3(m_planes[Right]), glm::vec3(m_planes[Far])), - glm::cross(glm::vec3(m_planes[Bottom]), glm::vec3(m_planes[Top])), - glm::cross(glm::vec3(m_planes[Bottom]), glm::vec3(m_planes[Near])), - glm::cross(glm::vec3(m_planes[Bottom]), glm::vec3(m_planes[Far])), - glm::cross(glm::vec3(m_planes[Top]), glm::vec3(m_planes[Near])), - glm::cross(glm::vec3(m_planes[Top]), glm::vec3(m_planes[Far])), - glm::cross(glm::vec3(m_planes[Near]), glm::vec3(m_planes[Far]))}; + glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Right])), + glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Bottom])), + glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Top])), + glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Near])), + glm::cross(glm::vec3(planes[Left]), glm::vec3(planes[Far])), + glm::cross(glm::vec3(planes[Right]), glm::vec3(planes[Bottom])), + glm::cross(glm::vec3(planes[Right]), glm::vec3(planes[Top])), + glm::cross(glm::vec3(planes[Right]), glm::vec3(planes[Near])), + glm::cross(glm::vec3(planes[Right]), glm::vec3(planes[Far])), + glm::cross(glm::vec3(planes[Bottom]), glm::vec3(planes[Top])), + glm::cross(glm::vec3(planes[Bottom]), glm::vec3(planes[Near])), + glm::cross(glm::vec3(planes[Bottom]), glm::vec3(planes[Far])), + glm::cross(glm::vec3(planes[Top]), glm::vec3(planes[Near])), + glm::cross(glm::vec3(planes[Top]), glm::vec3(planes[Far])), + glm::cross(glm::vec3(planes[Near]), glm::vec3(planes[Far]))}; - m_points[0] = intersection(crosses); - m_points[1] = intersection(crosses); - m_points[2] = intersection(crosses); - m_points[3] = intersection(crosses); - m_points[4] = intersection(crosses); - m_points[5] = intersection(crosses); - m_points[6] = intersection(crosses); - m_points[7] = intersection(crosses); + points[0] = intersection(crosses); + points[1] = intersection(crosses); + points[2] = intersection(crosses); + points[3] = intersection(crosses); + points[4] = intersection(crosses); + points[5] = intersection(crosses); + points[6] = intersection(crosses); + points[7] = intersection(crosses); + + minPoint = maxPoint = points[0]; + for (int i = 1; i < 8; i++) { + minPoint = glm::min(minPoint, points[i]); + maxPoint = glm::max(maxPoint, points[i]); + } } inline bool Frustum::isBoxVisible(const glm::vec3& minp, const glm::vec3& maxp) const { - // check box outside/inside of frustum for (int i = 0; i < Count; i++) { - if ((glm::dot(m_planes[i], glm::vec4(minp.x, minp.y, minp.z, 1.0f)) < - 0.0) && - (glm::dot(m_planes[i], glm::vec4(maxp.x, minp.y, minp.z, 1.0f)) < - 0.0) && - (glm::dot(m_planes[i], glm::vec4(minp.x, maxp.y, minp.z, 1.0f)) < - 0.0) && - (glm::dot(m_planes[i], glm::vec4(maxp.x, maxp.y, minp.z, 1.0f)) < - 0.0) && - (glm::dot(m_planes[i], glm::vec4(minp.x, minp.y, maxp.z, 1.0f)) < - 0.0) && - (glm::dot(m_planes[i], glm::vec4(maxp.x, minp.y, maxp.z, 1.0f)) < - 0.0) && - (glm::dot(m_planes[i], glm::vec4(minp.x, maxp.y, maxp.z, 1.0f)) < - 0.0) && - (glm::dot(m_planes[i], glm::vec4(maxp.x, maxp.y, maxp.z, 1.0f)) < - 0.0)) { + const glm::vec4& p = planes[i]; + glm::vec3 v( + p.x > 0.0f ? maxp.x : minp.x, + p.y > 0.0f ? maxp.y : minp.y, + p.z > 0.0f ? maxp.z : minp.z + ); + if (glm::dot(glm::vec3(p), v) + p.w < 0.0f) { return false; } } - // check frustum outside/inside box - int out; - out = 0; - for (int i = 0; i < 8; i++) out += ((m_points[i].x > maxp.x) ? 1 : 0); - if (out == 8) return false; - out = 0; - for (int i = 0; i < 8; i++) out += ((m_points[i].x < minp.x) ? 1 : 0); - if (out == 8) return false; - out = 0; - for (int i = 0; i < 8; i++) out += ((m_points[i].y > maxp.y) ? 1 : 0); - if (out == 8) return false; - out = 0; - for (int i = 0; i < 8; i++) out += ((m_points[i].y < minp.y) ? 1 : 0); - if (out == 8) return false; - out = 0; - for (int i = 0; i < 8; i++) out += ((m_points[i].z > maxp.z) ? 1 : 0); - if (out == 8) return false; - out = 0; - for (int i = 0; i < 8; i++) out += ((m_points[i].z < minp.z) ? 1 : 0); - if (out == 8) return false; - - return true; + return !(minPoint.x > maxp.x || maxPoint.x < minp.x || + minPoint.y > maxp.y || maxPoint.y < minp.y || + minPoint.z > maxp.z || maxPoint.z < minp.z); } template inline glm::vec3 Frustum::intersection(const glm::vec3* crosses) const { - float D = glm::dot(glm::vec3(m_planes[a]), crosses[ij2k::k]); + float d = glm::dot(glm::vec3(planes[a]), crosses[ij2k::k]); glm::vec3 res = glm::mat3( crosses[ij2k::k], -crosses[ij2k::k], crosses[ij2k::k] ) * - glm::vec3(m_planes[a].w, m_planes[b].w, m_planes[c].w); - return res * (-1.0f / D); + glm::vec3(planes[a].w, planes[b].w, planes[c].w); + return res * (-1.0f / d); } From 156ba027507c57ed372206006ebaaaddf692273e Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 12 Nov 2026 23:43:00 +0300 Subject: [PATCH 4/8] optimize ChunksRenderer by reducing meshes map reads --- src/frontend/screens/LevelScreen.cpp | 6 ++-- src/graphics/render/ChunksRenderer.cpp | 40 +++++++++++++++++--------- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/src/frontend/screens/LevelScreen.cpp b/src/frontend/screens/LevelScreen.cpp index 2f29e8b7d..ea02fe025 100644 --- a/src/frontend/screens/LevelScreen.cpp +++ b/src/frontend/screens/LevelScreen.cpp @@ -24,7 +24,6 @@ #include "logic/PlayerController.hpp" #include "logic/scripting/scripting.hpp" #include "logic/scripting/scripting_hud.hpp" -#include "maths/voxmaths.hpp" #include "objects/Players.hpp" #include "objects/Entities.hpp" #include "physics/Hitbox.hpp" @@ -257,8 +256,7 @@ void LevelScreen::update(float delta) { updateHotkeys(); } updateAudio(); - - auto menu = gui.getMenu(); + bool inputLocked = gui.getActiveFrame() || hud->isInventoryOpen() || gui.isFocusCaught(); bool paused = hud->isPause(); @@ -284,7 +282,7 @@ void LevelScreen::update(float delta) { renderer->update(camera, delta * !hud->isPause()); } -void LevelScreen::draw(float delta) { +void LevelScreen::draw(float) { Camera& camera = *playerController->getPlayer().currentCamera; const DrawContext ctx(nullptr, engine.getWindow(), batch.get()); diff --git a/src/graphics/render/ChunksRenderer.cpp b/src/graphics/render/ChunksRenderer.cpp index 6cccbe3fa..3f8fad4e3 100644 --- a/src/graphics/render/ChunksRenderer.cpp +++ b/src/graphics/render/ChunksRenderer.cpp @@ -315,6 +315,19 @@ void ChunksRenderer::drawChunks( if (chunk == nullptr) { continue; } + int cx = chunk->x; + int cz = chunk->z; + if (culling) { + glm::vec3 min(cx * CHUNK_W, chunk->bottom, cz * CHUNK_D); + glm::vec3 max( + cx * CHUNK_W + CHUNK_W, chunk->top, cz * CHUNK_D + CHUNK_D + ); + + if (!frustum.isBoxVisible(min, max)) { + continue; + } + } + auto found = meshes.find(glm::ivec2(chunk->x, chunk->z)); if (found == meshes.end()) { continue; @@ -323,19 +336,19 @@ void ChunksRenderer::drawChunks( if (mesh.mesh == nullptr) { continue; } + 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), + cx * CHUNK_W + std::min(0.0f, aabbMin.x), chunk->bottom, - chunk->z * CHUNK_D + std::min(0.0f, aabbMin.z) + cz * 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 + cx * CHUNK_W + aabbMax.x, chunk->top, cz * CHUNK_D + aabbMax.z ); if (!frustum.isBoxVisible(min, max)) { @@ -388,22 +401,23 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) { if (chunk == nullptr || !chunk->flags.lighted) { continue; } - const auto& found = meshes.find(glm::ivec2(chunk->x, chunk->z)); - if (found == meshes.end() || found->second.sortingMeshData.entries.empty()) { - continue; - } + int cx = chunk->x; + int cz = chunk->z; if (culling) { - glm::vec3 min(chunk->x * CHUNK_W, chunk->bottom, chunk->z * CHUNK_D); + glm::vec3 min(cx * CHUNK_W, chunk->bottom, cz * CHUNK_D); glm::vec3 max( - chunk->x * CHUNK_W + CHUNK_W, - chunk->top, - chunk->z * CHUNK_D + CHUNK_D + cx * CHUNK_W + CHUNK_W, chunk->top, cz * CHUNK_D + CHUNK_D ); if (!frustum.isBoxVisible(min, max)) continue; } + const auto& found = meshes.find(glm::ivec2(cx, cz)); + if (found == meshes.end() || found->second.sortingMeshData.entries.empty()) { + continue; + } + auto& chunkEntries = found->second.sortingMeshData.entries; if (chunkEntries.size() == 1) { From 2ec58d1a14a1af9f5471362ecb24bc5280e9b596 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Fri, 13 Nov 2026 00:38:10 +0300 Subject: [PATCH 5/8] fix AreaMap2D::remove --- src/util/AreaMap2D.hpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/util/AreaMap2D.hpp b/src/util/AreaMap2D.hpp index 9ec0e439d..8ad3ff1d7 100644 --- a/src/util/AreaMap2D.hpp +++ b/src/util/AreaMap2D.hpp @@ -120,9 +120,14 @@ namespace util { if (lx < 0 || ly < 0 || lx >= sizeX || ly >= sizeY) { return; } + auto& element = firstBuffer[ly * sizeX + lx]; + if (element == T{}) { + return; + } if (outCallback) - outCallback(x, y, firstBuffer[ly * sizeX + lx]); - firstBuffer[ly * sizeX + lx] = T{}; + outCallback(x, y, element); + element = T{}; + valuesCount--; } void setOutCallback(const OutCallback& callback) { From 7fcf049a72e72381dcd1b0cdeffd8bba4d3209e0 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Fri, 13 Nov 2026 01:12:06 +0300 Subject: [PATCH 6/8] refactor ChunksController::loadVisible --- src/logic/ChunksController.cpp | 202 +++++++++++++++++++++------------ src/logic/ChunksController.hpp | 36 +++++- src/logic/LevelController.cpp | 3 +- 3 files changed, 165 insertions(+), 76 deletions(-) diff --git a/src/logic/ChunksController.cpp b/src/logic/ChunksController.cpp index 368d641d6..ac983daae 100644 --- a/src/logic/ChunksController.cpp +++ b/src/logic/ChunksController.cpp @@ -1,5 +1,6 @@ #include "ChunksController.hpp" +#include #include #include @@ -8,7 +9,6 @@ #include "graphics/core/Mesh.hpp" #include "lighting/Lighting.hpp" #include "maths/voxmaths.hpp" -#include "util/timeutil.hpp" #include "objects/Player.hpp" #include "voxels/Block.hpp" #include "voxels/Chunk.hpp" @@ -18,9 +18,16 @@ #include "world/LevelEvents.hpp" #include "world/World.hpp" #include "world/generator/WorldGenerator.hpp" +#include "debug/Logger.hpp" const uint MAX_WORK_PER_FRAME = 128; const uint MIN_SURROUNDING = 9; +const float WORK_UNITS_PER_SPEED_SECOND = 600.0f; +const float MAX_SECONDS_LIMIT = 0.25f; +const int CREATE_CHUNK_COST = 2; +const int BUILD_LIGHTS_COST = 4; + +static debug::Logger logger("chunks-control"); ChunksController::ChunksController(Level& level) : level(level), @@ -33,12 +40,13 @@ ChunksController::ChunksController(Level& level) ChunksController::~ChunksController() = default; void ChunksController::update( - int64_t maxDuration, + float delta, + int loadSpeed, int loadDistance, uint padding, Player& player, bool isLocalPlayer -) const { +) { const auto& position = player.getPosition(); int centerX = floordiv(glm::floor(position.x)); int centerY = floordiv(glm::floor(position.z)); @@ -50,18 +58,89 @@ void ChunksController::update( return; } - int64_t mcstotal = 0; + auto& chunks = *player.chunks; + auto& state = states[player.getId()]; + syncState(state, chunks, padding); - for (uint i = 0; i < MAX_WORK_PER_FRAME; i++) { - timeutil::Timer timer; - if (loadVisible(player, padding, isLocalPlayer)) { - int64_t mcs = timer.stop(); - if (mcstotal + mcs < maxDuration * 1000) { - mcstotal += mcs; - continue; + float rate = loadSpeed * WORK_UNITS_PER_SPEED_SECOND; + state.budget = std::min( + state.budget + rate * delta, rate * MAX_SECONDS_LIMIT + ); + for (uint i = 0; i < MAX_WORK_PER_FRAME && state.budget > 0.0f; i++) { + int cost = loadVisible(state, player, isLocalPlayer); + if (cost == 0) { + state.budget = 0.0f; + break; + } + state.budget -= cost; + } + state.chunksCount = chunks.getChunksCount(); +} + +void ChunksController::syncState( + LoadingState& state, Chunks& chunks, uint padding +) const { + int sizeX = chunks.getWidth(); + int sizeY = chunks.getHeight(); + bool layoutChanged = state.width != sizeX || state.height != sizeY || + state.padding != padding; + bool moved = state.offsetX != chunks.getOffsetX() || + state.offsetZ != chunks.getOffsetY(); + + if (layoutChanged) { + state.width = sizeX; + state.height = sizeY; + state.padding = padding; + state.order.clear(); + + int pad = static_cast(padding); + int minDistance = ((sizeX - pad * 2) / 2) * ((sizeY - pad * 2) / 2); + std::vector> cells; + for (int z = pad; z < sizeY - pad; z++) { + for (int x = pad; x < sizeX - pad; x++) { + int lx = x - sizeX / 2; + int lz = z - sizeY / 2; + int distance = lx * lx + lz * lz; + if (distance < minDistance) { + cells.emplace_back(distance, z * sizeX + x); + } + } + } + std::sort(cells.begin(), cells.end()); + state.order.reserve(cells.size()); + for (const auto& [_, index] : cells) { + state.order.push_back(index); + } + } + if (layoutChanged || moved) { + removeFarChunks(chunks); + state.offsetX = chunks.getOffsetX(); + state.offsetZ = chunks.getOffsetY(); + } + if (layoutChanged || moved || state.chunksCount != chunks.getChunksCount()) { + state.loadIndex = 0; + state.lightIndex = 0; + state.lightsDirty = true; + state.chunksCount = chunks.getChunksCount(); + } +} + +void ChunksController::removeFarChunks(Chunks& chunks) const { + int sizeX = chunks.getWidth(); + int sizeY = chunks.getHeight(); + int maxDistance = (sizeX / 2) * (sizeY / 2); + const auto& buffer = chunks.getChunks(); + for (int z = 0; z < sizeY; z++) { + for (int x = 0; x < sizeX; x++) { + if (buffer[z * sizeX + x] == nullptr) { + continue; + } + int lx = x - sizeX / 2; + int lz = z - sizeY / 2; + if (lx * lx + lz * lz >= maxDistance) { + chunks.remove(x + chunks.getOffsetX(), z + chunks.getOffsetY()); } } - break; } } @@ -81,68 +160,49 @@ bool ChunksController::isInLoadingZone( return distance < minDistance; } -bool ChunksController::loadVisible( - const Player& player, uint padding, bool isLocalPlayer +int ChunksController::loadVisible( + LoadingState& state, const Player& player, bool isLocalPlayer ) const { auto& chunks = *player.chunks; + const auto& buffer = chunks.getChunks(); + const auto& order = state.order; + + while (state.loadIndex < order.size() && + buffer[order[state.loadIndex]] != nullptr) { + state.loadIndex++; + } + + if (isLocalPlayer && state.lightsDirty) { + while (state.lightIndex < state.loadIndex) { + const auto& chunk = buffer[order[state.lightIndex]]; + if (chunk && chunk->flags.loaded && !chunk->flags.lighted) { + break; + } + state.lightIndex++; + } + for (size_t i = state.lightIndex; i < state.loadIndex; i++) { + const auto& chunk = buffer[order[i]]; + if (chunk && chunk->flags.loaded && !chunk->flags.lighted && + buildLights(player, chunk)) { + return BUILD_LIGHTS_COST; + } + } + state.lightsDirty = false; + } + + if (state.loadIndex >= order.size() || !player.isLoadingChunks()) { + return 0; + } + int index = order[state.loadIndex]; int sizeX = chunks.getWidth(); - int sizeY = chunks.getHeight(); - - int nearX = 0; - int nearZ = 0; - bool assigned = false; - int minDistance = ((sizeX - padding * 2) / 2) * ((sizeY - padding * 2) / 2); - int maxDistance = ((sizeX) / 2) * ((sizeY) / 2); - for (uint z = 0; z < sizeY; z++) { - for (uint x = 0; x < sizeX; x++) { - int index = z * sizeX + x; - int lx = x - sizeX / 2; - int lz = z - sizeY / 2; - int distance = (lx * lx + lz * lz); - auto& chunk = chunks.getChunks()[index]; - if (chunk != nullptr) { - if (distance >= maxDistance) { - chunks.remove( - x + chunks.getOffsetX(), z + chunks.getOffsetY() - ); - } - continue; - } - } - } - for (uint z = padding; z < sizeY - padding; z++) { - for (uint x = padding; x < sizeX - padding; x++) { - int index = z * sizeX + x; - int lx = x - sizeX / 2; - int lz = z - sizeY / 2; - int distance = (lx * lx + lz * lz); - auto& chunk = chunks.getChunks()[index]; - if (chunk != nullptr) { - if (chunk->flags.loaded && !chunk->flags.lighted) { - if (isLocalPlayer && buildLights(player, chunk)) { - return true; - } - } - continue; - } - - if (distance < minDistance) { - minDistance = distance; - nearX = x; - nearZ = z; - assigned = true; - } - } - } - - const auto& chunk = chunks.getChunks()[nearZ * sizeX + nearX]; - if (chunk != nullptr || !assigned || !player.isLoadingChunks()) { - return false; - } - int offsetX = chunks.getOffsetX(); - int offsetY = chunks.getOffsetY(); - createChunk(player, nearX + offsetX, nearZ + offsetY); - return true; + createChunk( + player, + index % sizeX + chunks.getOffsetX(), + index / sizeX + chunks.getOffsetY() + ); + state.loadIndex++; + state.lightsDirty = true; + return CREATE_CHUNK_COST; } bool ChunksController::buildLights( diff --git a/src/logic/ChunksController.hpp b/src/logic/ChunksController.hpp index 8eaaf7dca..8068229ae 100644 --- a/src/logic/ChunksController.hpp +++ b/src/logic/ChunksController.hpp @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include "typedefs.hpp" @@ -14,11 +16,35 @@ class WorldGenerator; /// @brief ChunksController manages chunks dynamic loading/unloading class ChunksController { private: + struct LoadingState { + int width = 0; + int height = 0; + uint padding = 0; + + int offsetX = 0; + int offsetZ = 0; + + size_t chunksCount = 0; + std::vector order; + size_t loadIndex = 0; + size_t lightIndex = 0; + bool lightsDirty = true; + + float budget = 0.0f; + }; + Level& level; std::unique_ptr generator; + std::unordered_map states; + + void syncState(LoadingState& state, Chunks& chunks, uint padding) const; + void removeFarChunks(Chunks& chunks) const; /// @brief Process one chunk: load it or calculate lights for it - bool loadVisible(const Player& player, uint padding, bool isLocalPlayer) const; + /// @return work units spent, 0 if there is nothing to do + int loadVisible( + LoadingState& state, const Player& player, bool isLocalPlayer + ) const; bool buildLights(const Player& player, const std::shared_ptr& chunk) const; void createChunk(const Player& player, int x, int y) const; public: @@ -27,14 +53,16 @@ public: ChunksController(Level& level); ~ChunksController(); - /// @param maxDuration milliseconds reserved for chunks loading + /// @param delta frame time in seconds + /// @param loadSpeed chunks loading speed void update( - int64_t maxDuration, + float delta, + int loadSpeed, int loadDistance, uint padding, Player& player, bool isLocalPlayer - ) const; + ); bool isInLoadingZone(const Player& player, uint padding, int x, int z) const; diff --git a/src/logic/LevelController.cpp b/src/logic/LevelController.cpp index 1905745c7..7833de1e5 100644 --- a/src/logic/LevelController.cpp +++ b/src/logic/LevelController.cpp @@ -63,7 +63,7 @@ LevelController::LevelController( player->chunks->configure( std::floor(position.x), std::floor(position.z), 1 ); - chunks->update(16, 1, 0, *player, player.get() == clientPlayer); + chunks->update(1.0f, 16, 1, 0, *player, player.get() == clientPlayer); if (player->chunks->get( std::floor(position.x), 0, std::floor(position.z) )) { @@ -89,6 +89,7 @@ void LevelController::update(float delta, bool pause) { settings.chunks.loadDistance.get() + settings.chunks.padding.get() ); chunks->update( + delta, settings.chunks.loadSpeed.get(), settings.chunks.loadDistance.get(), settings.chunks.padding.get(), From 562a0f9b0540e9ecc1aec16537f510cf2b8045fa Mon Sep 17 00:00:00 2001 From: MihailRis Date: Fri, 13 Nov 2026 01:18:18 +0300 Subject: [PATCH 7/8] cleanup --- src/logic/ChunksController.hpp | 44 +++++++++++++++++----------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/src/logic/ChunksController.hpp b/src/logic/ChunksController.hpp index 8068229ae..2868d2c37 100644 --- a/src/logic/ChunksController.hpp +++ b/src/logic/ChunksController.hpp @@ -15,6 +15,28 @@ class WorldGenerator; /// @brief ChunksController manages chunks dynamic loading/unloading class ChunksController { +public: + std::unique_ptr lighting; + + ChunksController(Level& level); + ~ChunksController(); + + /// @param delta frame time in seconds + /// @param loadSpeed chunks loading speed + void update( + float delta, + int loadSpeed, + int loadDistance, + uint padding, + Player& player, + bool isLocalPlayer + ); + + bool isInLoadingZone(const Player& player, uint padding, int x, int z) const; + + const WorldGenerator* getGenerator() const { + return generator.get(); + } private: struct LoadingState { int width = 0; @@ -47,26 +69,4 @@ private: ) const; bool buildLights(const Player& player, const std::shared_ptr& chunk) const; void createChunk(const Player& player, int x, int y) const; -public: - std::unique_ptr lighting; - - ChunksController(Level& level); - ~ChunksController(); - - /// @param delta frame time in seconds - /// @param loadSpeed chunks loading speed - void update( - float delta, - int loadSpeed, - int loadDistance, - uint padding, - Player& player, - bool isLocalPlayer - ); - - bool isInLoadingZone(const Player& player, uint padding, int x, int z) const; - - const WorldGenerator* getGenerator() const { - return generator.get(); - } }; From 2274a35ac17c813c1fa9acc39a07ccd20f09c46f Mon Sep 17 00:00:00 2001 From: MihailRis Date: Fri, 13 Nov 2026 01:39:31 +0300 Subject: [PATCH 8/8] cleanup ChunksRenderer --- src/graphics/render/ChunksRenderer.cpp | 30 +++++++------------------- 1 file changed, 8 insertions(+), 22 deletions(-) diff --git a/src/graphics/render/ChunksRenderer.cpp b/src/graphics/render/ChunksRenderer.cpp index 3f8fad4e3..be962adca 100644 --- a/src/graphics/render/ChunksRenderer.cpp +++ b/src/graphics/render/ChunksRenderer.cpp @@ -310,7 +310,7 @@ void ChunksRenderer::drawChunks( auto denseDistance2 = denseDistance * denseDistance; // TODO: minimize draw calls number - for (int i = indices.size()-1; i >= 0; i--) { + for (int i = indices.size() - 1; i >= 0; i--) { auto& chunk = chunks.getChunks()[indices[i].index]; if (chunk == nullptr) { continue; @@ -337,32 +337,18 @@ void ChunksRenderer::drawChunks( continue; } - if (culling) { - const auto& meshAABB = mesh.meshAABB; - auto aabbMin = meshAABB.min(); - auto aabbMax = meshAABB.max(); - - glm::vec3 min( - cx * CHUNK_W + std::min(0.0f, aabbMin.x), - chunk->bottom, - cz * CHUNK_D + std::min(0.0f, aabbMin.z) - ); - glm::vec3 max( - cx * CHUNK_W + aabbMax.x, chunk->top, cz * CHUNK_D + 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::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), - (coord + glm::vec3(CHUNK_W * 0.5f, 0.0f, CHUNK_D * 0.5f))) < denseDistance2); + mesh.mesh->draw( + GL_TRIANGLES, + glm::distance2( + camera.position * glm::vec3(1, 0, 1), + (coord + glm::vec3(CHUNK_W * 0.5f, 0.0f, CHUNK_D * 0.5f)) + ) < denseDistance2 + ); visibleChunks++; } }