Techneck/code/source-c/meshize.c

147 lines
4.0 KiB
C

#include "world.h"
#include <stdlib.h>
#include <string.h>
float tc_block_vertices[108] =
{
// Front
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
// Back
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
// Left
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
// Right
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
// Top
-0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
// Bottom
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f
};
uint32_t tc_count_chunk_vertices(tc_chunk_s *chunk)
{
uint32_t num_vertices = 0;
uint32_t x_in_chunk = 0;
uint32_t y_in_chunk = 0;
uint32_t z_in_chunk = 0;
while(x_in_chunk < 32)
{
y_in_chunk = 0;
while(y_in_chunk < 32)
{
z_in_chunk = 0;
while(z_in_chunk < 32)
{
if(chunk->blocks[x_in_chunk][y_in_chunk][z_in_chunk].type_identifier > 0)
{
num_vertices += 36;
}
++z_in_chunk;
}
++y_in_chunk;
}
++x_in_chunk;
}
return num_vertices;
}
void tc_meshize_chunk(tc_chunk_s *chunk)
{
chunk->num_vertices = tc_count_chunk_vertices(chunk);
chunk->vertex_positions = malloc(sizeof(float) * 3 * chunk->num_vertices);
uint32_t vertex_index = 0;
float block_positions[36*3];
uint32_t x_in_chunk = 0;
uint32_t y_in_chunk = 0;
uint32_t z_in_chunk = 0;
while(x_in_chunk < 32)
{
y_in_chunk = 0;
while(y_in_chunk < 32)
{
z_in_chunk = 0;
while(z_in_chunk < 32)
{
if(chunk->blocks[x_in_chunk][y_in_chunk][z_in_chunk].type_identifier > 0)
{
memcpy(
block_positions,
tc_block_vertices,
sizeof(float) * 36 * 3
);
// Move the current block to where it is supposed to be
uint32_t vertex_of_block = 0;
while(vertex_of_block < 36)
{
uint32_t vertex_start = vertex_of_block * 3;
block_positions[vertex_start] +=
x_in_chunk;
block_positions[vertex_start + 1] +=
y_in_chunk;
block_positions[vertex_start + 2] +=
z_in_chunk;
++vertex_of_block;
}
memcpy(
&chunk->vertex_positions[vertex_index*3],
block_positions,
sizeof(float) * 36 * 3
);
vertex_index += 36;
}
++z_in_chunk;
}
++y_in_chunk;
}
++x_in_chunk;
}
}