6 Commits

Author SHA1 Message Date
8929af888a fix(renderer): correct shader uniform name and remove unused uniform 2026-06-20 22:08:16 +08:00
a72b0dd677 feat(world): integrate thread pool and async chunk generation 2026-06-20 21:57:27 +08:00
4b617612e8 fix(gameplay): use gen_phase_one to get seed 2026-06-20 17:12:48 +08:00
5cfd663566 refactor(gameplay): move chunk generation phases into gen_chunk method
Consolidate multiple phase generation calls into a single gen_chunk() method on Chunk, which handles neighbor generation and ensures thread safety. Simplify World::gen_chunks_internal by using gen_chunk() instead of manual phase orchestration.
2026-06-20 17:11:05 +08:00
d69e1895d4 refactor(gameplay): remove dead code and simplify chunk neighbor context
Remove the large commented-out `init_chunks()` function, and eliminate the `affected_neighbor` tracking in `gen_chunks_internal()`. This simplifies the neighbor context building and removes unused vertex data regeneration for affected neighbors.
2026-06-20 16:38:36 +08:00
be17846c16 feat(renderer): add fog effect based on render distance 2026-06-20 15:49:00 +08:00
8 changed files with 276 additions and 545 deletions

View File

@@ -25,6 +25,10 @@ uniform float minRadius;
uniform float maxRadius;
uniform bool enablePBR;
uniform bool flipY;
uniform int renderDistance;
uniform vec3 skyColor;
const vec2 poissonDisk32[32] = vec2[](
vec2(-0.975402, -0.071138),
vec2(-0.920347, -0.411420),
@@ -341,8 +345,17 @@ void main(void) {
vec3 specular = spec * sunlightColor * specularStrength;
float shadow = ShadowCalculation(FragPosLightSpace, norm, lightDir);
// fog
float dist = length(cameraPos - vert_pos);
vec4 fogColor = vec4(skyColor, 1.0);
float fogStart = renderDistance * 16 * 0.9;
float fogEnd = renderDistance * 16;
float fogFactor = smoothstep(fogEnd, fogStart, dist);
color = vec4((ambient + (1.0 - shadow) * (diffuse)) * objectColor.rgb + (1.0-shadow) * specular * objectColor.rgb, objectColor.a);
color = mix(fogColor, color, fogFactor);
//color = vec4(normal * 0.5 + 0.5, 1.0);
//color = vec4(tangent * 0.5 + 0.5, 1.0);;
//color = vec4(norm * 0.5 + 0.5, 1.0);

View File

@@ -23,6 +23,8 @@ private:
std::atomic<bool> m_dirty{false};
std::atomic<bool> m_need_upload{true};
std::atomic<bool> m_is_on_gen_vertex_data{false};
std::atomic<bool> m_gening{false};
std::atomic<bool> m_gen_finish{false};
std::atomic<BiomeType> m_biome = BiomeType::PLAIN;
std::mutex m_vertexs_data_mutex;
@@ -124,7 +126,10 @@ public:
void need_upload();
void set_chunk_block(int index, unsigned id);
// ensure thread safe!
void gen_chunk();
bool is_gen_finish() const;
ChunkPos chunk_pos() const;
BiomeType biome() const;
void biome(BiomeType b);

View File

@@ -4,6 +4,7 @@
#include "Cubed/gameplay/chunk.hpp"
#include "Cubed/gameplay/game_time.hpp"
#include "Cubed/gameplay/river_worm.hpp"
#include "Cubed/tools/thread_pool.hpp"
#include <atomic>
#include <condition_variable>
@@ -34,15 +35,22 @@ class Player;
class TextureManager;
class World {
private:
struct PendingChunk {
Chunk chunk;
std::future<void> future;
};
using OptionalBlockVectorArray =
std::array<std::optional<std::vector<BlockType>>, 4>;
using ChunkPtrUpdateList = std::vector<std::pair<ChunkPos, Chunk*>>;
using ChunkPairVector = std::vector<std::pair<ChunkPos, Chunk>>;
using ChunkPairQueue = std::queue<std::pair<ChunkPos, Chunk>>;
using ConstChunkMap =
std::unordered_map<ChunkPos, const Chunk*, ChunkPos::Hash>;
using ChunkPosSet = std::unordered_set<ChunkPos, ChunkPos::Hash>;
using ChunkHashMap = std::unordered_map<ChunkPos, Chunk, ChunkPos::Hash>;
using PendingChunkHashMap =
std::unordered_map<ChunkPos, PendingChunk, ChunkPos::Hash>;
glm::vec3 m_gen_player_pos{0.0f, 0.0f, 0.0f};
ChunkHashMap m_chunks;
std::unordered_map<std::size_t, Player> m_players;
@@ -50,7 +58,7 @@ private:
std::thread m_gen_thread;
std::thread m_server_thread;
std::unique_ptr<ThreadPool> m_gen_thread_pool;
std::stop_source m_server_stop_source;
std::atomic<int> m_per_tick_time = DEFAULT_PER_TICK_TIME; // ms
@@ -59,7 +67,7 @@ private:
mutable std::mutex m_chunks_mutex;
std::mutex m_gen_signal_mutex;
std::mutex m_new_chunk_queue_mutex;
std::mutex m_new_chunk_mutex;
std::mutex m_delete_vbo_mutex;
std::mutex m_delete_vao_mutex;
std::mutex m_gen_player_pos_mutex;
@@ -79,8 +87,9 @@ private:
std::vector<ChunkPos> m_dirty_queue;
std::vector<ChunkRenderSnapshot> m_render_snapshots;
std::vector<std::pair<ChunkPos, Chunk>> m_new_chunk;
std::vector<std::pair<ChunkPos, Chunk>> m_new_chunk_queue;
std::vector<std::pair<ChunkPos, Chunk>> m_new_finished_chunk;
// Can only be used in the gen thread
PendingChunkHashMap new_chunks;
CaveCarver m_cave_carcer;
RiverWorm m_river_worm;
@@ -88,18 +97,13 @@ private:
void gen_chunks_internal();
void sync_player_pos(glm::vec3& player_pos);
void
compute_required_chunks(ChunkPosSet& required_chunks,
ChunkPairVector& temp_neighbor,
std::vector<ChunkPos>& need_gen_temp_chunks_pos);
void compute_required_chunks(ChunkPosSet& required_chunks,
ChunkPairVector& temp_neighbor);
void sync_and_collect_missing_chunks(std::vector<ChunkPos>&,
const ChunkPosSet&);
void
build_neighbor_context_for_new_chunks(ConstChunkMap& new_chunks_neighbor,
ChunkPtrUpdateList& affected_neighbor,
const ChunkPairVector& new_chunks);
void build_neighbor_context_for_affected_neighbors(ChunkPtrUpdateList&,
ConstChunkMap&);
void submit_new_chunks();
void poll_finished_chunks();
public:
World();

View File

@@ -0,0 +1,115 @@
#pragma once
#include <condition_variable>
#include <cstddef>
#include <functional>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
namespace Cubed {
class ThreadPool {
private:
std::vector<std::jthread> m_workers;
std::queue<std::function<void()>> m_tasks;
std::mutex m_mtx;
std::condition_variable_any m_cv;
std::atomic<bool> m_stopping{false};
std::atomic<size_t> m_thread_sum{0};
public:
ThreadPool(const ThreadPool&) = delete;
ThreadPool(ThreadPool&&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
ThreadPool& operator=(ThreadPool&&) = delete;
explicit ThreadPool(size_t thread_sum) : m_thread_sum(thread_sum) {
for (size_t i = 0; i < thread_sum; i++) {
m_workers.emplace_back([this](std::stop_token stoken) {
while (true) {
std::function<void()> task;
{
std::unique_lock lock(m_mtx);
m_cv.wait(lock, stoken,
[this, stoken] { return !m_tasks.empty(); });
if (stoken.stop_requested() && m_tasks.empty()) {
return;
}
task = std::move(m_tasks.front());
m_tasks.pop();
}
task();
}
});
}
}
~ThreadPool() {
m_stopping = true;
for (auto& w : m_workers) {
w.request_stop();
}
m_cv.notify_all();
}
template <typename F> auto enqueue(F&& f) {
using R = std::invoke_result_t<F>;
auto task =
std::make_shared<std::packaged_task<R()>>(std::forward<F>(f));
auto fut = task->get_future();
{
std::lock_guard lock(m_mtx);
if (m_stopping)
throw std::runtime_error("thread pool stopped");
m_tasks.emplace([task] { (*task)(); });
}
m_cv.notify_one();
return fut;
}
size_t thread_sum() const { return m_thread_sum.load(); }
};
template <std::random_access_iterator Iter, typename F>
void parallel_do(ThreadPool& pool, Iter first, Iter last, size_t max_threads,
F&& f) {
max_threads = std::max<size_t>(1, max_threads);
max_threads = std::min(max_threads, pool.thread_sum());
std::decay_t<F> fn(std::forward<F>(f));
size_t length = std::distance(first, last);
if (!length) {
return;
}
constexpr size_t MIN_PER_THREAD = 25;
size_t num_blocks =
std::min(max_threads, (length + MIN_PER_THREAD - 1) / MIN_PER_THREAD);
num_blocks = std::max<size_t>(1, num_blocks);
size_t block_size = (length + num_blocks - 1) / num_blocks;
std::vector<std::future<void>> futures;
futures.reserve(num_blocks - 1);
Iter block_start = first;
for (size_t i = 0; i < num_blocks - 1; ++i) {
Iter block_end = block_start;
auto remain = std::distance(block_start, last);
std::advance(block_end, std::min<size_t>(block_size, remain));
futures.emplace_back(pool.enqueue([block_start, block_end, &fn]() {
for (auto it = block_start; it != block_end; ++it) {
fn(*it);
}
}));
block_start = block_end;
}
for (auto it = block_start; it != last; ++it) {
fn(*it);
}
for (auto& fut : futures) {
fut.get();
}
};
} // namespace Cubed

View File

@@ -4,4 +4,5 @@ leak:libpangocairo
leak:libdecor-gtk.so
leak:libgtk-3.so
leak:libwayland-client.so
leak:libglfw.so
leak:libglfw.so
leak:libEGL_nvidia.so

View File

@@ -455,6 +455,42 @@ void Chunk::gen_cross_plane_vertices(int world_x, int world_y, int world_z,
}
}
void Chunk::gen_chunk() {
if (m_gening.exchange(true))
return;
m_gening = true;
if (m_blocks.size() != 0) {
Logger::warn(
"Request Generator Chunk {} {} ,but the Blocks size is Not 0",
m_chunk_pos.x, m_chunk_pos.z);
}
std::vector<Chunk> neighbor;
for (int i = 0; i < 4; i++) {
neighbor.emplace_back(m_world, m_chunk_pos + CHUNK_DIR[i]);
}
for (auto& chunk : neighbor) {
chunk.gen_phase_one();
chunk.gen_phase_three();
chunk.gen_phase_five();
chunk.gen_phase_seven();
}
gen_phase_one();
gen_phase_three();
gen_phase_five();
OptionalBlockVectorArray neightbor_blocks;
for (int i = 0; i < 4; i++) {
neightbor_blocks[i] = neighbor[i].get_chunk_blocks();
}
gen_phase_six(neightbor_blocks);
gen_phase_seven();
for (int i = 0; i < 4; i++) {
neightbor_blocks[i] = neighbor[i].get_chunk_blocks();
}
gen_vertex_data(neightbor_blocks);
m_gen_finish = true;
}
bool Chunk::is_gen_finish() const { return m_gen_finish.load(); }
// Logger::info("Cross Sum {}", m_cross_vertices_sum.load());
} // namespace Cubed

View File

@@ -5,11 +5,10 @@
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/cubed_hash.hpp"
#include <execution>
#include <glm/gtc/constants.hpp>
#include <numbers>
using namespace std::chrono;
using namespace std::chrono_literals;
namespace Cubed {
struct ChunkRenderData {
@@ -77,10 +76,14 @@ void World::init_world() {
m_cave_carcer.init(ChunkGenerator::seed());
m_river_worm.init(ChunkGenerator::seed());
m_chunks.reserve(MAX_DISTANCE * MAX_DISTANCE * 4);
int max_thread = std::thread::hardware_concurrency();
int used_thread = std::max(max_thread - 3, 1);
Logger::info("Max Support Thread is {}, use {} threads to gen", max_thread,
used_thread);
m_gen_thread_pool = std::make_unique<ThreadPool>(used_thread);
auto t1 = std::chrono::system_clock::now();
Logger::info("Max Support Thread is {}",
std::thread::hardware_concurrency());
// init players
m_players.emplace(HASH::str("TestPlayer"), Player(*this, "TestPlayer"));
@@ -102,209 +105,6 @@ void World::init_chunks() {
}
}
/*
void World::init_chunks() {
int dis_x = PRE_LOAD_DISTANCE;
int dis_z = PRE_LOAD_DISTANCE;
for (int x = 0; x < dis_x; x++) {
for (int z = 0; z < dis_z; z++) {
int nx = x - dis_x / 2;
int nz = z - dis_z / 2;
ChunkPos pos{nx, nz};
auto it = m_chunks.find(pos);
if (it == m_chunks.end()) {
m_chunks.emplace(pos, Chunk(*this, pos));
}
}
}
ChunkHashMap temp_neighbor;
for (int x = 0; x < dis_x + 2; x++) {
for (int z = 0; z < dis_z + 2; z++) {
int nx = x - (dis_x + 2) / 2;
int nz = z - (dis_z + 2) / 2;
ChunkPos pos{nx, nz};
auto it = m_chunks.find(pos);
if (it == m_chunks.end()) {
auto it = temp_neighbor.find(pos);
if (it == temp_neighbor.end()) {
temp_neighbor.emplace(pos, Chunk(*this, pos));
}
}
}
}
for (auto& [pos, chunk] : m_chunks) {
chunk.gen_phase_one();
m_cave_carcer.try_to_add_path(pos, chunk.seed());
}
for (auto& [pos, chunk] : temp_neighbor) {
chunk.gen_phase_one();
m_cave_carcer.try_to_add_path(pos, chunk.seed());
}
std::array<const Chunk*, 8> neighbor_chunks;
for (auto& [pos, chunks] : m_chunks) {
for (int i = 0; i < 8; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = m_chunks.find(neighbor_pos);
if (it == m_chunks.end()) {
auto it = temp_neighbor.find(neighbor_pos);
if (it == temp_neighbor.end()) {
neighbor_chunks[i] = nullptr;
ASSERT_MSG(false, "Neighbor Chunk is nullptr");
} else {
neighbor_chunks[i] = &it->second;
}
continue;
}
neighbor_chunks[i] = &it->second;
}
chunks.gen_phase_two(neighbor_chunks);
}
for (auto& [pos, chunks] : temp_neighbor) {
for (int i = 0; i < 8; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = m_chunks.find(neighbor_pos);
if (it == m_chunks.end()) {
auto it = temp_neighbor.find(neighbor_pos);
if (it == temp_neighbor.end()) {
neighbor_chunks[i] = nullptr;
} else {
neighbor_chunks[i] = &it->second;
}
continue;
}
neighbor_chunks[i] = &it->second;
}
chunks.gen_phase_two(neighbor_chunks);
}
for (auto& [pos, chunks] : m_chunks) {
chunks.gen_phase_three();
}
for (auto& [pos, chunks] : temp_neighbor) {
chunks.gen_phase_three();
}
for (int i = 0; i < 4; i++) {
for (auto& [pos, chunks] : temp_neighbor) {
std::array<std::optional<HeightMapArray>, 8>
neighbor_chunk_heightmap;
std::array<BiomeType, 8> neighbor_biome;
for (int i = 0; i < 4; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = m_chunks.find(neighbor_pos);
if (it == m_chunks.end()) {
auto it = temp_neighbor.find(neighbor_pos);
if (it == temp_neighbor.end()) {
neighbor_chunk_heightmap[i] = std::nullopt;
neighbor_biome[i] = BiomeType::NONE;
} else {
neighbor_chunk_heightmap[i] =
it->second.get_heightmap();
neighbor_biome[i] = it->second.biome();
}
continue;
}
neighbor_chunk_heightmap[i] = it->second.get_heightmap();
neighbor_biome[i] = it->second.biome();
}
chunks.gen_phase_four(neighbor_chunk_heightmap, neighbor_biome);
}
for (auto& [pos, chunks] : m_chunks) {
std::array<std::optional<HeightMapArray>, 8>
neighbor_chunk_heightmap;
std::array<BiomeType, 8> neighbor_biome;
for (int i = 0; i < 8; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = m_chunks.find(neighbor_pos);
if (it == m_chunks.end()) {
auto it = temp_neighbor.find(neighbor_pos);
if (it == temp_neighbor.end()) {
neighbor_chunk_heightmap[i] = std::nullopt;
neighbor_biome[i] = BiomeType::NONE;
ASSERT_MSG(false, "Neighbor Chunk is nullptr");
} else {
neighbor_chunk_heightmap[i] =
it->second.get_heightmap();
neighbor_biome[i] = it->second.biome();
}
continue;
}
neighbor_chunk_heightmap[i] = it->second.get_heightmap();
neighbor_biome[i] = it->second.biome();
}
chunks.gen_phase_four(neighbor_chunk_heightmap, neighbor_biome);
}
}
for (auto& [pos, chunks] : m_chunks) {
chunks.gen_phase_five();
}
for (auto& [pos, chunks] : temp_neighbor) {
chunks.gen_phase_five();
}
std::array<std::optional<std::vector<BlockType>>, 4> neighbor_block;
for (auto& [pos, chunks] : m_chunks) {
for (int i = 0; i < 4; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = m_chunks.find(neighbor_pos);
if (it == m_chunks.end()) {
auto it = temp_neighbor.find(neighbor_pos);
if (it == temp_neighbor.end()) {
neighbor_block[i] = std::nullopt;
ASSERT_MSG(false, "Neighbor Chunk is nullptr");
} else {
neighbor_block[i] = it->second.get_chunk_blocks();
}
continue;
}
neighbor_block[i] = it->second.get_chunk_blocks();
}
chunks.gen_phase_six(neighbor_block);
}
for (auto& [pos, chunks] : m_chunks) {
chunks.gen_phase_seven();
}
std::atomic<int> sync{0};
sync.store(1, std::memory_order_release);
sync.load(std::memory_order_acquire);
m_cave_carcer.cleanup_finished_caves();
std::vector<ChunkRenderData> pending_gen_data;
pending_gen_data.reserve(m_chunks.size());
for (auto& [pos, chunk] : m_chunks) {
ChunkRenderData data;
data.chunk = &chunk;
for (int i = 0; i < 4; i++) {
auto it = m_chunks.find(pos + CHUNK_DIR[i]);
if (it != m_chunks.end()) {
data.neighbor_block[i] = &(it->second.get_chunk_blocks());
} else {
data.neighbor_block[i] = nullptr;
}
}
pending_gen_data.emplace_back(std::move(data));
}
std::for_each(std::execution::par, pending_gen_data.begin(),
pending_gen_data.end(), [](ChunkRenderData& data) {
if (!data.chunk) {
return;
}
data.chunk->gen_vertex_data(data.neighbor_block);
});
for (auto& chunk_map : m_chunks) {
auto& [chunk_pos, chunk] = chunk_map;
chunk.upload_to_gpu();
}
}
*/
ChunkPos World::chunk_pos(int world_x, int world_z) {
int chunk_x, chunk_z;
if (world_x < 0) {
@@ -325,13 +125,19 @@ ChunkPos World::chunk_pos(int world_x, int world_z) {
#pragma region ChunkGenerate
void World::gen_chunks_internal() {
// Logger::info("gen_chunks_internal");
m_chunk_gen_fraction = 0.0f;
m_chunk_gen_finished = false;
/*
if (!new_chunks.empty()) {
submit_new_chunks();
return;
}*/
ChunkPosSet required_chunks;
ChunkPairVector temp_neighbor;
std::vector<ChunkPos> need_gen_temp_chunks_pos;
compute_required_chunks(required_chunks, temp_neighbor,
need_gen_temp_chunks_pos);
compute_required_chunks(required_chunks, temp_neighbor);
ASSERT_MSG(!required_chunks.empty(), "required chunks is empty!!");
@@ -348,256 +154,27 @@ void World::gen_chunks_internal() {
}
m_chunk_gen_fraction = 0.1f;
ChunkPairVector new_chunks;
ChunkHashMap new_temp_chunks;
for (auto& pos : need_gen_chunks_pos) {
new_chunks.push_back({pos, Chunk(*this, pos)});
new_chunks.emplace(pos, Chunk(*this, pos));
}
for (auto& pos : need_gen_temp_chunks_pos) {
new_temp_chunks.emplace(pos, Chunk(*this, pos));
}
ConstChunkMap new_chunks_neighbor;
// affected neighbor
ChunkPtrUpdateList affected_neighbor;
build_neighbor_context_for_new_chunks(new_chunks_neighbor,
affected_neighbor, new_chunks);
// build new chunk, but the neighbor in m_chunks also need to re-build
std::for_each(std::execution::par, new_chunks.begin(), new_chunks.end(),
[this](std::pair<ChunkPos, Chunk>& new_chunk) {
auto& [pos, chunk] = new_chunk;
chunk.gen_phase_one();
m_cave_carcer.try_to_add_path(pos, chunk.seed());
m_river_worm.try_to_add_path(pos, chunk.seed());
});
std::for_each(new_temp_chunks.begin(), new_temp_chunks.end(),
[](std::pair<const ChunkPos, Chunk>& new_chunk) {
auto& [pos, chunk] = new_chunk;
chunk.gen_phase_one();
});
// precompute path to ensure the continuity of the path
std::for_each(std::execution::par, temp_neighbor.begin(),
temp_neighbor.end(),
[this](std::pair<ChunkPos, Chunk>& new_chunk) {
auto& [pos, chunk] = new_chunk;
chunk.gen_phase_one();
m_cave_carcer.try_to_add_path(pos, chunk.seed());
m_river_worm.try_to_add_path(pos, chunk.seed());
});
m_chunk_gen_fraction = 0.2f;
/*
std::array<const Chunk*, 8> neighbor_chunks;
for (auto& [pos, chunks] : new_chunks) {
for (int i = 0; i < 8; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = new_chunks_neighbor.find(neighbor_pos);
if (it == new_chunks_neighbor.end()) {
neighbor_chunks[i] = nullptr;
// ASSERT_MSG(false, "Cant Find Neighbot");
continue;
}
neighbor_chunks[i] = it->second;
}
chunks.gen_phase_two(neighbor_chunks);
}
*/
/*
for (auto& [pos, chunks] : temp_neighbor) {
for (int i = 0; i < 8; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = new_chunks_neighbor.find(neighbor_pos);
if (it == new_chunks_neighbor.end()) {
neighbor_chunks[i] = nullptr;
continue;
}
neighbor_chunks[i] = it->second;
}
chunks.gen_phase_two(neighbor_chunks);
}
*/
m_chunk_gen_fraction = 0.3f;
std::for_each(std::execution::par, new_chunks.begin(), new_chunks.end(),
[](std::pair<ChunkPos, Chunk>& pair) {
auto& [pos, chunks] = pair;
chunks.gen_phase_three();
});
for (auto& [pos, chunk] : new_temp_chunks) {
chunk.gen_phase_three();
}
// for (auto& [pos, chunks] : temp_neighbor) {
// chunks.gen_phase_three();
// }
/*
for (int i = 0; i < 4; i++) {
for (auto& [pos, chunks] : temp_neighbor) {
std::array<std::optional<HeightMapArray>, 8>
neighbor_chunk_heightmap;
// std::lock_guard lk(m_chunks_mutex);
std::array<BiomeType, 8> neighbor_biome;
for (int i = 0; i < 8; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = new_chunks_neighbor.find(neighbor_pos);
if (it == new_chunks_neighbor.end()) {
neighbor_chunk_heightmap[i] = std::nullopt;
neighbor_biome[i] = BiomeType::NONE;
continue;
}
neighbor_chunk_heightmap[i] = it->second->get_heightmap();
neighbor_biome[i] = it->second->biome();
}
chunks.gen_phase_four(neighbor_chunk_heightmap, neighbor_biome);
}
for (auto& [pos, chunks] : new_chunks) {
std::array<std::optional<HeightMapArray>, 8>
neighbor_chunk_heightmap;
// std::lock_guard lk(m_chunks_mutex);
std::array<BiomeType, 8> neighbor_biome;
for (int i = 0; i < 8; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = new_chunks_neighbor.find(neighbor_pos);
if (it == new_chunks_neighbor.end()) {
neighbor_chunk_heightmap[i] = std::nullopt;
neighbor_biome[i] = BiomeType::NONE;
ASSERT_MSG(false, "Cant Find Neighbot");
continue;
}
neighbor_chunk_heightmap[i] = it->second->get_heightmap();
neighbor_biome[i] = it->second->biome();
}
chunks.gen_phase_four(neighbor_chunk_heightmap, neighbor_biome);
}
}
*/
m_chunk_gen_fraction = 0.4f;
for (auto& [pos, chunks] : new_chunks) {
chunks.gen_phase_five();
}
m_chunk_gen_fraction = 0.45f;
for (auto& [pos, chunk] : new_temp_chunks) {
chunk.gen_phase_five();
}
m_chunk_gen_fraction = 0.5f;
/*
for (auto& [pos, chunks] : temp_neighbor) {
chunks.gen_phase_five();
}
*/
std::vector<std::pair<Chunk*, OptionalBlockVectorArray>>
new_chunks_surface_blend_data(new_chunks.size());
for (size_t idx = 0; idx < new_chunks.size(); idx++) {
auto& [pos, chunk] = new_chunks[idx];
new_chunks_surface_blend_data[idx].first = &chunk;
{
// std::lock_guard lk(m_chunks_mutex);
for (int i = 0; i < 4; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = new_chunks_neighbor.find(neighbor_pos);
if (it == new_chunks_neighbor.end()) {
auto it = new_temp_chunks.find(neighbor_pos);
if (it == new_temp_chunks.end()) {
new_chunks_surface_blend_data[idx].second[i] =
std::nullopt;
Logger::warn(
"Can't find neighbor for chunk surface blend");
continue;
}
new_chunks_surface_blend_data[idx].second[i] =
it->second.get_chunk_blocks();
continue;
}
new_chunks_surface_blend_data[idx].second[i] =
it->second->get_chunk_blocks();
}
}
}
std::for_each(
std::execution::par, new_chunks_surface_blend_data.begin(),
new_chunks_surface_blend_data.end(),
[](std::pair<Chunk*, OptionalBlockVectorArray>& new_chunk_data) {
auto& [chunk, neighbor_data] = new_chunk_data;
chunk->gen_phase_six(neighbor_data);
});
m_chunk_gen_fraction = 0.55f;
std::for_each(std::execution::par, new_chunks.begin(), new_chunks.end(),
[](std::pair<ChunkPos, Chunk>& new_chunk) {
auto& [pos, chunk] = new_chunk;
chunk.gen_phase_seven();
});
m_chunk_gen_fraction = 0.6f;
std::vector<std::pair<Chunk*, OptionalBlockVectorArray>>
new_chunk_vertices_data(new_chunks.size());
for (size_t idx = 0; idx < new_chunks.size(); idx++) {
auto& [pos, chunk] = new_chunks[idx];
new_chunk_vertices_data[idx].first = &chunk;
for (int i = 0; i < 4; i++) {
auto it = new_chunks_neighbor.find(pos + CHUNK_DIR[i]);
if (it != new_chunks_neighbor.end()) {
new_chunk_vertices_data[idx].second[i] =
(it->second->get_chunk_blocks());
} else {
new_chunk_vertices_data[idx].second[i] = std::nullopt;
}
}
}
std::for_each(
std::execution::par, new_chunk_vertices_data.begin(),
new_chunk_vertices_data.end(),
[](std::pair<Chunk*, OptionalBlockVectorArray>& new_chunk_data) {
auto& [chunk, neighbor_data] = new_chunk_data;
chunk->gen_vertex_data(neighbor_data);
});
m_chunk_gen_fraction = 0.7f;
build_neighbor_context_for_affected_neighbors(affected_neighbor,
new_chunks_neighbor);
m_chunk_gen_fraction = 0.8f;
OptionalBlockVectorArray neighbor_block;
for (auto& [pos, chunk] : affected_neighbor) {
for (int i = 0; i < 4; i++) {
auto it = new_chunks_neighbor.find(pos + CHUNK_DIR[i]);
if (it != new_chunks_neighbor.end()) {
neighbor_block[i] = (it->second->get_chunk_blocks());
} else {
neighbor_block[i] = std::nullopt;
}
}
chunk->gen_vertex_data(neighbor_block);
chunk->need_upload();
}
auto t1 = system_clock::now();
parallel_do(*m_gen_thread_pool, temp_neighbor.begin(), temp_neighbor.end(),
m_gen_thread_pool->thread_sum(),
[this](std::pair<ChunkPos, Chunk>& new_chunk) {
auto& [pos, chunk] = new_chunk;
chunk.gen_phase_one();
m_cave_carcer.try_to_add_path(pos, chunk.seed());
m_river_worm.try_to_add_path(pos, chunk.seed());
});
auto t2 = system_clock::now();
Logger::info("Temp Neighbor Add Path Consum {}",
duration_cast<milliseconds>(t2 - t1));
m_chunk_gen_fraction = 0.9f;
{
std::lock_guard lk(m_new_chunk_queue_mutex);
for (auto& x : new_chunks) {
m_new_chunk_queue.emplace_back(std::move(x));
}
}
m_cave_carcer.cleanup_finished_caves();
m_river_worm.cleanup_finished_rivers();
m_chunk_gen_fraction = 1.0f;
submit_new_chunks();
m_chunk_gen_finished = true;
}
@@ -606,9 +183,8 @@ void World::sync_player_pos(glm::vec3& player_pos) {
player_pos = m_gen_player_pos;
}
void World::compute_required_chunks(
ChunkPosSet& required_chunks, ChunkPairVector& temp_neighbor,
std::vector<ChunkPos>& need_gen_temp_chunks_pos) {
void World::compute_required_chunks(ChunkPosSet& required_chunks,
ChunkPairVector& temp_neighbor) {
glm::vec3 player_pos;
sync_player_pos(player_pos);
@@ -626,20 +202,6 @@ void World::compute_required_chunks(
}
}
}
int new_radius = radius + 1;
int new_r2 = new_radius * new_radius;
for (int dx = -new_radius; dx <= new_radius; ++dx) {
for (int dz = -new_radius; dz <= new_radius; ++dz) {
if (dx * dx + dz * dz <= new_r2) {
int nx = chunk_x + dx;
int nz = chunk_z + dz;
auto it = required_chunks.find({nx, nz});
if (it == required_chunks.end()) {
need_gen_temp_chunks_pos.push_back({nx, nz});
}
}
}
}
int max_path_len = std::max(CavePath::step_max(), RiverPath::step_max());
radius = max_path_len / 2;
r2 = radius * radius;
@@ -677,37 +239,34 @@ void World::sync_and_collect_missing_chunks(
}
}
void World::build_neighbor_context_for_new_chunks(
ConstChunkMap& new_chunks_neighbor, ChunkPtrUpdateList& affected_neighbor,
const ChunkPairVector& new_chunks) {
{
std::lock_guard lk(m_chunks_mutex);
for (auto& [pos, chunk] : new_chunks) {
for (auto& dir : CHUNK_DIR) {
auto it = m_chunks.find(pos + dir);
if (it != m_chunks.end()) {
new_chunks_neighbor.insert({it->first, &(it->second)});
affected_neighbor.push_back({it->first, &(it->second)});
}
}
void World::submit_new_chunks() {
std::lock_guard lock(m_new_chunk_mutex);
for (auto& [pos, task] : new_chunks) {
if (!task.future.valid()) {
task.future = m_gen_thread_pool->enqueue(
[&task]() { task.chunk.gen_chunk(); });
}
}
for (auto& [pos, chunk] : new_chunks) {
new_chunks_neighbor.insert({pos, &chunk});
}
}
void World::build_neighbor_context_for_affected_neighbors(
ChunkPtrUpdateList& affected_neighbor, ConstChunkMap& new_chunks_neighbor) {
std::lock_guard lk(m_chunks_mutex);
for (auto& [pos, chunk] : affected_neighbor) {
for (auto& dir : CHUNK_DIR) {
auto it = m_chunks.find(pos + dir);
if (it != m_chunks.end()) {
new_chunks_neighbor.insert({it->first, &(it->second)});
void World::poll_finished_chunks() {
m_new_finished_chunk.clear();
std::lock_guard lock(m_new_chunk_mutex);
std::erase_if(
new_chunks, [&](std::pair<const ChunkPos, PendingChunk>& pair) {
auto& pending = pair.second;
if (!pending.future.valid()) {
return false;
}
}
}
if (pending.future.wait_for(0ms) != std::future_status::ready) {
return false;
}
pending.future.get();
m_new_finished_chunk.emplace_back(pair.first,
std::move(pending.chunk));
return true;
});
}
#pragma endregion
@@ -767,10 +326,12 @@ void World::serever_run(std::stop_token stoken) {
}
void World::need_gen() {
if (!m_could_gen) {
Logger::warn("It is generating or consuming new chunks");
return;
}
m_could_gen = false;
{
std::lock_guard lk(m_gen_player_pos_mutex);
@@ -778,6 +339,7 @@ void World::need_gen() {
}
m_need_gen_chunk = true;
m_gen_cv.notify_one();
}
@@ -845,16 +407,16 @@ BlockType World::get_block_tpye(const glm::ivec3& block_pos) const {
auto it = m_chunks.find(ChunkPos{chunk_x, chunk_z});
if (it == m_chunks.end()) {
Logger::error("Can't Find Block {} {} {}", block_pos.x, block_pos.y,
block_pos.z);
// Logger::error("Can't Find Block {} {} {}", block_pos.x, block_pos.y,
// block_pos.z);
return 0;
}
const auto& chunk_blocks = it->second.get_chunk_blocks();
auto [x, y, z] = Chunk::world_to_block(block_pos, {chunk_x, chunk_z});
if (x < 0 || y < 0 || z < 0 || x >= CHUNK_SIZE || y >= WORLD_SIZE_Y ||
z >= CHUNK_SIZE) {
Logger::error("Can't Find Block {} {} {}", block_pos.x, block_pos.y,
block_pos.z);
// Logger::error("Can't Find Block {} {} {}", block_pos.x, block_pos.y,
// block_pos.z);
return 0;
}
return chunk_blocks[Chunk::index(x, y, z)];
@@ -918,16 +480,9 @@ void World::update(float delta_time) {
m_pending_delete_vao.clear();
}
{
std::scoped_lock lk(m_chunks_mutex, m_new_chunk_queue_mutex);
m_new_chunk.clear();
for (auto& x : m_new_chunk_queue) {
m_new_chunk.emplace_back(std::move(x));
}
m_new_chunk_queue.clear();
}
poll_finished_chunks();
for (auto& x : m_new_chunk) {
for (auto& x : m_new_finished_chunk) {
x.second.upload_to_gpu();
}
@@ -936,7 +491,7 @@ void World::update(float delta_time) {
std::lock_guard lk(m_chunks_mutex);
bool consumed = false;
for (auto& x : m_new_chunk) {
for (auto& x : m_new_finished_chunk) {
m_chunks.insert_or_assign(x.first, std::move(x.second));
consumed = true;
}
@@ -1011,9 +566,9 @@ void World::rebuild_world() {
m_cave_carcer.reload(ChunkGenerator::seed());
m_river_worm.reload(ChunkGenerator::seed());
{
std::scoped_lock lk(m_chunks_mutex, m_new_chunk_queue_mutex);
std::scoped_lock lk(m_chunks_mutex);
m_chunks.clear();
m_new_chunk_queue.clear();
m_new_finished_chunk.clear();
}
m_could_gen = true;
ChunkGenerator::reload();
@@ -1023,20 +578,6 @@ void World::rebuild_world() {
m_is_rebuilding = false;
}
float World::chunk_gen_fraction() const { return m_chunk_gen_fraction.load(); }
int World::rendering_distance() const { return m_rendering_distance.load(); }
void World::rendering_distance(int rendering_distance) {
m_rendering_distance = rendering_distance;
}
CaveCarver& World::cave_carcer() { return m_cave_carcer; }
RiverWorm& World::river_worm() { return m_river_worm; }
std::vector<glm::vec4>& World::planes() { return m_planes; }
std::vector<ChunkRenderSnapshot>& World::render_snapshots() {
return m_render_snapshots;
};
/*
glm::vec3 World::sunlight_dir() const {
float t = static_cast<float>(m_day_tick) / DAY_TIME;
@@ -1071,6 +612,21 @@ glm::vec3 World::sunlight_dir() const {
return glm::normalize(-dir);
}
float World::chunk_gen_fraction() const { return m_chunk_gen_fraction.load(); }
int World::rendering_distance() const { return m_rendering_distance.load(); }
void World::rendering_distance(int rendering_distance) {
m_rendering_distance = rendering_distance;
}
CaveCarver& World::cave_carcer() { return m_cave_carcer; }
RiverWorm& World::river_worm() { return m_river_worm; }
std::vector<glm::vec4>& World::planes() { return m_planes; }
std::vector<ChunkRenderSnapshot>& World::render_snapshots() {
return m_render_snapshots;
};
TickType World::game_tick() const { return m_game_ticks.load(); }
TickType World::day_tick() const { return m_day_tick.load(); }
void World::day_tick(TickType tick) {

View File

@@ -419,7 +419,7 @@ void Renderer::render_ui() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
shader.set_loc("mv_matrix", m_ui_m_matrix);
shader.set_loc("m_matrix", m_ui_m_matrix);
shader.set_loc("proj_matrix", m_ui_proj);
glBindVertexArray(m_vao[3]);
@@ -719,7 +719,6 @@ void Renderer::render_world() {
normal_block_shader.set_loc("sunlightDir", light_dir_view);
normal_block_shader.set_loc("shadowMode", m_shadow_mode);
normal_block_shader.set_loc("shader_on", m_shader_on);
normal_block_shader.set_loc("texelsPerUnit", texels_per_unit);
normal_block_shader.set_loc("lightSizeUV",
static_cast<float>(m_light_size_uv));
normal_block_shader.set_loc("minRadius", m_min_radius);
@@ -728,6 +727,8 @@ void Renderer::render_world() {
normal_block_shader.set_loc("specularStrength", m_specular_strength);
normal_block_shader.set_loc("cameraPos", m_camera.get_camera_pos());
normal_block_shader.set_loc("flipY", m_flip_y);
normal_block_shader.set_loc("renderDistance", m_world.rendering_distance());
normal_block_shader.set_loc("skyColor", m_sky_uniform.sky_top);
m_mvp_mat = m_p_mat * m_mv_mat;
auto& m_planes = m_world.planes();