From 9675503933d488736bb59f81337ab103fc0b2f57 Mon Sep 17 00:00:00 2001 From: davidovski Date: Tue, 11 Jul 2023 23:00:41 +0100 Subject: implement save on exit for editor --- src/tiledfile.c | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) (limited to 'src/tiledfile.c') diff --git a/src/tiledfile.c b/src/tiledfile.c index 64a1e0d..78f9c0e 100644 --- a/src/tiledfile.c +++ b/src/tiledfile.c @@ -1,6 +1,7 @@ #include #include #include +#include #include "tiledfile.h" @@ -17,7 +18,6 @@ void textureFromPixels(Texture2D *texOut, Color *pixels, int width, int height) }; *texOut = LoadTextureFromImage(checkedIm); - UnloadImage(checkedIm); } //! read rgba image from file @@ -28,6 +28,23 @@ void readrgba(Texture2D *loc, int width, int height, FILE *file) { } + +//! write a big endian bytes from file +int writeb(char * in, size_t noBytes, FILE * file) { + if (!is_bigendian()) { + int tmp; + // reverse byte order + for(int i = 0; i < noBytes/2; i++) { + tmp = in[i]; + in[i] = in[noBytes-i-1]; + in[noBytes-i-1] = tmp; + } + + } + + return fwrite(in, (size_t)1, (size_t) noBytes, file); +} + //! read a big endian bytes from file int readb(char * out, size_t noBytes, FILE * file) { if (!fread(out, (size_t)1, (size_t) noBytes, file)) @@ -88,7 +105,35 @@ TiledMap loadTiledMap(char * filename) { tiledMap.atlasData = malloc(atlasSizeBytes); fread(tiledMap.atlasData, atlasSizeBytes, (size_t) 1, file); + tiledMap.tileCount = tiledMap.atlasSize[0]*tiledMap.atlasSize[1] + 1; + fclose(file); return tiledMap; } +void saveTiledMap(char * filename, TiledMap tiledMap) { + FILE * file; + + if (!(file = fopen(filename, "wb"))) { + fprintf(stderr, "Failed to load %s\n", filename); + return; + } + size_t layoutSize = tiledMap.width*tiledMap.height; + size_t atlasSizeBytes = tiledMap.atlasSize[0]*tiledMap.tileSize*tiledMap.atlasSize[1]*tiledMap.tileSize*4; + + fwrite("TILEFILEv2", 10, 1, file); + + writeb((char *) &tiledMap.width, 4, file); + writeb((char *) &tiledMap.height, 4, file); + + fwrite(tiledMap.tilelayout, 1, layoutSize, file); + + writeb((char *) &tiledMap.tileSize, 4, file); + writeb((char *) &tiledMap.atlasSize[0], 4, file); + writeb((char *) &tiledMap.atlasSize[1], 4, file); + + fwrite(tiledMap.atlasData, 1, atlasSizeBytes, file); + + fclose(file); + fprintf(stderr, "Written tiledfiled to %s\n", filename); +} -- cgit v1.2.1