1
0
Fork 0
Univerxel/src/world/Chunk.cpp

80 lines
2.3 KiB
C++
Raw Normal View History

2020-07-10 17:49:16 +00:00
#include "Chunk.hpp"
#include <FastNoiseSIMD.h>
#include "materials.hpp"
2020-07-25 16:45:03 +00:00
using namespace world;
2020-07-10 17:49:16 +00:00
#define DENSITY 0.f
#define GRANULARITY 30.f
Chunk::Chunk(const chunk_pos& pos, Generator& rnd) {
const auto [densitySet, materialSet] = rnd.getChunk(pos, CHUNK_LENGTH);
for (size_t i = 0; i < CHUNK_SIZE; i++) {
voxels[i].Density = std::clamp((densitySet[i] + DENSITY) * GRANULARITY, 0.f, 1.f) * UCHAR_MAX;
2020-07-25 14:29:05 +00:00
voxels[i].Material = voxels[i].Density > 0 ? 1 + std::clamp(static_cast<int>(std::lrint((materialSet[i] + 1) / 2 * (materials::count - 2))),
0, materials::count - 2) : 0; //NOTE: map (approx -1, 1) to (1, mat_max)
2020-07-10 17:49:16 +00:00
}
2020-07-23 19:39:08 +00:00
FastNoiseSIMD::FreeNoiseSet(densitySet);
FastNoiseSIMD::FreeNoiseSet(materialSet);
2020-07-10 17:49:16 +00:00
}
Chunk::~Chunk() { }
2020-07-25 14:29:05 +00:00
std::optional<Faces> Chunk::update() {
2020-07-10 17:49:16 +00:00
if(upToDate) {
2020-07-25 14:29:05 +00:00
return {};
2020-07-10 17:49:16 +00:00
} else {
upToDate = true;
2020-07-25 14:29:05 +00:00
return {toUpdate};
2020-07-10 17:49:16 +00:00
}
}
2020-07-25 16:45:03 +00:00
void Chunk::set(ushort idx, const Voxel& val) {
voxels[idx] = val;
invalidate(
((!getNeighborIdx(idx, Face::Up).has_value()) & Faces::Up) |
((!getNeighborIdx(idx, Face::Down).has_value()) & Faces::Down) |
((!getNeighborIdx(idx, Face::Left).has_value()) & Faces::Left) |
((!getNeighborIdx(idx, Face::Right).has_value()) & Faces::Right) |
((!getNeighborIdx(idx, Face::Forward).has_value()) & Faces::Forward) |
((!getNeighborIdx(idx, Face::Backward).has_value()) & Faces::Backward));
}
2020-07-10 17:49:16 +00:00
std::optional<ushort> Chunk::getNeighborIdx(ushort idx, Face face) {
switch (face) {
case Face::Forward:
if (idx % CHUNK_LENGTH >= CHUNK_LENGTH - 1)
return {};
return idx + 1;
case Face::Backward:
if (idx % CHUNK_LENGTH <= 0)
return {};
return idx - 1;
case Face::Up:
if ((idx / CHUNK_LENGTH) % CHUNK_LENGTH >= CHUNK_LENGTH - 1)
return {};
return idx + CHUNK_LENGTH;
case Face::Down:
if ((idx / CHUNK_LENGTH) % CHUNK_LENGTH <= 0)
return {};
return idx - CHUNK_LENGTH;
case Face::Right:
if (idx / CHUNK_LENGTH2 >= CHUNK_LENGTH - 1)
return {};
return idx + CHUNK_LENGTH2;
case Face::Left:
if (idx / CHUNK_LENGTH2 <= 0)
return {};
return idx - CHUNK_LENGTH2;
default:
return {};
}
}