diff --git a/src/voxels/Chunk.cpp b/src/voxels/Chunk.cpp index c9dc4037..a4e645b0 100644 --- a/src/voxels/Chunk.cpp +++ b/src/voxels/Chunk.cpp @@ -35,3 +35,12 @@ Chunk* Chunk::clone() const { other->lightmap->set(lightmap); return other; } + +void Chunk::incref(){ + references++; +} + +void Chunk::decref(){ + if (--references <= 0) + delete this; +} diff --git a/src/voxels/Chunk.h b/src/voxels/Chunk.h index d2a972a3..850530f7 100644 --- a/src/voxels/Chunk.h +++ b/src/voxels/Chunk.h @@ -18,12 +18,15 @@ public: bool ready = false; bool accepted = false; bool generated = false; + int references = 1; Chunk(int x, int y, int z); ~Chunk(); bool isEmpty(); Chunk* clone() const; + void incref(); + void decref(); }; #endif /* VOXELS_CHUNK_H_ */ diff --git a/src/voxels/Chunks.cpp b/src/voxels/Chunks.cpp index 2887473d..73c4d875 100644 --- a/src/voxels/Chunks.cpp +++ b/src/voxels/Chunks.cpp @@ -278,7 +278,7 @@ void Chunks::translate(WorldFiles* worldFiles, int dx, int dy, int dz){ Mesh* mesh = meshes[(y * d + z) * w + x]; if (nx < 0 || ny < 0 || nz < 0 || nx >= w || ny >= h || nz >= d){ worldFiles->put((const char*)chunk->voxels, chunk->x, chunk->z); - delete chunk; + chunk->decref(); delete mesh; continue; } @@ -322,7 +322,7 @@ bool Chunks::putChunk(Chunk* chunk) { void Chunks::clear(bool freeMemory){ for (size_t i = 0; i < volume; i++){ if (freeMemory){ - delete chunks[i]; + chunks[i]->decref(); delete meshes[i]; } chunks[i] = nullptr; diff --git a/src/voxels/ChunksLoader.cpp b/src/voxels/ChunksLoader.cpp index c055158c..24bfd29c 100644 --- a/src/voxels/ChunksLoader.cpp +++ b/src/voxels/ChunksLoader.cpp @@ -17,30 +17,24 @@ void ChunksLoader::_thread(){ continue; } Chunk* chunk = current; - //std::cout << "LOADER: received chunk " << chunk->x << " " << chunk->y << " " << chunk->z << std::endl; + chunk->incref(); chunks._setOffset(chunk->x-1, chunk->y-1, chunk->z-1); if (!chunk->generated){ WorldGenerator::generate(chunk->voxels, chunk->x, chunk->y, chunk->z); - //std::cout << "LOADER: generated chunk" << std::endl; } - /*for (int i = 0; i < 27; i++){ - Chunk* other = closes[i]; - if (other == nullptr) - continue; - chunks.putChunk(other); - }*/ chunks.putChunk(chunk); lighting.onChunkLoaded(chunk->x, chunk->y, chunk->z, true); chunks.clear(false); for (int i = 0; i < 27; i++){ Chunk* other = closes[i]; - delete other; + //delete other; } chunk->ready = true; current = nullptr; + chunk->decref(); //std::cout << "LOADER: success" << std::endl; } } @@ -58,7 +52,7 @@ void ChunksLoader::perform(Chunk* chunk, const Chunk** cs){ if (other == nullptr) closes[i] = nullptr; else - closes[i] = other->clone(); + closes[i] = (Chunk*)other;//->clone(); } current = chunk; }