Dawn/src/dawn/world/chunk.c
2021-04-19 15:56:16 +10:00

84 lines
2.3 KiB
C

/**
* Copyright (c) 2021 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "chunk.h"
void chunkLoad(world_t *world, chunk_t *chunk, int32_t x, int32_t y, int32_t z){
int32_t tx, ty, tz, i;
tile_t *tile;
tiledef_t *tileDef;
tilesetdiv_t *div;
char *buffer, *seek, *current;
char fileName[128];
// Determine file name of the chunk.
fileName[0] = '\0';
strcat(fileName, world->assetWorldDirectory);
strcat(fileName, "chunks/");
strcat(fileName, "%d_%d_%d.txt");
sprintf(fileName, fileName, x, y, z);
// Load contents of chunk
buffer = assetStringLoad(fileName);
if(buffer == NULL) return;
seek = buffer;
// Determine the size of our primitive.
int32_t indiceCount = 0, verticeCount = 0;
for(i = 0; i < world->tileCount; i++) {
// Get the tile
tile = chunk->tiles + i;
// Now load from the buffer.
current = strtok_r(seek, ";", &seek);
tile->id = current[0] - CHUNK_TILE_LOAD_ASCII;
if(tile->id == TILE_NULL) continue;
tileDef = world->tilemap->tileDefinitions + tile->id;
if(tileDef->verticeCount == 0 || tileDef->indiceCount == 0) continue;
tile->verticeStart = verticeCount;
tile->indiceStart = indiceCount;
verticeCount += tileDef->verticeCount;
indiceCount += tileDef->indiceCount;
}
// Now we know how big the primitive needs to be!
free(buffer);
if(indiceCount > 0) {
chunk->primitive = primitiveCreate(verticeCount, indiceCount);
}
// For each tile
i = 0;
for(tx = 0; tx < CHUNK_WIDTH; tx++) {
for(ty = 0; ty < CHUNK_HEIGHT; ty++) {
for(tz = 0; tz < CHUNK_DEPTH; tz++) {
// Get tile for position...
tile = chunk->tiles + (i++);
// Should Chunk bother rendering?
if(tile->id == TILE_NULL) continue;
tileDef = world->tilemap->tileDefinitions + tile->id;
if(tileDef->verticeCount == 0 || tileDef->indiceCount == 0) continue;
// Render the tile's primitive
tileRender(world, chunk, tile, tileDef, tx, ty, tz);
}
}
}
}
void chunkUnload(world_t *world, chunk_t *chunk) {
// Unload the primitive
primitiveDispose(chunk->primitive);
chunk->primitive = NULL;
// Load chunks to zero. TODO: Necessary?
memset(chunk->tiles, TILE_NULL, world->count);
}