Techneck/code/source-c/chunk_pool.c

91 lines
2.5 KiB
C
Raw Normal View History

2023-10-12 16:52:05 +00:00
#include "world.h"
#include <stdlib.h>
2023-10-14 13:04:52 +00:00
#include <string.h>
2023-10-12 16:52:05 +00:00
void tc_reset_chunk_pool(tc_chunk_pool_s *chunk_pool)
{
chunk_pool->used_entries = 0;
chunk_pool->first_free = chunk_pool->entries;
uint32_t entry_index = 0;
while(entry_index < chunk_pool->capacity)
{
chunk_pool->entries[entry_index].next = &chunk_pool->entries[entry_index+1];
chunk_pool->entries[entry_index].previous = &chunk_pool->entries[entry_index-1];
++entry_index;
}
chunk_pool->entries[0].previous = NULL;
chunk_pool->entries[chunk_pool->capacity-1].next = NULL;
}
tc_chunk_pool_s * tc_new_chunk_pool(uint32_t capacity)
{
tc_chunk_pool_s *pool = malloc(sizeof(tc_chunk_pool_s));
pool->capacity = capacity;
pool->entries = calloc(sizeof(tc_chunk_pool_entry_s), pool->capacity);
tc_reset_chunk_pool(pool);
return pool;
}
tc_chunk_pool_entry_s * tc_allocate_chunk_pool_entry(tc_chunk_pool_s *pool)
{
if(pool->first_free == NULL)
{
pool->continuation = tc_new_chunk_pool(pool->capacity * 2);
return tc_allocate_chunk_pool_entry(pool->continuation);
}
tc_chunk_pool_entry_s *allocated = pool->first_free;
pool->first_free = allocated->next;
return allocated;
}
tc_chunk_s * tc_allocate_chunk(tc_world_s *world)
{
tc_chunk_pool_entry_s *entry = tc_allocate_chunk_pool_entry(world->pool);
2023-10-14 08:47:21 +00:00
entry->chunk.pool_entry = entry;
2023-10-12 16:52:05 +00:00
return &entry->chunk;
}
void tc_free_chunk(tc_world_s *world, tc_chunk_s *chunk)
{
tc_chunk_pool_s *pool = world->pool;
2023-10-14 08:47:21 +00:00
if(chunk->vao != 0)
{
glDeleteVertexArrays(1, &chunk->vertex_data);
chunk->vao = 0;
}
2023-10-13 06:00:53 +00:00
2023-10-14 08:47:21 +00:00
if(chunk->vertex_data != 0)
{
glDeleteBuffers(1, &chunk->vertex_data);
chunk->vertex_data = 0;
}
2023-10-13 06:00:53 +00:00
2023-10-14 08:47:21 +00:00
if(chunk->vertex_positions != NULL)
{
free(chunk->vertex_positions);
chunk->vertex_positions = NULL;
}
2023-10-13 06:00:53 +00:00
2023-10-14 08:47:21 +00:00
if(chunk->vertex_uvs != NULL)
{
free(chunk->vertex_uvs);
chunk->vertex_uvs = NULL;
}
2023-10-13 06:00:53 +00:00
2023-10-14 08:47:21 +00:00
chunk->num_vertices = 0;
chunk->position.x = 0;
chunk->position.y = 0;
chunk->position.z = 0;
memset(&chunk->blocks, 0x00, sizeof(uint32_t) * 32 * 32 * 32);
chunk->pool_entry->next = pool->first_free;
pool->first_free = chunk->pool_entry;
2023-10-12 16:52:05 +00:00
}