From c0579ee3ade78a9fc40ec33f38c7781bb3dba825 Mon Sep 17 00:00:00 2001 From: ZynoXelek Date: Wed, 3 Jul 2024 20:18:32 +0200 Subject: [PATCH 01/84] Use uint8 for colors in Python --- Python/mapGenerator.py | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index 030f0b8..853948f 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -42,14 +42,14 @@ def colorize(value: float, sea_level: float, min_value: float, max_value: float) #? Show red dots on zero values. Could be removed. if value == 0: - return (1., 0., 0.) + return (255, 0, 0) elif value <= sea_level: - blue = int((value - min_value) * 200. / (sea_level - min_value)) / 255 - o = 50 / 255 + blue = int((value - min_value) * 200. / (sea_level - min_value)) + o = 50 return (o, o, blue) else: - green = int((value - min_value) * 255. / (max_value - min_value)) / 255 - o = 50 / 255 + green = int((value - min_value) * 255. / (max_value - min_value)) + o = 50 return (o, green, o) @@ -154,11 +154,13 @@ def generateColorMap(self) -> None: max_alt = np.max(alt) min_alt = np.min(alt) - self.color_map = [[(0, 0, 0) for j in range(width)] for i in range(height)] + color_map = [[(0, 0, 0) for j in range(width)] for i in range(height)] for i in range(height): for j in range(width): - self.color_map[i][j] = CompleteMap.colorize(alt[i][j], self.sea_level, min_alt, max_alt) + color_map[i][j] = CompleteMap.colorize(alt[i][j], self.sea_level, min_alt, max_alt) + + self.color_map = np.array(color_map, dtype=np.uint8) @@ -420,8 +422,30 @@ def plotCompleteMap(complete_map: CompleteMap) -> None: y = np.linspace(0, map_size[1], chunk_size[1] * map_size[1]) x, y = np.meshgrid(x, y) + + if not type(complete_map.color_map) == np.ndarray: + print("Color map should be an numpy array.") + + + + + + if np.issubdtype(complete_map.color_map.dtype, np.integer): + cmap = complete_map.color_map.astype(np.float32) + cmap /= 255 + elif not np.issubdtype(complete_map.color_map.dtype, np.floating): + # WHAT ARE YOU TRYING TO DO ??? + print("Error : cmap can only be integers in [0, 255] or floating point values in [0., 1.]") + print("You tried to use : ", complete_map.color_map.dtype) + cmap = complete_map.color_map + else: + cmap = complete_map.color_map + + + + # print(np.shape(y), np.shape(x), np.shape(complete_map.sea_values), np.shape(complete_map.color_map)) - surf = ax3D.plot_surface(y, x, np.array(complete_map.sea_values), facecolors=np.array(complete_map.color_map)) + surf = ax3D.plot_surface(y, x, np.array(complete_map.sea_values), facecolors=np.array(cmap)) xylim = max(map_size[0], map_size[1]) ax3D.set_xlim(0, xylim) From 247b7d2b2f16adb5671a5cfeb97b972adc5c587d Mon Sep 17 00:00:00 2001 From: ZynoXelek Date: Thu, 4 Jul 2024 11:17:17 +0200 Subject: [PATCH 02/84] Use uint8 for colors in C --- C/headers/mapGenerator.h | 14 +++--- C/src/map.c | 4 +- C/src/mapGenerator.c | 92 +++++++--------------------------------- 3 files changed, 24 insertions(+), 86 deletions(-) diff --git a/C/headers/mapGenerator.h b/C/headers/mapGenerator.h index 01e3a71..0efff1c 100644 --- a/C/headers/mapGenerator.h +++ b/C/headers/mapGenerator.h @@ -20,13 +20,9 @@ */ struct color { - int red_int; /**< the red int value in [0, 255]*/ - int green_int; /**< the green int value in [0, 255]*/ - int blue_int; /**< the blue int value in [0, 255]*/ - - float red_float; /**< the red float value in [0, 1]*/ - float green_float; /**< the green float value in [0, 1]*/ - float blue_float; /**< the blue float value in [0, 1]*/ + __uint8_t red; /**< the red integer value in [0, 255] */ + __uint8_t green; /**< the green integer value in [0, 255]*/ + __uint8_t blue; /**< the blue integer value in [0, 255] */ }; typedef struct color color; @@ -242,14 +238,14 @@ void printCompleteMap(completeMap* completeMap); void writeSeaMapFile(completeMap* completeMap, char path[]); /** - * @brief TODO : Writes both color_map structures in two different files. + * @brief Writes the color_map in a file at the given path. * * @param width (int) : the width of the color map * @param height (int) : the height of the color map. * @param color_map (color**) : the array of pointers to the color structures representing the color map. * @param path (char[]) : the path where the file shall be written. */ -void writeColorMapFiles(int width, int height, color* color_map[width * height], char path[]); +void writeColorMapFile(int width, int height, color* color_map[width * height], char path[]); /** * @brief Writes every required files to save the completeMap structure. diff --git a/C/src/map.c b/C/src/map.c index 14347fc..23f7fdf 100644 --- a/C/src/map.c +++ b/C/src/map.c @@ -196,9 +196,11 @@ map* addMeanAltitude(map* p_map, unsigned int display_loading) } } - display_loading-=2; if (display_loading != 0) { + display_loading-=2; + + double total_time = (double) (clock() - start_time)/CLOCKS_PER_SEC; char final_string[200] = ""; diff --git a/C/src/mapGenerator.c b/C/src/mapGenerator.c index cd6ce87..364d5a0 100644 --- a/C/src/mapGenerator.c +++ b/C/src/mapGenerator.c @@ -184,33 +184,21 @@ color* colorize(double value, double sea_level, double min_value, double max_val //? Show red dots on zero values. Could be removed. if (value == 0) { - new_color->red_int = 255; - new_color->green_int = 0; - new_color->blue_int = 0; - - new_color->red_float = 1.; - new_color->green_float = 0; - new_color->blue_float = 0; + new_color->red = 255; + new_color->green = 0; + new_color->blue = 0; } else if (value <= sea_level) { - new_color->red_int = 50; - new_color->green_int = 50; - new_color->blue_int = s; - - new_color->red_float = 1./255 * 50; - new_color->green_float = 1./255 * 50; - new_color->blue_float = 1./255 * s; + new_color->red = 50; + new_color->green = 50; + new_color->blue = s; } else { - new_color->red_int = 50; - new_color->green_int = i; - new_color->blue_int = 50; - - new_color->red_float = 1./255 * 50; - new_color->green_float = 1./255 * i; - new_color->blue_float = 1./255 * 50; + new_color->red = 50; + new_color->green = i; + new_color->blue = 50; } return new_color; @@ -565,7 +553,7 @@ void writeSeaMapFile(completeMap* completeMap, char path[]) -void writeColorIntMapFile(color** color_map, int width, int height, char path[]) +void writeColorMapFile(int width, int height, color* color_map[width * height], char path[]) { FILE* f = NULL; @@ -587,53 +575,11 @@ void writeColorIntMapFile(color** color_map, int width, int height, char path[]) if (j != width - 1) { - fprintf(f, "(%d,%d,%d)\t", color->red_int, color->green_int, color->blue_int); + fprintf(f, "(%3d,%3d,%3d)\t", color->red, color->green, color->blue); } else { - fprintf(f, "(%d,%d,%d)\n", color->red_int, color->green_int, color->blue_int); - } - } - } - - fclose(f); - } - else - { - printf("%sERROR : could not open file in writing mode at path '%s'%s\n", RED_COLOR, path, DEFAULT_COLOR); - return; - } -} - - - -void writeColorFloatMapFile(color** color_map, int width, int height, char path[]) -{ - FILE* f = NULL; - - f = fopen(path, "w"); - - if (f != NULL) - { - fprintf(f, "Color Float Map\n"); - - // Writing the parameters - fprintf(f, "width=%d\nheight=%d\n", width, height); - - // Writing the vectors - for (int i = 0; i < height; i++) - { - for (int j = 0; j < width; j++) - { - color* color = color_map[j + i * width]; - - if (j != width - 1) - { - fprintf(f, "(%.4f,%.4f,%.4f)\t", color->red_float, color->green_float, color->blue_float); - } - else - { - fprintf(f, "(%.4f,%.4f,%.4f)\n", color->red_float, color->green_float, color->blue_float); + fprintf(f, "(%3d,%3d,%3d)\n", color->red, color->green, color->blue); } } } @@ -668,16 +614,10 @@ void writeCompleteMapFiles(completeMap* complete_map, char folder_path[]) writeSeaMapFile(complete_map, sea_map_path); - // Generates the color int map file - char color_int_path[200] = ""; - snprintf(color_int_path, sizeof(color_int_path), "%scolor_int_map.txt", folder_path); - writeColorIntMapFile(complete_map->color_map, complete_map->width, complete_map->height, color_int_path); - - - // Generates the color float map file - char color_float_path[200] = ""; - snprintf(color_float_path, sizeof(color_float_path), "%scolor_float_map.txt", folder_path); - writeColorFloatMapFile(complete_map->color_map, complete_map->width, complete_map->height, color_float_path); + // Generates the color map file + char color_path[200] = ""; + snprintf(color_path, sizeof(color_path), "%scolor_map.txt", folder_path); + writeColorMapFile(complete_map->width, complete_map->height, complete_map->color_map, color_path); } From 440f1075e227629c8eef327478de4fc6815e9627 Mon Sep 17 00:00:00 2001 From: ZynoXelek Date: Thu, 4 Jul 2024 11:22:42 +0200 Subject: [PATCH 03/84] Adapt old complete map loader to colors as int --- C/src/mapGenerator.c | 2 +- Python/main.py | 4 ++-- Python/old_mapGenerator.py | 18 +++++++++--------- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/C/src/mapGenerator.c b/C/src/mapGenerator.c index 364d5a0..c545808 100644 --- a/C/src/mapGenerator.c +++ b/C/src/mapGenerator.c @@ -561,7 +561,7 @@ void writeColorMapFile(int width, int height, color* color_map[width * height], if (f != NULL) { - fprintf(f, "Color Int Map\n"); + fprintf(f, "Color Map\n"); // Writing the parameters fprintf(f, "width=%d\nheight=%d\n", width, height); diff --git a/Python/main.py b/Python/main.py index 4f407b6..bcf892d 100644 --- a/Python/main.py +++ b/Python/main.py @@ -6,8 +6,8 @@ from old_mapGenerator import mapGenerator as old_MapGenerator from mapGenerator import MapGenerator -LOAD = False -GENERATE = True +LOAD = True +GENERATE = False if LOAD: path_to_load = "../saves/completeMap_test/" diff --git a/Python/old_mapGenerator.py b/Python/old_mapGenerator.py index 1697b14..9ae6d37 100644 --- a/Python/old_mapGenerator.py +++ b/Python/old_mapGenerator.py @@ -584,7 +584,7 @@ def loadColorMap(color_map_path : str): return # Description line - if "Color Float Map" not in lines[0]: + if "Color Map" not in lines[0]: print(RED_COLOR + "Color float map does not contain the correct first line" + DEFAULT_COLOR) # Parameters @@ -627,28 +627,28 @@ def loadColorMap(color_map_path : str): vector_parts = parts[j].split(",") try: - r = float(vector_parts[0]) + r = int(vector_parts[0]) except: - print(RED_COLOR + "Could not convert '{}' into a float for red value at indexes i={} j={} !".format(vector_parts[0], i, j) + DEFAULT_COLOR) + print(RED_COLOR + "Could not convert '{}' into an int for red value at indexes i={} j={} !".format(vector_parts[0], i, j) + DEFAULT_COLOR) return try: - g = float(vector_parts[1]) + g = int(vector_parts[1]) except: - print(RED_COLOR + "Could not convert '{}' into a float for green value at indexes i={} j={} !".format(vector_parts[1], i, j) + DEFAULT_COLOR) + print(RED_COLOR + "Could not convert '{}' into an int for green value at indexes i={} j={} !".format(vector_parts[1], i, j) + DEFAULT_COLOR) return try: - b = float(vector_parts[2]) + b = int(vector_parts[2]) except: - print(RED_COLOR + "Could not convert '{}' into a float for blue value at indexes i={} j={} !".format(vector_parts[2], i, j) + DEFAULT_COLOR) + print(RED_COLOR + "Could not convert '{}' into an int for blue value at indexes i={} j={} !".format(vector_parts[2], i, j) + DEFAULT_COLOR) return color_map[i][j] = (r, g, b) - return np.array(color_map) + return np.array(color_map)/255 else: raise FileNotFoundError(RED_COLOR + "File '{}' was not found!".format(color_map_path) + DEFAULT_COLOR) @@ -679,7 +679,7 @@ def loadCompleteMap(folder_path : str): if os.path.isdir(folder_path): sea_map_path = os.path.join(folder_path, "sea_map.txt") - color_map_path = os.path.join(folder_path, "color_float_map.txt") + color_map_path = os.path.join(folder_path, "color_map.txt") sea_map, map_width_in_points, map_height_in_points, sea_level, map_width_in_chunks, map_height_in_chunks = mapGenerator.loadSeaMap(sea_map_path) From c8f904829506be75f775a36962d354a68041702c Mon Sep 17 00:00:00 2001 From: ZynoXelek Date: Thu, 4 Jul 2024 15:44:59 +0200 Subject: [PATCH 04/84] Add main.c to generate a custom map with user inputs (Lacks seed and saving path inputs) --- C/Makefile | 4 +- C/src/main.c | 465 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 468 insertions(+), 1 deletion(-) create mode 100644 C/src/main.c diff --git a/C/Makefile b/C/Makefile index f6aa5c2..fdb50f2 100644 --- a/C/Makefile +++ b/C/Makefile @@ -47,8 +47,10 @@ $(COMP)%.o : $(SRC)%.c $(CC) -c $< -o $@ +# Main -------------------------------------- - +main: $(COMP)main.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o + $(CC) $^ -o $(BIN)$@ $(LFLAGS) # Tests ------------------------------------- diff --git a/C/src/main.c b/C/src/main.c new file mode 100644 index 0000000..8775363 --- /dev/null +++ b/C/src/main.c @@ -0,0 +1,465 @@ +/** + * @file main.c + * @author Zyno + * @brief main code to generate a new complete map + * @version 0.1 + * @date 2024-07-04 + * + */ + +#include +#include + +#include "loadingBar.h" +#include "mapGenerator.h" + + +#define INPUT_MAX_SIZE 100 + + + +int main(int argc, char* argv[argc]) +{ + //? --- Initialisation of the different variables ----------------------------------------------------------------------------------------------- + + // Can be set in command line + int map_width = 0; + int map_height = 0; + int nb_layers = 0; + + double sea_level = 0.; + int sea_level_affected = 0; // boolean + + //? --- Manage command line inputs : ./main ---------------------------------------------------- + + if (argc > 1) + { + int temp = 0; + int nb_associated = sscanf(argv[1], "%d", &temp); + + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : input '%s' could not be cast as an integer for map_width /!\\%s\n", RED_COLOR, argv[1], DEFAULT_COLOR); + } + else if (temp <= 0) + { + printf("%s/!\\ Value Error : map_width should be a strictly positive integer but %d was given /!\\%s\n", RED_COLOR, temp, DEFAULT_COLOR); + } + else + { + map_width = temp; + } + } + if (argc > 2) + { + int temp = 0; + int nb_associated = sscanf(argv[2], "%d", &temp); + + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : input '%s' could not be cast as an integer for map_height /!\\%s\n", RED_COLOR, argv[2], DEFAULT_COLOR); + } + else if (temp <= 0) + { + printf("%s/!\\ Value Error : map_height should be a strictly positive integer but %d was given /!\\%s\n", RED_COLOR, temp, DEFAULT_COLOR); + } + else + { + map_height = temp; + } + } + if (argc > 3) + { + int temp = 0; + int nb_associated = sscanf(argv[3], "%d", &temp); + + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : input '%s' could not be cast as an integer for nb_layers /!\\%s\n", RED_COLOR, argv[3], DEFAULT_COLOR); + } + else if (temp <= 0) + { + printf("%s/!\\ Value Error : nb_layers should be a strictly positive integer but %d was given /!\\%s\n", RED_COLOR, temp, DEFAULT_COLOR); + } + else + { + nb_layers = temp; + } + } + if (argc > 4) + { + double temp = 0.; + int nb_associated = sscanf(argv[4], "%lf", &temp); + + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : input '%s' could not be cast as a double for sea_level /!\\%s\n", RED_COLOR, argv[4], DEFAULT_COLOR); + } + else + { + sea_level = temp; + sea_level_affected = 1; + } + } + if (argc > 5) + { + printf("%s/!\\ Warning : the remaining inputs will not be treated : /!\\%s\n", YELLOW_COLOR, DEFAULT_COLOR); + for (int i = 5; i < argc; i++) + { + if (i < argc - 1) + { + printf("'%s', ", argv[i]); + } + else + { + printf("'%s'\n", argv[i]); + } + } + } + + + + + + //? --- Manage missing values with prompt inputs (will have to manage layers whatsoever) -------------------------------------------------------- + + if ( !(map_width > 0) ) + { + int temp = 0; + int nb_associated = 0; + char line[INPUT_MAX_SIZE] = ""; + + while ( !(temp > 0) ) + { + printf("Please enter a valid map_width value for the map generation. It should be > 0. Your input : "); + + fgets(line, INPUT_MAX_SIZE, stdin); + + nb_associated = sscanf(line, " %d", &temp); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as an integer value. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + else if (temp <= 0) + { + printf("%s/!\\ Value Error : map_width should be a strictly positive integer but %d was given /!\\%s\n", RED_COLOR, temp, DEFAULT_COLOR); + } + } + + map_width = temp; + } + printf("%sMap width is set to %d%s\n\n", GREEN_COLOR, map_width, DEFAULT_COLOR); + + + if ( !(map_height > 0) ) + { + int temp = 0; + int nb_associated = 0; + char line[INPUT_MAX_SIZE] = ""; + + while ( !(temp > 0) ) + { + printf("Please enter a valid map_height value for the map generation. It should be > 0. Your input : "); + + fgets(line, INPUT_MAX_SIZE, stdin); + + nb_associated = sscanf(line, " %d", &temp); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as an integer value. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + else if (temp <= 0) + { + printf("%s/!\\ Value Error : map_height should be a strictly positive integer but %d was given /!\\%s\n", RED_COLOR, temp, DEFAULT_COLOR); + } + } + + map_height = temp; + } + printf("%sMap height is set to %d%s\n\n", GREEN_COLOR, map_height, DEFAULT_COLOR); + + + if ( !(nb_layers > 0) ) + { + int temp = 0; + int nb_associated = 0; + char line[INPUT_MAX_SIZE] = ""; + + while ( !(temp > 0) ) + { + printf("Please enter a valid nb_layers value for the map generation. It should be > 0. Your input : "); + + fgets(line, INPUT_MAX_SIZE, stdin); + + nb_associated = sscanf(line, " %d", &temp); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as an integer value. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + else if (temp <= 0) + { + printf("%s/!\\ Value Error : nb_layers should be a strictly positive integer but %d was given /!\\%s\n", RED_COLOR, temp, DEFAULT_COLOR); + } + } + + nb_layers = temp; + } + printf("%sNumber of layers is set to %d%s\n\n", GREEN_COLOR, nb_layers, DEFAULT_COLOR); + + + + + //? --- Manage layers parameters ---------------------------------------------------------------------------------------------------------------- + + + // Initialisation of the missing variables + + int grid_dimensions[nb_layers]; + double layers_factors[nb_layers]; + + for (int i=0; i < nb_layers; i++) + { + printf("Setting up the layer n°%d/%d...\n", i+1, nb_layers); + + int nb_associated = 0; + int temp_i = 0; + double temp_d = 0.; + char line[INPUT_MAX_SIZE] = ""; + + while ( !(temp_i > 0) ) + { + printf("Please enter a valid grid dimension value for gradientGrid %d/%d. It should be > 0. Your input : ", i+1, nb_layers); + + fgets(line, INPUT_MAX_SIZE, stdin); + + nb_associated = sscanf(line, " %d", &temp_i); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as an integer value. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + else if (temp_i <= 0) + { + printf("%s/!\\ Value Error : a grid dimension should be a strictly positive integer but %d was given /!\\%s\n", RED_COLOR, temp_i, DEFAULT_COLOR); + } + } + + grid_dimensions[i] = temp_i; + printf("Grid dimensions %d/%d set to %d\n", i+1, nb_layers, grid_dimensions[i]); + + + + + // Reset tracking parameters + nb_associated = 0; + snprintf(line, sizeof(line), ""); + + while ( (nb_associated == 0) ) + { + printf("Please enter a valid layer factor value for layer %d/%d. It should be a double value. Your input : ", i+1, nb_layers); + + fgets(line, INPUT_MAX_SIZE, stdin); + + nb_associated = sscanf(line, " %lf", &temp_d); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as a double value. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + } + + layers_factors[i] = temp_d; + printf("Layer factor %d/%d set to %lf\n\n", i+1, nb_layers, layers_factors[i]); + } + + + + // Summary of the values set + + printf("Gradient grid sizes (-1) are finally set to the following values :\n"); + for (int i = 0; i < nb_layers; i++) + { + if (i == 0) + { + printf("%s{%d, ", GREEN_COLOR, grid_dimensions[i]); + } + else if (i < nb_layers - 1) + { + printf("%d, ", grid_dimensions[i]); + } + else + { + printf("%d}%s\n", grid_dimensions[i], DEFAULT_COLOR); + } + } + int final_size = lcmOfArray(nb_layers, grid_dimensions); + printf("It will lead to square chunks of sizes %s%d%s\n\n", GREEN_COLOR, final_size, DEFAULT_COLOR); + + + + + printf("Layers factors are finally set to the following values :\n"); + for (int i = 0; i < nb_layers; i++) + { + if (i == 0) + { + printf("%s{%lf, ", GREEN_COLOR, layers_factors[i]); + } + else if (i < nb_layers - 1) + { + printf("%lf, ", layers_factors[i]); + } + else + { + printf("%lf}%s\n\n", layers_factors[i], DEFAULT_COLOR); + } + } + + + + //? --- Manage final missing parameter : sea_level ---------------------------------------------------------------------------------------------- + + if ( (sea_level_affected != 1) ) + { + int nb_associated = 0; + char line[INPUT_MAX_SIZE] = ""; + + while ( sea_level_affected != 1 ) + { + printf("Please enter a valid sea_level value for the map generation. It should be a double value. Your input : "); + + fgets(line, INPUT_MAX_SIZE, stdin); + + nb_associated = sscanf(line, " %lf", &sea_level); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as a double value. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + else + { + sea_level_affected = 1; + } + } + } + printf("%sSea level is set to %lf%s\n\n", GREEN_COLOR, sea_level, DEFAULT_COLOR); + + + + + + //? --- Generation ------------------------------------------------------------------------------------------------------------------------------ + + // Required memory space + long int mem_space_by_chunk = sizeof(chunk) + final_size * final_size * sizeof(double) + nb_layers * (sizeof(double) + sizeof(layer*)) + + sizeof(layer) + final_size * final_size * sizeof(double); + + for (int i = 0; i < nb_layers; i++) + { + mem_space_by_chunk += sizeof(gradientGrid) + grid_dimensions[i] * grid_dimensions[i] * sizeof(vector); + } + + long int total_memory_space_used = sizeof(completeMap) + map_width * final_size * map_height * final_size * (sizeof(double) + sizeof(color*) + sizeof(color)) + + sizeof(map) + map_width * final_size * map_height * final_size * sizeof(double) + + map_width * map_height * (sizeof(chunk*) + mem_space_by_chunk); + + printf("The complete memory space used will be around %s%ld bytes%s.\n", BLUE_COLOR, total_memory_space_used, DEFAULT_COLOR); + + + int user_input = -1; + int temp = -1; + int nb_associated = 0; + char line[INPUT_MAX_SIZE] = ""; + + while ( temp != 0 && temp != 1 ) + { + printf("Do you want to continue ? (1 for Yes, 0 for No) -> "); + + fgets(line, INPUT_MAX_SIZE, stdin); + + nb_associated = sscanf(line, " %d", &temp); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as an integer value. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + else if (temp != 0 && temp != 1) + { + printf("%s/!\\ Value Error : please enter 0 to cancel or 1 to proceed with the generation. /!\\%s\n", RED_COLOR, DEFAULT_COLOR); + } + } + + user_input = temp; + printf("\n"); + + if (user_input != 1) + { + printf("The process was cancelled.\n"); + return 0; // The process was correctly cancelled. + } + + + + // Whether to display loading bars or not + + int display_loading = -1; // boolean + + // Reset tracking parameters + temp = -1; + nb_associated = 0; + snprintf(line, sizeof(line), ""); + + while ( temp != 0 && temp != 1 ) + { + printf("Do you want to print loading bars during the generation ? (1 for Yes, 0 for No) -> "); + + fgets(line, INPUT_MAX_SIZE, stdin); + + nb_associated = sscanf(line, " %d", &temp); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as an integer value. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + else if (temp != 0 && temp != 1) + { + printf("%s/!\\ Value Error : please enter 0 to hide loading bars or 1 to show them. /!\\%s\n", RED_COLOR, DEFAULT_COLOR); + } + } + + display_loading = temp; + + + // TODO : Ask for a seed input + + + printf("Generating a complete map with given parameters...\n"); + clock_t start_time = clock(); + + + completeMap* new_complete_map = fullGen(nb_layers, grid_dimensions, layers_factors, map_width, map_height, sea_level, display_loading); + printf("Generation complete!\n"); + + double total_time = (double) (clock() - start_time) / CLOCKS_PER_SEC; + printf("The whole map generation took a total of %lf second(s) in CPU time\n", total_time); + + + // TODO : Ask for a path to save the map + + + //? Comment this if you don't want to save it in a file. + //! WARNING : ../saves/ the folder must exist for it to work properly + printf("File creation...\n"); + start_time = clock(); + + char folder_path[200] = "../saves/completeMap_test/"; + + writeCompleteMapFiles(new_complete_map, folder_path); + + total_time = (double) (clock() - start_time) / CLOCKS_PER_SEC; + printf("The map saving took a total of %lf second(s) in CPU time\n", total_time); + + + + printf("Deallocating now...\n"); + freeCompleteMap(new_complete_map); + + + + return 0; +} \ No newline at end of file From 2586e7b67dfeec7ff8974f478daab99ca3f6a4b3 Mon Sep 17 00:00:00 2001 From: ZynoXelek Date: Sun, 7 Jul 2024 13:03:18 +0200 Subject: [PATCH 05/84] Remove altitude storage in layer after chunk generation --- Python/chunk.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Python/chunk.py b/Python/chunk.py index 6057b0b..926f250 100644 --- a/Python/chunk.py +++ b/Python/chunk.py @@ -17,6 +17,9 @@ class Chunk: Chunk : ------------- The Chunk class used to generate an altitude map by superposition of multiple layers. + + Note : + Layers' altitude values are then free'd. """ @@ -427,6 +430,10 @@ def regenerate(self) -> None: self.altitude /= factor_sum self.base_altitude = Chunk.generateBaseAltitude() + + for i in range(len_fac): + layer = self.layers[i] + layer.altitude = None # Free memory now From 27dc019f092c828491dc713dac7db59ab766ee21 Mon Sep 17 00:00:00 2001 From: ZynoXelek Date: Sun, 7 Jul 2024 13:03:47 +0200 Subject: [PATCH 06/84] Remove map altitude storage and add getFullMap() method --- Python/main.py | 4 +-- Python/map.py | 57 +++++++++++++++++++++++++++++------------- Python/mapGenerator.py | 16 +++++++----- 3 files changed, 51 insertions(+), 26 deletions(-) diff --git a/Python/main.py b/Python/main.py index bcf892d..4f407b6 100644 --- a/Python/main.py +++ b/Python/main.py @@ -6,8 +6,8 @@ from old_mapGenerator import mapGenerator as old_MapGenerator from mapGenerator import MapGenerator -LOAD = True -GENERATE = False +LOAD = False +GENERATE = True if LOAD: path_to_load = "../saves/completeMap_test/" diff --git a/Python/map.py b/Python/map.py index a2a9ddd..8b448a9 100644 --- a/Python/map.py +++ b/Python/map.py @@ -17,6 +17,9 @@ class Map: Map : ------------- The Map class used to generate large terrain by gathering chunks. + + Note : + A Map structure does not contain the complete map array. Use method `getFullMap()` on a map structure to get it. """ @@ -175,7 +178,7 @@ def __init__(self, map_width: int, map_height: int, chunks: list[list[Chunk]], v self.chunk_width = 0 self.chunk_height = 0 - self.altitude = None + # self.altitude = None self.chunks = None self.virtual_chunks = None @@ -210,14 +213,6 @@ def __str__(self) -> str: final_str = "-----------------------------------------\n" final_str += "Map of {} x {} chunks of dimension {} x {}\n"\ .format(self.map_width, self.map_height, self.chunk_width, self.chunk_height) - # final_str += "\nAltitude values :\n" - # for i in range(self.height): - - # for j in range(self.width): - # alt = self.altitude[i, j] - # final_str += Layer.ALT_PRINTING_FORMAT.format(alt) - - # final_str += "\n" final_str += "-----------------------------------------\n" return final_str @@ -234,17 +229,17 @@ def regenerate(self) -> None: #* -------------- Verifications : End -------------- - width = self.map_width * self.chunk_width - height = self.map_height * self.chunk_height + # width = self.map_width * self.chunk_width + # height = self.map_height * self.chunk_height - self.altitude = np.zeros((height, width)) + # self.altitude = np.zeros((height, width)) - # First copies altitudes from chunks - for i in range(height): - for j in range(width): + # # First copies altitudes from chunks + # for i in range(height): + # for j in range(width): - current_chunk = self.chunks[i//self.chunk_height][j//self.chunk_width] - self.altitude[i][j] = current_chunk.altitude[i%self.chunk_height][j%self.chunk_width] + # current_chunk = self.chunks[i//self.chunk_height][j//self.chunk_width] + # self.altitude[i][j] = current_chunk.altitude[i%self.chunk_height][j%self.chunk_width] self.applyMeanAltitude() @@ -296,10 +291,36 @@ def applyMeanAltitude(self) -> None: alt_i = pi + math.floor((i-0.5)*chunk_height) alt_j = pj + math.floor((j-0.5)*chunk_width) + if alt_i < 0 or alt_j < 0: print("Warning alt i and j are : ", alt_i, alt_j) - self.altitude[alt_i][alt_j] += alt + current_chunk = self.chunks[alt_i//chunk_height][alt_j//chunk_width] + + + current_chunk.altitude[alt_i%chunk_height][alt_j%chunk_width] += alt + + + + def getFullMap(self) -> np.ndarray: + """Get the full map altitude from the contained chunks. + + Returns: + `np.ndarray`: the complete altitude array from the map. + """ + + width = self.map_width * self.chunk_width + height = self.map_height * self.chunk_height + + altitude = np.zeros((height, width)) + + for i in range(height): + for j in range(width): + + current_chunk = self.chunks[i//self.chunk_height][j//self.chunk_width] + altitude[i][j] = current_chunk.altitude[i%self.chunk_height][j%self.chunk_width] + + return altitude diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index 853948f..5270ee2 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -129,10 +129,12 @@ def __init__(self, map: Map, sea_level: float) -> None: self.map = map self.sea_level = sea_level - if type(map.altitude) == np.ndarray: - alt = map.altitude + alt = self.map.getFullMap() + + if type(alt) == np.ndarray: + pass else: - alt = np.array(map.altitude) + alt = np.array(alt) self.sea_values = np.where(alt >= sea_level, alt, sea_level) self.generateColorMap() @@ -146,10 +148,12 @@ def generateColorMap(self) -> None: width = self.map.map_width * self.map.chunk_width height = self.map.map_height * self.map.chunk_height - if type(self.map.altitude) == np.ndarray: - alt = self.map.altitude + alt = self.map.getFullMap() + + if type(alt) == np.ndarray: + pass else: - alt = np.array(self.map.altitude) + alt = np.array(alt) max_alt = np.max(alt) min_alt = np.min(alt) From 210a2b4034eda98607557e3018d4f88572bc67f4 Mon Sep 17 00:00:00 2001 From: ZynoXelek Date: Sun, 7 Jul 2024 19:36:50 +0200 Subject: [PATCH 07/84] Frees layers altitude values after chunk generation (C) --- C/headers/chunk.h | 9 +++++++++ C/src/chunk.c | 20 ++++++++++++++++++-- C/src/layer.c | 5 ++++- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/C/headers/chunk.h b/C/headers/chunk.h index c899e8c..75c12ad 100644 --- a/C/headers/chunk.h +++ b/C/headers/chunk.h @@ -100,6 +100,13 @@ chunk* initChunk(int width, int height, int number_of_layers, double layers_fact +/** + * @brief Generates a new base altitude to be set to a chunk. + * + * @return double : the base_altitude value. + */ +double generateBaseAltitude(); + /** * @brief Regenerates the given chunk final altitude values from its layers and layers factors. * @@ -107,6 +114,8 @@ chunk* initChunk(int width, int height, int number_of_layers, double layers_fact * @param display_loading (unsigned int) : the given value defines the behaviour. * * If `0` the loading bars won't be printed. * * If `> 0` the loading bars will be printed with a number of indent equal to `display_loading - 1`. + * + * @note each layer will see its values free'd at this point. They can still be regenerated if needed using the dedicated function. */ void regenerateChunk(chunk* chunk, unsigned int display_loading); diff --git a/C/src/chunk.c b/C/src/chunk.c index 5d6a6b4..0db3dba 100644 --- a/C/src/chunk.c +++ b/C/src/chunk.c @@ -86,6 +86,13 @@ chunk* initChunk(int width, int height, int number_of_layers, double layers_fact +double generateBaseAltitude() +{ + return -0.5+2*rand()*1./RAND_MAX; +} + + + void regenerateChunk(chunk* chunk, unsigned int display_loading) { clock_t start_time = clock(); @@ -137,7 +144,16 @@ void regenerateChunk(chunk* chunk, unsigned int display_loading) *value /= divisor; } } - chunk->base_altitude=-0.5+2*rand()*1./RAND_MAX; + + chunk->base_altitude=generateBaseAltitude(); + + // Frees layer altitude arrays + + for (int k = 0; k < nblayers; k++) + { + free(layers[k]->values); + layers[k]->values = NULL; + } } @@ -281,7 +297,7 @@ chunk* newVirtualChunk(int number_of_layers, int gradGrids_width[number_of_layer new_chunk->layers = NULL; - new_chunk->base_altitude=-0.5+2*rand()*1./RAND_MAX; + new_chunk->base_altitude=generateBaseAltitude(); return new_chunk; } diff --git a/C/src/layer.c b/C/src/layer.c index d01e153..f6f5c5f 100644 --- a/C/src/layer.c +++ b/C/src/layer.c @@ -103,7 +103,10 @@ double* getLayerValue(layer* layer, int width_idx, int height_idx) return NULL; } - layer_value = (layer->values) + height_idx * width + width_idx; + if (layer->values != NULL) + { + layer_value = (layer->values) + height_idx * width + width_idx; + } } return layer_value; From 2072214ce0e5ea969cec657adbb17ad12461cac5 Mon Sep 17 00:00:00 2001 From: ZynoXelek Date: Sun, 7 Jul 2024 19:39:20 +0200 Subject: [PATCH 08/84] Removes altitude array in map structure. Chunks are directly modified. --- C/headers/map.h | 20 +++++++-- C/src/map.c | 111 +++++++++++++++++++++++++++++++----------------- 2 files changed, 87 insertions(+), 44 deletions(-) diff --git a/C/headers/map.h b/C/headers/map.h index 4401471..cfd2b86 100644 --- a/C/headers/map.h +++ b/C/headers/map.h @@ -31,7 +31,7 @@ struct map int chunk_width; /**< the width of each chunk*/ int chunk_height; /**< the height of each chunk*/ - double* map_values; /**< the array of altitude values. Its size is `map_width * chunk_width` x `map_height * chunk_height`*/ + // double* map_values; /**< the array of altitude values. Its size is `map_width * chunk_width` x `map_height * chunk_height`*/ }; typedef struct map map; @@ -39,12 +39,13 @@ typedef struct map map; // ----- Functions ----- /** - * @brief Get the pointer to the altitude value at given width and height indexes in the given map structure + * @brief Get the pointer to the altitude value at given width and height indexes in the given map structure. + * This points to the altitude value in the correct chunk. * * @param map (map*) : the pointer to the map structure. * @param width_idx (int) : the width index of the wanted value. * @param height_idx (int) : the height index of the wanted value. - * @return double* : the pointer to the map altitude value. + * @return double* : the pointer to the map altitude value in the correct chunk structure. */ double* getMapValue(map* map, int width_idx, int height_idx); @@ -72,6 +73,17 @@ chunk* getVirtualChunk(map* map, int width_idx, int height_idx); +/** + * @brief Get the full map altitude values built from concatenation of each chunk altitude value. + * + * @param map (map*) : the pointer to the map to get the full map altitude from. + * @return double* : the pointer to the full altitude array. It is of size + * `map.map_width * map.chunk_width * map.map_height * map.chunk_height`. + */ +double* getFullMap(map* map); + + + /** * @brief Interpolates the given values in 2d in order to get a smooth 2d interpolation. * @@ -86,7 +98,7 @@ chunk* getVirtualChunk(map* map, int width_idx, int height_idx); double interpolate2D(double a1, double a2, double a3, double a4, double x, double y); /** - * @brief Modifies the given map to process each chunk's base altitude and adapt the final altitude values of the given map. + * @brief Modifies the chunks of the given map to process each chunk's base altitude and adapt the final altitude values of each chunk. * * @param p_map (map*) : the pointer to the original untreated map. * @param display_loading (unsigned int) : the given value defines the behaviour. diff --git a/C/src/map.c b/C/src/map.c index 23f7fdf..923df87 100644 --- a/C/src/map.c +++ b/C/src/map.c @@ -38,7 +38,10 @@ double* getMapValue(map* map, int width_idx, int height_idx) return NULL; } - map_value = (map->map_values) + height_idx * width + width_idx; + + chunk* current_chunk = getChunk(map, width_idx/map->chunk_width, height_idx/map->chunk_height); + + map_value = getChunkValue(current_chunk, width_idx%map->chunk_width, height_idx%map->chunk_height); } return map_value; @@ -85,6 +88,33 @@ chunk* getVirtualChunk(map* map, int width_idx, int height_idx) +double* getFullMap(map* map) +{ + double* altitude = NULL; + + if (map != NULL) + { + int width = map->map_width * map->chunk_width; + int height = map->map_height * map->chunk_height; + + altitude = calloc(width * height, sizeof(double)); + + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width; j++) + { + altitude[i*width + j] = *getMapValue(map, j, i); + } + } + } + + return altitude; +} + + + + + double interpolate2D(double a1, double a2, double a3, double a4, double x, double y) { return a1 + (a2 - a1) * smoothstep(x) + (a3 - a1) * smoothstep(y) + (a1 + a4 - a2 - a3) * smoothstep(x) * smoothstep(y); @@ -159,18 +189,19 @@ map* addMeanAltitude(map* p_map, unsigned int display_loading) clock_t start_adding_time = clock(); - for (int i=0; i=chunk_width*0.5) && (j!=0 || pj>=chunk_height*0.5)) @@ -223,7 +254,7 @@ map* addMeanAltitude(map* p_map, unsigned int display_loading) map* newMapFromChunks(int map_width, int map_height, chunk* chunks[map_width * map_height], chunk* virtual_chunks[(map_height+2+map_width+2)*2-4], unsigned int display_loading) { - clock_t start_time = clock(); + // clock_t start_time = clock(); if (chunks != NULL && map_width > 0 && map_height > 0) { @@ -262,32 +293,32 @@ map* newMapFromChunks(int map_width, int map_height, chunk* chunks[map_width * m new_map->chunk_height = chunk_height; - int width = map_width * chunk_width; - int height = map_height * chunk_height; - double* map_values = calloc(width * height, sizeof(double)); + // int width = map_width * chunk_width; + // int height = map_height * chunk_height; + // double* map_values = calloc(width * height, sizeof(double)); - new_map->map_values = map_values; + // new_map->map_values = map_values; - // Copy the correct altitude values - for (int i = 0; i < height; i++) - { - for (int j = 0; j < width; j++) - { - double* value = getMapValue(new_map, j, i); - chunk* current_chunk = getChunk(new_map, j/chunk_width, i/chunk_height); + // // Copy the correct altitude values + // for (int i = 0; i < height; i++) + // { + // for (int j = 0; j < width; j++) + // { + // double* value = getMapValue(new_map, j, i); + // chunk* current_chunk = getChunk(new_map, j/chunk_width, i/chunk_height); - *value = *getChunkValue(current_chunk, j%chunk_width, i%chunk_height); + // *value = *getChunkValue(current_chunk, j%chunk_width, i%chunk_height); - if (display_loading != 0) - { - int nb_indents = display_loading - 1; + // if (display_loading != 0) + // { + // int nb_indents = display_loading - 1; - char base_str[100] = "Generating map values... "; + // char base_str[100] = "Generating map values... "; - predefined_loading_bar(j + i * width, width * height - 1, NUMBER_OF_SEGMENTS, base_str, nb_indents, start_time); - } - } - } + // predefined_loading_bar(j + i * width, width * height - 1, NUMBER_OF_SEGMENTS, base_str, nb_indents, start_time); + // } + // } + // } new_map = addMeanAltitude(new_map,display_loading); @@ -436,18 +467,18 @@ map* copyMap(map* p_map) } } - int n = res->chunk_width*res->map_width; - int m = res->chunk_height*res->map_height; + // int n = res->chunk_width*res->map_width; + // int m = res->chunk_height*res->map_height; - res->map_values = calloc(n*m, sizeof(double)); + // res->map_values = calloc(n*m, sizeof(double)); - for (int i=0; imap_width; int map_height = map->map_height; - if (map->map_values != NULL) - { - free(map->map_values); - } + // if (map->map_values != NULL) + // { + // free(map->map_values); + // } if (map->chunks != NULL) From e9d441f33b07c6a2cc5d08e8de5cb61940ae60e3 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Tue, 9 Jul 2024 17:14:29 +0200 Subject: [PATCH 09/84] get custom bytes representation for ints and floats --- Python/interpreter.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Python/interpreter.py b/Python/interpreter.py index 81eff7b..d215143 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -321,6 +321,34 @@ class DecodeDictError(InterpreterError): +### ---------- Binary encoding methods ---------- ### + +from numpy import uint8 +def bits(x : int | float | uint8) -> bytes: + if type(x)==int and int.bit_length(x)<=23: + temp = 0 if x>0 else 128 + x = abs(x) + res = bytes([temp+x//256**2,x%256**2//256,x%256]) + return res + elif type(x)==float: + temp = 0 if x>0 else 128 + x = abs(x) + exp = 0 + if x<2**19: + while exp>-16 and x<2**19: + exp-=1 + x*=2 + else: + while exp<15 and x>=2**19: + exp+=1 + x/=2 + exp+=16 + x=int(x) + res = bytes([temp+int(bin(exp)+bin(x//2**17)[2:],2)])+bits(x%2**17)[1:] + return res + + + if __name__ == "__main__": From 3f098d7d13bdbb875166bf6a16b6aa079dd289b6 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Tue, 9 Jul 2024 17:22:34 +0200 Subject: [PATCH 10/84] bytes for numpy uint8 --- Python/interpreter.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index d215143..7ff2340 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -325,7 +325,10 @@ class DecodeDictError(InterpreterError): from numpy import uint8 def bits(x : int | float | uint8) -> bytes: - if type(x)==int and int.bit_length(x)<=23: + if type(x)==uint8: + res=bytes([x]) + return res + elif type(x)==int and int.bit_length(x)<=23: temp = 0 if x>0 else 128 x = abs(x) res = bytes([temp+x//256**2,x%256**2//256,x%256]) From 6176bc67ff47af8aed97dea577aaf50c54db369a Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Tue, 9 Jul 2024 18:22:22 +0200 Subject: [PATCH 11/84] decoding number from bytes --- Python/interpreter.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index 7ff2340..9b0840e 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -324,7 +324,7 @@ class DecodeDictError(InterpreterError): ### ---------- Binary encoding methods ---------- ### from numpy import uint8 -def bits(x : int | float | uint8) -> bytes: +def bytesNumber(x : int | float | uint8) -> bytes: if type(x)==uint8: res=bytes([x]) return res @@ -338,7 +338,7 @@ def bits(x : int | float | uint8) -> bytes: x = abs(x) exp = 0 if x<2**19: - while exp>-16 and x<2**19: + while exp>-16 and x<2**18: exp-=1 x*=2 else: @@ -347,9 +347,28 @@ def bits(x : int | float | uint8) -> bytes: x/=2 exp+=16 x=int(x) - res = bytes([temp+int(bin(exp)+bin(x//2**17)[2:],2)])+bits(x%2**17)[1:] + print(exp,x) + res = bytes([temp+int(bin(exp)+bin(x//2**16)[2:],2),x%2**16//256,x%256]) return res +def nextInt(bytes_str : bytes) -> tuple[int, bytes]: + x = int.from_bytes(bytes_str[:3]) + if x//2**23==1: x=-x%2**23 + return x,bytes_str[3:] + +def nextFloat(bytes_str : bytes) -> tuple[float, bytes]: + x = int.from_bytes(bytes_str[:3]) + if x//2**23==1: x*=-x%2**23 + exp=x//2**19 + exp-=16 + x=x%2**19 + print(exp,x) + return x*2**exp,bytes_str[3:] + +def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: + x = int.from_bytes(bytes_str[0]) + x = uint8(x) + return x,bytes_str[1:] From 07afdf5589e081cdfaf3165a335d9ca3cc271b5f Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 10 Jul 2024 11:47:24 +0200 Subject: [PATCH 12/84] debuging float encoding --- Python/interpreter.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index 9b0840e..f269a6f 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -323,8 +323,8 @@ class DecodeDictError(InterpreterError): ### ---------- Binary encoding methods ---------- ### -from numpy import uint8 -def bytesNumber(x : int | float | uint8) -> bytes: +from numpy import uint8, float64 +def bytesNumber(x : int | float | float64 | uint8) -> bytes: if type(x)==uint8: res=bytes([x]) return res @@ -333,7 +333,7 @@ def bytesNumber(x : int | float | uint8) -> bytes: x = abs(x) res = bytes([temp+x//256**2,x%256**2//256,x%256]) return res - elif type(x)==float: + elif type(x)==float or type(x)==float64: temp = 0 if x>0 else 128 x = abs(x) exp = 0 @@ -347,7 +347,6 @@ def bytesNumber(x : int | float | uint8) -> bytes: x/=2 exp+=16 x=int(x) - print(exp,x) res = bytes([temp+int(bin(exp)+bin(x//2**16)[2:],2),x%2**16//256,x%256]) return res @@ -358,12 +357,13 @@ def nextInt(bytes_str : bytes) -> tuple[int, bytes]: def nextFloat(bytes_str : bytes) -> tuple[float, bytes]: x = int.from_bytes(bytes_str[:3]) - if x//2**23==1: x*=-x%2**23 - exp=x//2**19 + if x//(2**23)==1: s=-1 + else: s=1 + x=x%(2**23) + exp=x//(2**19) exp-=16 - x=x%2**19 - print(exp,x) - return x*2**exp,bytes_str[3:] + x=x%(2**19) + return s*x*2**exp,bytes_str[3:] def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: x = int.from_bytes(bytes_str[0]) From b7d25939dc163bd3a1ba5ee579f37c6e5b2a0a32 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 10 Jul 2024 11:52:25 +0200 Subject: [PATCH 13/84] grid encoding --- Python/gradientGrid.py | 61 +++++++++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 13 deletions(-) diff --git a/Python/gradientGrid.py b/Python/gradientGrid.py index 2c7d2e1..2b21feb 100644 --- a/Python/gradientGrid.py +++ b/Python/gradientGrid.py @@ -6,7 +6,7 @@ import numpy as np import random as rd - +import interpreter as interp @@ -28,6 +28,7 @@ class GradientGrid: #? -------------------------- Static ------------------------- # + GRID_ENCODING = b'\x01' MAX_INT_SEED = 1000000000000 # Maximum integer for the automatic random seed generation CURRENT_SEED = "a simple seed" # Current seed used by the randomizer @@ -52,16 +53,48 @@ def setRandomSeed(seed: int | float | str | bytes | bytearray | None = rd.randin @staticmethod - def write(path: str, grid: GradientGrid) -> None: + def write(grid: GradientGrid, path: str=None) -> bytes: #TODO - pass + bytes_str : bytes = b'' + bytes_str += GradientGrid.GRID_ENCODING + bytes_str += interp.bytesNumber(grid.height) + bytes_str += interp.bytesNumber(grid.width) + for i in range(grid.height): + for j in range(grid.width): + bytes_str += interp.bytesNumber(grid.vectors[i,j,0]) + bytes_str += interp.bytesNumber(grid.vectors[i,j,1]) + if path!=None: + f=open(path,"wb") + f.write(bytes_str) + return bytes_str @staticmethod - def read(path: str) -> GradientGrid: + def read(path: str=None, bytes_in : bytes=None) -> GradientGrid: #TODO - return None + bytes_str : bytes + if path!=None: + pass + elif bytes_in!=None and bytes_in[0:1]==GradientGrid.GRID_ENCODING: + bytes_str=bytes_in[1:] + else: bytes_str=None + + grid : GradientGrid + + if bytes_str!=None: + height, bytes_str = interp.nextInt(bytes_str) + width, bytes_str = interp.nextInt(bytes_str) + grid = GradientGrid(width,height) + print(grid.width, grid.height) + for i in range(grid.height): + for j in range(grid.width): + grid.vectors[i,j,0], bytes_str = interp.nextFloat(bytes_str) + grid.vectors[i,j,1], bytes_str = interp.nextFloat(bytes_str) + + else: grid = None + + return grid #? ------------------------ Instances ------------------------ # @@ -181,7 +214,7 @@ def regenerate(self, adjacent_grids: tuple[GradientGrid] = (None, None, None, No GradientGrid.setRandomSeed("seed") - grid = GradientGrid(5, 5) + grid = GradientGrid(5, 3) print(grid) @@ -190,15 +223,17 @@ def regenerate(self, adjacent_grids: tuple[GradientGrid] = (None, None, None, No grid.regenerate() print(grid) + print(GradientGrid.write(grid)) + print(GradientGrid.read(None, GradientGrid.write(grid))) - print("Trying to generate a grid at the north of the first one :") - gridn = GradientGrid(5, 3, (None, None, grid, None)) - print(gridn) + # print("Trying to generate a grid at the north of the first one :") + # gridn = GradientGrid(5, 3, (None, None, grid, None)) + # print(gridn) - print("Trying to manually modify the first grid and see if the other gris is also modified : (It shouldn't)") - grid.vectors[0, 2, 0] = 0 - print(grid) - print(gridn) + # print("Trying to manually modify the first grid and see if the other gris is also modified : (It shouldn't)") + # grid.vectors[0, 2, 0] = 0 + # print(grid) + # print(gridn) From 0c393468051c8d82713f982cc88b1fb7d5b7a5ce Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 10 Jul 2024 11:53:57 +0200 Subject: [PATCH 14/84] gradientGrid as main --- Python/gradientGrid.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Python/gradientGrid.py b/Python/gradientGrid.py index 2b21feb..30627cb 100644 --- a/Python/gradientGrid.py +++ b/Python/gradientGrid.py @@ -223,17 +223,18 @@ def regenerate(self, adjacent_grids: tuple[GradientGrid] = (None, None, None, No grid.regenerate() print(grid) + print("\nTrying to encode and decode the grid :") print(GradientGrid.write(grid)) print(GradientGrid.read(None, GradientGrid.write(grid))) - # print("Trying to generate a grid at the north of the first one :") - # gridn = GradientGrid(5, 3, (None, None, grid, None)) - # print(gridn) + print("Trying to generate a grid at the north of the first one :") + gridn = GradientGrid(5, 3, (None, None, grid, None)) + print(gridn) - # print("Trying to manually modify the first grid and see if the other gris is also modified : (It shouldn't)") - # grid.vectors[0, 2, 0] = 0 - # print(grid) - # print(gridn) + print("Trying to manually modify the first grid and see if the other gris is also modified : (It shouldn't)") + grid.vectors[0, 2, 0] = 0 + print(grid) + print(gridn) From 27b33e42c4e693870038e989d3624200b9bd9f32 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 10 Jul 2024 12:15:11 +0200 Subject: [PATCH 15/84] layer encoding and decoding 1st attempt --- Python/gradientGrid.py | 5 ++--- Python/interpreter.py | 4 ++++ Python/layer.py | 34 +++++++++++++++++++++++++++++----- 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/Python/gradientGrid.py b/Python/gradientGrid.py index 30627cb..868e90e 100644 --- a/Python/gradientGrid.py +++ b/Python/gradientGrid.py @@ -71,7 +71,7 @@ def write(grid: GradientGrid, path: str=None) -> bytes: @staticmethod - def read(path: str=None, bytes_in : bytes=None) -> GradientGrid: + def read(path: str=None, bytes_in : bytes=None) -> tuple[GradientGrid, bytes]: #TODO bytes_str : bytes if path!=None: @@ -86,7 +86,6 @@ def read(path: str=None, bytes_in : bytes=None) -> GradientGrid: height, bytes_str = interp.nextInt(bytes_str) width, bytes_str = interp.nextInt(bytes_str) grid = GradientGrid(width,height) - print(grid.width, grid.height) for i in range(grid.height): for j in range(grid.width): grid.vectors[i,j,0], bytes_str = interp.nextFloat(bytes_str) @@ -94,7 +93,7 @@ def read(path: str=None, bytes_in : bytes=None) -> GradientGrid: else: grid = None - return grid + return grid, bytes_str #? ------------------------ Instances ------------------------ # diff --git a/Python/interpreter.py b/Python/interpreter.py index f269a6f..d990b65 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -324,6 +324,10 @@ class DecodeDictError(InterpreterError): ### ---------- Binary encoding methods ---------- ### from numpy import uint8, float64 + +BYTES_TRUE = b'\x01' +BYTES_FALSE = b'\x00' + def bytesNumber(x : int | float | float64 | uint8) -> bytes: if type(x)==uint8: res=bytes([x]) diff --git a/Python/layer.py b/Python/layer.py index 684549d..49dc074 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -6,7 +6,7 @@ import numpy as np from gradientGrid import GradientGrid - +import interpreter as interp @@ -22,6 +22,7 @@ class Layer: #? -------------------------- Static ------------------------- # + LAYER_ENCODING = b'\x02' ALT_PRINTING_DECIMALS = 4 ALT_PRINTING_FORMAT = " {{: .{}f}} ".format(ALT_PRINTING_DECIMALS) @@ -169,16 +170,39 @@ def generateLayerFromScratch(grid_width: int, grid_height: int, size_factor: int @staticmethod - def write(path: str, layer: Layer) -> None: + def write(layer: Layer, path: str=None, altitude : bool = False) -> bytes: #TODO - pass + bytes_str : bytes = b'' + bytes_str += Layer.LAYER_ENCODING + bytes_str += interp.bytesNumber(layer.size_factor) + bytes_str += GradientGrid.write(layer.grid) + if path!=None: + f=open(path,"wb") + f.write(bytes_str) + return bytes_str @staticmethod - def read(path: str) -> Layer: + def read(path: str = None, bytes_in : bytes=None) -> tuple[Layer, bytes]: #TODO - return None + bytes_str : bytes + if path!=None: + pass + elif bytes_in!=None and bytes_in[0:1]==Layer.LAYER_ENCODING: + bytes_str=bytes_in[1:] + else: bytes_str=None + + layer : Layer + + if bytes_str!=None: + size_factor, bytes_str = interp.nextInt(bytes_str) + grid, bytes_str = GradientGrid.read(None,bytes_str) + layer = Layer(grid,size_factor) + + else: layer = None + + return layer, bytes_str #? ------------------------ Instances ------------------------ # From ad87bfadc4e15bdce233937a4b1c6ec06eb7d42e Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 10 Jul 2024 12:17:50 +0200 Subject: [PATCH 16/84] Seems to work --- Python/gradientGrid.py | 2 +- Python/layer.py | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Python/gradientGrid.py b/Python/gradientGrid.py index 868e90e..f75938b 100644 --- a/Python/gradientGrid.py +++ b/Python/gradientGrid.py @@ -224,7 +224,7 @@ def regenerate(self, adjacent_grids: tuple[GradientGrid] = (None, None, None, No print("\nTrying to encode and decode the grid :") print(GradientGrid.write(grid)) - print(GradientGrid.read(None, GradientGrid.write(grid))) + print(GradientGrid.read(None, GradientGrid.write(grid))[0]) print("Trying to generate a grid at the north of the first one :") diff --git a/Python/layer.py b/Python/layer.py index 49dc074..d0f979f 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -303,6 +303,10 @@ def regenerate(self) -> None: layer.regenerate() print(layer) + print("\nTrying to encode and decode the layer :") + print(Layer.write(layer)) + print(Layer.read(None, Layer.write(layer))[0]) + print("Trying to generate a layer at the north of the first one :") From cb4914ff392e4ba4842be9acb4e51a6c11bc5dd8 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 10 Jul 2024 12:25:44 +0200 Subject: [PATCH 17/84] write chunk --- Python/chunk.py | 16 ++++++++++++++-- Python/layer.py | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Python/chunk.py b/Python/chunk.py index 926f250..ea8ee2e 100644 --- a/Python/chunk.py +++ b/Python/chunk.py @@ -8,6 +8,7 @@ import random as rd from gradientGrid import GradientGrid from layer import Layer +import interpreter as interp @@ -25,6 +26,7 @@ class Chunk: #? -------------------------- Static ------------------------- # + CHUNK_ENCODING = b'\x03' ALT_PRINTING_DECIMALS = 4 ALT_PRINTING_FORMAT = " {{: .{}f}} ".format(ALT_PRINTING_DECIMALS) @@ -268,9 +270,19 @@ def newVirtualChunk(chunk_width: int, chunk_height: int) -> Chunk: @staticmethod - def write(path: str, chunk: Chunk) -> None: + def write(chunk: Chunk, path: str=None) -> bytes: #TODO - pass + bytes_str : bytes = b'' + bytes_str += Chunk.CHUNK_ENCODING + bytes_str += interp.bytesNumber(len(chunk.layers_factors)) + for x in chunk.layers_factors: + bytes_str += interp.bytesNumber(x) + for x in chunk.layers: + bytes_str += Layer.write(x) + if path!=None: + f=open(path,"wb") + f.write(bytes_str) + return bytes_str diff --git a/Python/layer.py b/Python/layer.py index d0f979f..6b1bfb2 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -170,7 +170,7 @@ def generateLayerFromScratch(grid_width: int, grid_height: int, size_factor: int @staticmethod - def write(layer: Layer, path: str=None, altitude : bool = False) -> bytes: + def write(layer: Layer, path: str=None) -> bytes: #TODO bytes_str : bytes = b'' bytes_str += Layer.LAYER_ENCODING From 22b50f311ba2d71404c7825874db2eaf6ace4f44 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 17:28:41 +0200 Subject: [PATCH 18/84] modularity of layer encoding --- Python/gradientGrid.py | 8 ++++---- Python/layer.py | 46 +++++++++++++++++++++++++++++------------- 2 files changed, 36 insertions(+), 18 deletions(-) diff --git a/Python/gradientGrid.py b/Python/gradientGrid.py index f75938b..5fc785e 100644 --- a/Python/gradientGrid.py +++ b/Python/gradientGrid.py @@ -53,8 +53,7 @@ def setRandomSeed(seed: int | float | str | bytes | bytearray | None = rd.randin @staticmethod - def write(grid: GradientGrid, path: str=None) -> bytes: - #TODO + def write(grid: GradientGrid, path: str=None, append: bool=False) -> bytes: bytes_str : bytes = b'' bytes_str += GradientGrid.GRID_ENCODING bytes_str += interp.bytesNumber(grid.height) @@ -64,7 +63,8 @@ def write(grid: GradientGrid, path: str=None) -> bytes: bytes_str += interp.bytesNumber(grid.vectors[i,j,0]) bytes_str += interp.bytesNumber(grid.vectors[i,j,1]) if path!=None: - f=open(path,"wb") + if append: f=open(path,"ab") + else: f=open(path,"wb") f.write(bytes_str) return bytes_str @@ -72,7 +72,7 @@ def write(grid: GradientGrid, path: str=None) -> bytes: @staticmethod def read(path: str=None, bytes_in : bytes=None) -> tuple[GradientGrid, bytes]: - #TODO + #TODO from file path bytes_str : bytes if path!=None: pass diff --git a/Python/layer.py b/Python/layer.py index 6b1bfb2..28f1656 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -170,22 +170,28 @@ def generateLayerFromScratch(grid_width: int, grid_height: int, size_factor: int @staticmethod - def write(layer: Layer, path: str=None) -> bytes: - #TODO + def write(layer: Layer, altitude: bool=False, path: str=None, append: bool=False) -> bytes: bytes_str : bytes = b'' bytes_str += Layer.LAYER_ENCODING bytes_str += interp.bytesNumber(layer.size_factor) bytes_str += GradientGrid.write(layer.grid) + if altitude: + bytes_str += interp.BYTES_TRUE + for i in range(layer.height): + for j in range(layer.width): + bytes_str += interp.bytesNumber(layer.altitude[i,j]) + else: bytes_str += interp.BYTES_FALSE if path!=None: - f=open(path,"wb") + if append: f=open(path,"ab") + else: f=open(path,"wb") f.write(bytes_str) return bytes_str @staticmethod - def read(path: str = None, bytes_in : bytes=None) -> tuple[Layer, bytes]: - #TODO + def read(path: str = None, bytes_in: bytes=None, altitude: bool=False) -> tuple[Layer, bytes]: + #TODO from file path bytes_str : bytes if path!=None: pass @@ -198,7 +204,18 @@ def read(path: str = None, bytes_in : bytes=None) -> tuple[Layer, bytes]: if bytes_str!=None: size_factor, bytes_str = interp.nextInt(bytes_str) grid, bytes_str = GradientGrid.read(None,bytes_str) - layer = Layer(grid,size_factor) + if bytes_str[0:1]==interp.BYTES_TRUE: + bytes_str=bytes_str[1:] + layer = Layer(grid,size_factor,False) + if altitude: + layer.altitude=np.zeros((layer.height,layer.width)) + for i in range(layer.height): + for j in range(layer.width): + layer.altitude[i,j], bytes_str = interp.nextFloat(bytes_str) + else: + bytes_str=bytes_str[1:] + layer = Layer(grid,size_factor,altitude) + else: layer = None @@ -208,7 +225,7 @@ def read(path: str = None, bytes_in : bytes=None) -> tuple[Layer, bytes]: #? ------------------------ Instances ------------------------ # - def __init__(self, grid: GradientGrid, size_factor: int) -> None: + def __init__(self, grid: GradientGrid, size_factor: int, regenerate: bool=True) -> None: """Initializes a new layer instance from an already existing GradientGrid and a size factor. If no gradient grid are already generated, please use the designated static method `generateLayerFromScratch` to generate the appropriate GradientGrid and then generate the layer structure. @@ -236,7 +253,7 @@ def __init__(self, grid: GradientGrid, size_factor: int) -> None: self.grid = grid self.size_factor = size_factor - self.regenerate() + self.regenerate(regenerate) @@ -262,7 +279,7 @@ def __str__(self) -> str: - def regenerate(self) -> None: + def regenerate(self, regenerate: bool=True) -> None: """Regenerates the altitude values of the layer based on its `grid` and `size_factor` parameters. """ @@ -273,12 +290,13 @@ def regenerate(self) -> None: self.width = (self.grid.width - 1) * self.size_factor self.height = (self.grid.height - 1) * self.size_factor - self.altitude = np.zeros((self.height, self.width)) - for i in range(self.height): - for j in range(self.width): - - self.altitude[i, j] = Layer.perlin(i/self.size_factor, j/self.size_factor, self.grid) + if regenerate: + self.altitude = np.zeros((self.height, self.width)) + for i in range(self.height): + for j in range(self.width): + + self.altitude[i, j] = Layer.perlin(i/self.size_factor, j/self.size_factor, self.grid) From 5933e0f6416fdd60bd1777a9bcb0ce48189fa8da Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 17:39:42 +0200 Subject: [PATCH 19/84] layer modularity encoding testing --- Python/layer.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Python/layer.py b/Python/layer.py index 28f1656..4a06cdd 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -266,13 +266,17 @@ def __str__(self) -> str: """ final_str = "-----------------------------------------\n" final_str += "Layer of dimensions {} x {} :\n".format(self.width, self.height) - for i in range(self.height): - - for j in range(self.width): - alt = self.altitude[i, j] - final_str += Layer.ALT_PRINTING_FORMAT.format(alt) + + if self.altitude.shape!=(0,0): - final_str += "\n" + for i in range(self.height): + + for j in range(self.width): + alt = self.altitude[i, j] + final_str += Layer.ALT_PRINTING_FORMAT.format(alt) + + final_str += "\n" + final_str += "-----------------------------------------\n" return final_str @@ -297,6 +301,8 @@ def regenerate(self, regenerate: bool=True) -> None: for j in range(self.width): self.altitude[i, j] = Layer.perlin(i/self.size_factor, j/self.size_factor, self.grid) + else: + self.altitude = np.zeros((0, 0)) @@ -322,8 +328,12 @@ def regenerate(self, regenerate: bool=True) -> None: print(layer) print("\nTrying to encode and decode the layer :") + print("\tWithout altitude :") print(Layer.write(layer)) print(Layer.read(None, Layer.write(layer))[0]) + print("\n\tWith altitude :") + print(Layer.write(layer,True)) + print(Layer.read(None, Layer.write(layer,True), True)[0]) From 2f6ed54cb6f92e65a93ec8c1bef5914c42afb523 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 17:45:15 +0200 Subject: [PATCH 20/84] uninitialised altitude arrays --- Python/layer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/layer.py b/Python/layer.py index 4a06cdd..fe0b56f 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -267,7 +267,7 @@ def __str__(self) -> str: final_str = "-----------------------------------------\n" final_str += "Layer of dimensions {} x {} :\n".format(self.width, self.height) - if self.altitude.shape!=(0,0): + if type(self.altitude)==np.ndarray: for i in range(self.height): @@ -302,7 +302,7 @@ def regenerate(self, regenerate: bool=True) -> None: self.altitude[i, j] = Layer.perlin(i/self.size_factor, j/self.size_factor, self.grid) else: - self.altitude = np.zeros((0, 0)) + self.altitude = None From 6418179e84db8b1c5273d2f64701e1a75ccfca8c Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 18:12:24 +0200 Subject: [PATCH 21/84] Chunk encoding and decoding --- Python/chunk.py | 75 ++++++++++++++++++++++++++++++++++++------------- Python/layer.py | 4 +++ 2 files changed, 59 insertions(+), 20 deletions(-) diff --git a/Python/chunk.py b/Python/chunk.py index ea8ee2e..3b76da6 100644 --- a/Python/chunk.py +++ b/Python/chunk.py @@ -270,32 +270,64 @@ def newVirtualChunk(chunk_width: int, chunk_height: int) -> Chunk: @staticmethod - def write(chunk: Chunk, path: str=None) -> bytes: - #TODO + def write(chunk: Chunk, path: str=None, append: bool=False) -> bytes: bytes_str : bytes = b'' bytes_str += Chunk.CHUNK_ENCODING + bytes_str += interp.bytesNumber(chunk.base_altitude) bytes_str += interp.bytesNumber(len(chunk.layers_factors)) for x in chunk.layers_factors: - bytes_str += interp.bytesNumber(x) + bytes_str += interp.bytesNumber(float(x)) for x in chunk.layers: bytes_str += Layer.write(x) + for i in range(chunk.height): + for j in range(chunk.width): + bytes_str += interp.bytesNumber(chunk.altitude[i,j]) if path!=None: - f=open(path,"wb") + if append: f=open(path,"ab") + else: f=open(path,"wb") f.write(bytes_str) return bytes_str @staticmethod - def read(path: str) -> Chunk: - #TODO - return None + def read(path: str, bytes_in : bytes=None) -> tuple[Chunk, bytes]: + #TODO from file path + bytes_str : bytes + if path!=None: + pass + elif bytes_in!=None and bytes_in[0:1]==Chunk.CHUNK_ENCODING: + bytes_str=bytes_in[1:] + else: bytes_str=None + + chunk : Chunk + + if bytes_str!=None: + base_altitude, bytes_str = interp.nextFloat(bytes_str) + layer_number, bytes_str = interp.nextInt(bytes_str) + layers: list[Layer] = [] + layer_factors: list[float] = [] + for _ in range(layer_number): + x, bytes_str = interp.nextFloat(bytes_str) + layer_factors.append(x) + for _ in range(layer_number): + x, bytes_str = Layer.read(None,bytes_str) + layers.append(x) + chunk = Chunk(layers, layer_factors, False) + chunk.altitude = np.zeros((chunk.height,chunk.width)) + for i in range(chunk.height): + for j in range(chunk.width): + chunk.altitude[i,j], bytes_str = interp.nextFloat(bytes_str) + + else: chunk = None + + return chunk, bytes_str #? ------------------------ Instances ------------------------ # - def __init__(self, layers: list[Layer], layers_factors: list[float]) -> None: + def __init__(self, layers: list[Layer], layers_factors: list[float], regenerate = True) -> None: """Initializes a new Chunk structure from the given list of already existing layers and factors. If layers should be generated in the process, please use one of the designated static methods. @@ -350,7 +382,7 @@ def __init__(self, layers: list[Layer], layers_factors: list[float]) -> None: self.layers_factors = layers_factors.copy() # Compute altitude - self.regenerate() + self.regenerate(regenerate) @@ -379,7 +411,7 @@ def __str__(self) -> str: - def regenerate(self) -> None: + def regenerate(self, regenerate: bool = True) -> None: """Regenerates the altitude values of the chunk based on its `layers` and `layer_factors` parameters. """ @@ -431,17 +463,17 @@ def regenerate(self) -> None: #* -------------- Verifications : End -------------- - - self.altitude = np.zeros((self.height, self.width)) - - for i in range(len_fac): - fac = self.layers_factors[i] - layer = self.layers[i] + if (regenerate): + self.altitude = np.zeros((self.height, self.width)) - self.altitude += fac * layer.altitude - - self.altitude /= factor_sum - self.base_altitude = Chunk.generateBaseAltitude() + for i in range(len_fac): + fac = self.layers_factors[i] + layer = self.layers[i] + + self.altitude += fac * layer.altitude + + self.altitude /= factor_sum + self.base_altitude = Chunk.generateBaseAltitude() for i in range(len_fac): layer = self.layers[i] @@ -473,6 +505,9 @@ def regenerate(self) -> None: print(chunk) + print("\nTesting chunk encoding: ") + print(Chunk.write(chunk)) + print(Chunk.read(None,Chunk.write(chunk))[0]) print("Generating a south chunk from gradient grids structures :") diff --git a/Python/layer.py b/Python/layer.py index fe0b56f..564125c 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -212,6 +212,10 @@ def read(path: str = None, bytes_in: bytes=None, altitude: bool=False) -> tuple[ for i in range(layer.height): for j in range(layer.width): layer.altitude[i,j], bytes_str = interp.nextFloat(bytes_str) + else: + for i in range(layer.height): + for j in range(layer.width): + _, bytes_str = interp.nextFloat(bytes_str) else: bytes_str=bytes_str[1:] layer = Layer(grid,size_factor,altitude) From a1e5929d0db5c6d572576880ea0fe4c416211254 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 18:31:41 +0200 Subject: [PATCH 22/84] virtual chunks encoding --- Python/chunk.py | 64 ++++++++++++++++++++++++++++++------------------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/Python/chunk.py b/Python/chunk.py index 3b76da6..13f3c8a 100644 --- a/Python/chunk.py +++ b/Python/chunk.py @@ -245,7 +245,7 @@ def generateChunkFromGradientGrids(grids: list[GradientGrid], size_factors: list @staticmethod - def newVirtualChunk(chunk_width: int, chunk_height: int) -> Chunk: + def newVirtualChunk(chunk_width: int, chunk_height: int, base_altitude: int = None) -> Chunk: """Generates a new virtual chunk. Args: @@ -262,7 +262,8 @@ def newVirtualChunk(chunk_width: int, chunk_height: int) -> Chunk: virtual_chunk.width = chunk_width virtual_chunk.height = chunk_height - virtual_chunk.base_altitude = Chunk.generateBaseAltitude() + if base_altitude!=None: virtual_chunk.base_altitude = base_altitude + else: virtual_chunk.base_altitude = Chunk.generateBaseAltitude() return virtual_chunk @@ -270,18 +271,24 @@ def newVirtualChunk(chunk_width: int, chunk_height: int) -> Chunk: @staticmethod - def write(chunk: Chunk, path: str=None, append: bool=False) -> bytes: + def write(chunk: Chunk, virtual: bool=False, path: str=None, append: bool=False) -> bytes: bytes_str : bytes = b'' bytes_str += Chunk.CHUNK_ENCODING bytes_str += interp.bytesNumber(chunk.base_altitude) - bytes_str += interp.bytesNumber(len(chunk.layers_factors)) - for x in chunk.layers_factors: - bytes_str += interp.bytesNumber(float(x)) - for x in chunk.layers: - bytes_str += Layer.write(x) - for i in range(chunk.height): - for j in range(chunk.width): - bytes_str += interp.bytesNumber(chunk.altitude[i,j]) + bytes_str += interp.bytesNumber(chunk.width) + bytes_str += interp.bytesNumber(chunk.height) + if virtual: + bytes_str += interp.BYTES_TRUE + else: + bytes_str += interp.BYTES_FALSE + bytes_str += interp.bytesNumber(len(chunk.layers_factors)) + for x in chunk.layers_factors: + bytes_str += interp.bytesNumber(float(x)) + for x in chunk.layers: + bytes_str += Layer.write(x) + for i in range(chunk.height): + for j in range(chunk.width): + bytes_str += interp.bytesNumber(chunk.altitude[i,j]) if path!=None: if append: f=open(path,"ab") else: f=open(path,"wb") @@ -304,20 +311,27 @@ def read(path: str, bytes_in : bytes=None) -> tuple[Chunk, bytes]: if bytes_str!=None: base_altitude, bytes_str = interp.nextFloat(bytes_str) - layer_number, bytes_str = interp.nextInt(bytes_str) - layers: list[Layer] = [] - layer_factors: list[float] = [] - for _ in range(layer_number): - x, bytes_str = interp.nextFloat(bytes_str) - layer_factors.append(x) - for _ in range(layer_number): - x, bytes_str = Layer.read(None,bytes_str) - layers.append(x) - chunk = Chunk(layers, layer_factors, False) - chunk.altitude = np.zeros((chunk.height,chunk.width)) - for i in range(chunk.height): - for j in range(chunk.width): - chunk.altitude[i,j], bytes_str = interp.nextFloat(bytes_str) + height, bytes_str = interp.nextInt(bytes_str) + width, bytes_str = interp.nextInt(bytes_str) + if bytes_str[0:1]==interp.BYTES_TRUE: + chunk = Chunk.newVirtualChunk(width, height, base_altitude) + bytes_str = bytes_str[1:] + else: + bytes_str = bytes_str[1:] + layer_number, bytes_str = interp.nextInt(bytes_str) + layers: list[Layer] = [] + layer_factors: list[float] = [] + for _ in range(layer_number): + x, bytes_str = interp.nextFloat(bytes_str) + layer_factors.append(x) + for _ in range(layer_number): + x, bytes_str = Layer.read(None,bytes_str) + layers.append(x) + chunk = Chunk(layers, layer_factors, False) + chunk.altitude = np.zeros((chunk.height,chunk.width)) + for i in range(chunk.height): + for j in range(chunk.width): + chunk.altitude[i,j], bytes_str = interp.nextFloat(bytes_str) else: chunk = None From e8f08803756b4f7a24cd33b0a64d5062e0699548 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 18:40:05 +0200 Subject: [PATCH 23/84] map encoding --- Python/map.py | 64 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 53 insertions(+), 11 deletions(-) diff --git a/Python/map.py b/Python/map.py index 8b448a9..aa87a3a 100644 --- a/Python/map.py +++ b/Python/map.py @@ -10,6 +10,7 @@ from gradientGrid import GradientGrid from layer import Layer from chunk import Chunk +import interpreter as interp class Map: @@ -25,6 +26,7 @@ class Map: #? -------------------------- Static ------------------------- # + MAP_ENCODING = b'\x04' ALT_PRINTING_DECIMALS = 4 ALT_PRINTING_FORMAT = " {{: .{}f}} ".format(ALT_PRINTING_DECIMALS) @@ -112,16 +114,56 @@ def generateMapFromScratch(grid_widths: list[int], grid_heights: list[int], size @staticmethod - def write(path: str, map: Map) -> None: - #TODO - pass + def write(map: Map, path: str=None, append: bool=False) -> bytes: + bytes_str : bytes = b'' + bytes_str += Map.MAP_ENCODING + bytes_str += interp.bytesNumber(map.map_height) + bytes_str += interp.bytesNumber(map.map_width) + for i in range(map.map_height): + for j in range(map.map_width): + bytes_str += Chunk.write(map.chunks[i][j]) + n = 2 * (map.map_width+2) + 2 * map.map_height + for i in range(n): + bytes_str += Chunk.write(map.virtual_chunks[i],True) + if path!=None: + if append: f=open(path,"ab") + else: f=open(path,"wb") + f.write(bytes_str) + return bytes_str @staticmethod - def read(path: str) -> Map: - #TODO - return None + def read(path: str, bytes_in : bytes=None) -> tuple[Map, bytes]: + #TODO from file path + bytes_str : bytes + if path!=None: + pass + elif bytes_in!=None and bytes_in[0:1]==Map.MAP_ENCODING: + bytes_str=bytes_in[1:] + else: bytes_str=None + + map : Map + + if bytes_str!=None: + height, bytes_str = interp.nextInt(bytes_str) + width, bytes_str = interp.nextInt(bytes_str) + chunks: list[list[Chunk]] = [] + virtual_chunks: list[Chunk] = [] + for i in range(height): + chunks.append([]) + for _ in range(width): + x, bytes_str = Chunk.read(None, bytes_str) + chunks[i].append(x) + n = 2 * (width+2) + 2 * height + for _ in range(n): + x, bytes_str = Chunk.read(None, bytes_str) + virtual_chunks.append(x) + map = Map(width,height,chunks,virtual_chunks,False) + + else: chunk = None + + return chunk, bytes_str @@ -159,7 +201,7 @@ def getVirtualChunk(self, width_idx: int, height_idx: int) -> Chunk: - def __init__(self, map_width: int, map_height: int, chunks: list[list[Chunk]], virtual_chunks: list[Chunk]) -> None: + def __init__(self, map_width: int, map_height: int, chunks: list[list[Chunk]], virtual_chunks: list[Chunk], regenerate: bool = True) -> None: """Initializes a new Map structure from the given list of already existing chunks and virtual chunks. If chunks should be generated in the process, please use one of the designated static methods. @@ -199,7 +241,7 @@ def __init__(self, map_width: int, map_height: int, chunks: list[list[Chunk]], v self.chunks = copy.deepcopy(chunks) #? To keep both dimensions copied. Or use an np.ndarray ? self.virtual_chunks = virtual_chunks.copy() - self.regenerate() + self.regenerate(regenerate) @@ -219,7 +261,7 @@ def __str__(self) -> str: - def regenerate(self) -> None: + def regenerate(self, regenerate: bool = True) -> None: """Regenerates the altitude values of the map based on its chunks. """ @@ -241,8 +283,8 @@ def regenerate(self) -> None: # current_chunk = self.chunks[i//self.chunk_height][j//self.chunk_width] # self.altitude[i][j] = current_chunk.altitude[i%self.chunk_height][j%self.chunk_width] - - self.applyMeanAltitude() + if regenerate: + self.applyMeanAltitude() From d073420a7b43a7c990db8d7c297343685d5382f0 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 18:42:34 +0200 Subject: [PATCH 24/84] map encoding testing --- Python/map.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Python/map.py b/Python/map.py index aa87a3a..6956d2c 100644 --- a/Python/map.py +++ b/Python/map.py @@ -161,9 +161,9 @@ def read(path: str, bytes_in : bytes=None) -> tuple[Map, bytes]: virtual_chunks.append(x) map = Map(width,height,chunks,virtual_chunks,False) - else: chunk = None + else: map = None - return chunk, bytes_str + return map, bytes_str @@ -413,4 +413,8 @@ def getFullMap(self) -> np.ndarray: map = Map.generateMapFromScratch(grid_dim, grid_dim, size_factors, layer_factors, map_dimensions[0], map_dimensions[1]) print(map) + + print("\nTesting map encoding: ") + print(Map.write(map)) + print(Map.read(None,Map.write(map))[0]) \ No newline at end of file From e73d3e120468fb8052fcf19541970caca3bf6409 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 18:54:00 +0200 Subject: [PATCH 25/84] encoding complete map --- Python/mapGenerator.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index 5270ee2..b869121 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -11,6 +11,7 @@ from layer import Layer from chunk import Chunk from map import Map +import interpreter as interp class CompleteMap: """ @@ -22,6 +23,8 @@ class CompleteMap: #? -------------------------- Static ------------------------- # + COMPLETE_MAP_ENCODING = b'\x04' + @staticmethod def colorize(value: float, sea_level: float, min_value: float, max_value: float) -> tuple[float]: """Returns the color associated with the given value for the given parameters. The color is a @@ -95,9 +98,24 @@ def generateCompleteMapFromScratch(grid_widths: list[int], grid_heights: list[in @staticmethod - def write(path: str, complete_map: CompleteMap) -> None: - #TODO - pass + def write(complete_map: CompleteMap, path: str=None, append: bool=False) -> bytes: + bytes_str : bytes = b'' + bytes_str += CompleteMap.COMPLETE_MAP_ENCODING + bytes_str += Map.write(complete_map.map) + bytes_str += interp.bytesNumber(complete_map.sea_level) + height = map.map_height * map.chunk_height + width = map.map_width * map.chunk_width + for i in range(height): + for j in range(width): + bytes_str += interp.bytesNumber(complete_map.sea_values[i,j]) + bytes_str += interp.bytesNumber(complete_map.color_map[i,j,0]) + bytes_str += interp.bytesNumber(complete_map.color_map[i,j,1]) + bytes_str += interp.bytesNumber(complete_map.color_map[i,j,2]) + if path!=None: + if append: f=open(path,"ab") + else: f=open(path,"wb") + f.write(bytes_str) + return bytes_str From 6f5ff19f970e75bfbf140b8379469c1e5b4b3bae Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 19:02:46 +0200 Subject: [PATCH 26/84] decoding completemap --- Python/mapGenerator.py | 59 +++++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 15 deletions(-) diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index b869121..ed81bfd 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -103,8 +103,8 @@ def write(complete_map: CompleteMap, path: str=None, append: bool=False) -> byte bytes_str += CompleteMap.COMPLETE_MAP_ENCODING bytes_str += Map.write(complete_map.map) bytes_str += interp.bytesNumber(complete_map.sea_level) - height = map.map_height * map.chunk_height - width = map.map_width * map.chunk_width + height = complete_map.map.map_height * complete_map.map.chunk_height + width = complete_map.map.map_width * complete_map.map.chunk_width for i in range(height): for j in range(width): bytes_str += interp.bytesNumber(complete_map.sea_values[i,j]) @@ -120,14 +120,42 @@ def write(complete_map: CompleteMap, path: str=None, append: bool=False) -> byte @staticmethod - def read(path: str) -> CompleteMap: - #TODO - return None + def read(path: str, bytes_in : bytes=None) -> tuple[CompleteMap, bytes]: + #TODO from file path + bytes_str : bytes + if path!=None: + pass + elif bytes_in!=None and bytes_in[0:1]==CompleteMap.COMPLETE_MAP_ENCODING: + bytes_str=bytes_in[1:] + else: bytes_str=None + + complete_map : CompleteMap + + if bytes_str!=None: + map,bytes_str = Map.read(None, bytes_str) + height = map.map_height * map.chunk_height + width = map.map_width * map.chunk_width + sea_level, bytes_str = interp.nextFloat(bytes_str) + sea_values = np.zeros((height,width)) + color_map = np.zeros((height,width,3),np.uint8) + for i in range(height): + for j in range(width): + sea_values[i,j], bytes_str = interp.nextFloat(bytes_str) + color_map[i,j,0], bytes_str = interp.nextUInt8(bytes_str) + color_map[i,j,1], bytes_str = interp.nextUInt8(bytes_str) + color_map[i,j,2], bytes_str = interp.nextUInt8(bytes_str) + complete_map = CompleteMap(map,sea_level,False) + complete_map.sea_values = sea_values + complete_map.color_map = color_map + + else: complete_map = None + + return complete_map, bytes_str #? ------------------------ Instances ------------------------ # - def __init__(self, map: Map, sea_level: float) -> None: + def __init__(self, map: Map, sea_level: float, regenerate: bool = True) -> None: """Initialize a CompleteMap structure based on the given Map and sea altitude. Args: @@ -147,15 +175,16 @@ def __init__(self, map: Map, sea_level: float) -> None: self.map = map self.sea_level = sea_level - alt = self.map.getFullMap() - - if type(alt) == np.ndarray: - pass - else: - alt = np.array(alt) - self.sea_values = np.where(alt >= sea_level, alt, sea_level) - - self.generateColorMap() + if regenerate: + alt = self.map.getFullMap() + + if type(alt) == np.ndarray: + pass + else: + alt = np.array(alt) + self.sea_values = np.where(alt >= sea_level, alt, sea_level) + + self.generateColorMap() From 426773764133a6fcc76baf1a327bbfe356c64908 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 12 Jul 2024 19:06:04 +0200 Subject: [PATCH 27/84] completeMap encoding testing --- Python/interpreter.py | 2 +- Python/mapGenerator.py | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index d990b65..d62b38e 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -370,7 +370,7 @@ def nextFloat(bytes_str : bytes) -> tuple[float, bytes]: return s*x*2**exp,bytes_str[3:] def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: - x = int.from_bytes(bytes_str[0]) + x = int.from_bytes(bytes_str[0:1]) x = uint8(x) return x,bytes_str[1:] diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index ed81bfd..19acea2 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -546,6 +546,10 @@ def plotCompleteMap(complete_map: CompleteMap) -> None: MapGenerator.plotCompleteMap(complete_map) + print("\nTesting completeMap encoding: ") + print(CompleteMap.write(complete_map)) + MapGenerator.plotCompleteMap(CompleteMap.read(None,CompleteMap.write(complete_map))[0]) + From f3d47741d8dfc3bdb33d2392350e2e42cd29a415 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 21 Jul 2024 12:04:39 +0200 Subject: [PATCH 28/84] int encoding modularity --- Python/interpreter.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index d62b38e..0e3c844 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -327,15 +327,21 @@ class DecodeDictError(InterpreterError): BYTES_TRUE = b'\x01' BYTES_FALSE = b'\x00' +INT_BITS_NBR = 24 #24 should be a multiple of 8 +FLOAT_BITS_SIGN = 1 +FLOAT_BITS_EXP = 5 +FLOAT_BITS_MANTISS = 18 +FLOAT_BITS_NBR = FLOAT_BITS_SIGN + FLOAT_BITS_EXP + FLOAT_BITS_MANTISS #24 should be a multiple of 8 def bytesNumber(x : int | float | float64 | uint8) -> bytes: if type(x)==uint8: res=bytes([x]) return res - elif type(x)==int and int.bit_length(x)<=23: + elif type(x)==int and int.bit_length(x)0 else 128 x = abs(x) - res = bytes([temp+x//256**2,x%256**2//256,x%256]) + l=[temp + x // (2**(INT_BITS_NBR-8))] + [x % (2**(INT_BITS_NBR-i)) // (2**(INT_BITS_NBR-i-8)) for i in range(8,INT_BITS_NBR,8)] + res = bytes(l) return res elif type(x)==float or type(x)==float64: temp = 0 if x>0 else 128 From 571cbb29062e56483d80ea46cb756d400414583d Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 21 Jul 2024 12:56:26 +0200 Subject: [PATCH 29/84] float encoding modularity --- Python/interpreter.py | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index 0e3c844..082c9dc 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -328,10 +328,9 @@ class DecodeDictError(InterpreterError): BYTES_TRUE = b'\x01' BYTES_FALSE = b'\x00' INT_BITS_NBR = 24 #24 should be a multiple of 8 -FLOAT_BITS_SIGN = 1 -FLOAT_BITS_EXP = 5 -FLOAT_BITS_MANTISS = 18 -FLOAT_BITS_NBR = FLOAT_BITS_SIGN + FLOAT_BITS_EXP + FLOAT_BITS_MANTISS #24 should be a multiple of 8 +FLOAT_BITS_EXP = 5 #5 sould be < 8 +FLOAT_BITS_MANTISS = 18 +FLOAT_BITS_NBR = 1 + FLOAT_BITS_EXP + FLOAT_BITS_MANTISS #24 should be a multiple of 8 def bytesNumber(x : int | float | float64 | uint8) -> bytes: if type(x)==uint8: @@ -347,33 +346,38 @@ def bytesNumber(x : int | float | float64 | uint8) -> bytes: temp = 0 if x>0 else 128 x = abs(x) exp = 0 - if x<2**19: - while exp>-16 and x<2**18: + if x<2**(FLOAT_BITS_MANTISS): + while exp>-2**(FLOAT_BITS_EXP-1) and x<2**(FLOAT_BITS_MANTISS-1): exp-=1 x*=2 else: - while exp<15 and x>=2**19: + while exp<2**(FLOAT_BITS_EXP-1)-1 and x>=2**(FLOAT_BITS_MANTISS): exp+=1 x/=2 + print(x,exp) exp+=16 x=int(x) - res = bytes([temp+int(bin(exp)+bin(x//2**16)[2:],2),x%2**16//256,x%256]) + print(x,exp) + l = [temp + exp*2**(8-(1+FLOAT_BITS_EXP)) + x//2**(FLOAT_BITS_MANTISS-(8-(1+FLOAT_BITS_EXP)))] + l += [x%2**(FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP)-i) // (2**(FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP)-i-8)) for i in range(8,FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP),8)] + res = bytes(l) return res def nextInt(bytes_str : bytes) -> tuple[int, bytes]: - x = int.from_bytes(bytes_str[:3]) + x = int.from_bytes(bytes_str[:INT_BITS_NBR//8]) if x//2**23==1: x=-x%2**23 - return x,bytes_str[3:] + return x,bytes_str[INT_BITS_NBR//8:] def nextFloat(bytes_str : bytes) -> tuple[float, bytes]: - x = int.from_bytes(bytes_str[:3]) - if x//(2**23)==1: s=-1 + x = int.from_bytes(bytes_str[:FLOAT_BITS_NBR//8]) + if x//(2**(FLOAT_BITS_NBR-1))==1: s=-1 else: s=1 - x=x%(2**23) - exp=x//(2**19) + x=x%(2**(FLOAT_BITS_NBR-1)) + exp=x//(2**(FLOAT_BITS_MANTISS)) exp-=16 - x=x%(2**19) - return s*x*2**exp,bytes_str[3:] + x=x%(2**(FLOAT_BITS_MANTISS)) + print(s,x,exp) + return s*x*2**exp,bytes_str[FLOAT_BITS_NBR//8:] def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: x = int.from_bytes(bytes_str[0:1]) From d2050c72bcc6ae0a5f0d5531e7eaa3ce4d7e5bde Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 21 Jul 2024 13:01:19 +0200 Subject: [PATCH 30/84] File reading and closing --- Python/chunk.py | 6 ++++-- Python/gradientGrid.py | 6 ++++-- Python/layer.py | 6 ++++-- Python/map.py | 6 ++++-- Python/mapGenerator.py | 6 ++++-- 5 files changed, 20 insertions(+), 10 deletions(-) diff --git a/Python/chunk.py b/Python/chunk.py index 13f3c8a..0b149c4 100644 --- a/Python/chunk.py +++ b/Python/chunk.py @@ -293,16 +293,18 @@ def write(chunk: Chunk, virtual: bool=False, path: str=None, append: bool=False) if append: f=open(path,"ab") else: f=open(path,"wb") f.write(bytes_str) + f.close() return bytes_str @staticmethod def read(path: str, bytes_in : bytes=None) -> tuple[Chunk, bytes]: - #TODO from file path bytes_str : bytes if path!=None: - pass + f=open(path,'rb') + bytes_str=f.read() + f.close() elif bytes_in!=None and bytes_in[0:1]==Chunk.CHUNK_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None diff --git a/Python/gradientGrid.py b/Python/gradientGrid.py index 5fc785e..2c06e03 100644 --- a/Python/gradientGrid.py +++ b/Python/gradientGrid.py @@ -66,16 +66,18 @@ def write(grid: GradientGrid, path: str=None, append: bool=False) -> bytes: if append: f=open(path,"ab") else: f=open(path,"wb") f.write(bytes_str) + f.close() return bytes_str @staticmethod def read(path: str=None, bytes_in : bytes=None) -> tuple[GradientGrid, bytes]: - #TODO from file path bytes_str : bytes if path!=None: - pass + f=open(path,'rb') + bytes_str=f.read() + f.close() elif bytes_in!=None and bytes_in[0:1]==GradientGrid.GRID_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None diff --git a/Python/layer.py b/Python/layer.py index 564125c..20a23b2 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -185,16 +185,18 @@ def write(layer: Layer, altitude: bool=False, path: str=None, append: bool=False if append: f=open(path,"ab") else: f=open(path,"wb") f.write(bytes_str) + f.close() return bytes_str @staticmethod def read(path: str = None, bytes_in: bytes=None, altitude: bool=False) -> tuple[Layer, bytes]: - #TODO from file path bytes_str : bytes if path!=None: - pass + f=open(path,'rb') + bytes_str=f.read() + f.close() elif bytes_in!=None and bytes_in[0:1]==Layer.LAYER_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None diff --git a/Python/map.py b/Python/map.py index 6956d2c..3fd79de 100644 --- a/Python/map.py +++ b/Python/map.py @@ -129,16 +129,18 @@ def write(map: Map, path: str=None, append: bool=False) -> bytes: if append: f=open(path,"ab") else: f=open(path,"wb") f.write(bytes_str) + f.close() return bytes_str @staticmethod def read(path: str, bytes_in : bytes=None) -> tuple[Map, bytes]: - #TODO from file path bytes_str : bytes if path!=None: - pass + f=open(path,'rb') + bytes_str=f.read() + f.close() elif bytes_in!=None and bytes_in[0:1]==Map.MAP_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index 19acea2..f0c3eee 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -115,16 +115,18 @@ def write(complete_map: CompleteMap, path: str=None, append: bool=False) -> byte if append: f=open(path,"ab") else: f=open(path,"wb") f.write(bytes_str) + f.close() return bytes_str @staticmethod def read(path: str, bytes_in : bytes=None) -> tuple[CompleteMap, bytes]: - #TODO from file path bytes_str : bytes if path!=None: - pass + f=open(path,'rb') + bytes_str=f.read() + f.close() elif bytes_in!=None and bytes_in[0:1]==CompleteMap.COMPLETE_MAP_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None From 484b16a1bfab03f8245cb4232643dff279494681 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 21 Jul 2024 13:04:07 +0200 Subject: [PATCH 31/84] File writing and reading testing for completemap --- Python/mapGenerator.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index f0c3eee..e34e8a3 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -549,8 +549,8 @@ def plotCompleteMap(complete_map: CompleteMap) -> None: MapGenerator.plotCompleteMap(complete_map) print("\nTesting completeMap encoding: ") - print(CompleteMap.write(complete_map)) - MapGenerator.plotCompleteMap(CompleteMap.read(None,CompleteMap.write(complete_map))[0]) + print(CompleteMap.write(complete_map,"../saves/test_completeMap.data")) + MapGenerator.plotCompleteMap(CompleteMap.read("../saves/test_completeMap.data")) From 69eec7bc2a13f544538aeb873fb8d63018bb6660 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 21 Jul 2024 14:02:30 +0200 Subject: [PATCH 32/84] File reading --- Python/chunk.py | 2 ++ Python/gradientGrid.py | 6 ++++-- Python/interpreter.py | 3 --- Python/layer.py | 2 ++ Python/map.py | 2 ++ Python/mapGenerator.py | 4 +++- 6 files changed, 13 insertions(+), 6 deletions(-) diff --git a/Python/chunk.py b/Python/chunk.py index 0b149c4..24cd83c 100644 --- a/Python/chunk.py +++ b/Python/chunk.py @@ -305,6 +305,8 @@ def read(path: str, bytes_in : bytes=None) -> tuple[Chunk, bytes]: f=open(path,'rb') bytes_str=f.read() f.close() + if bytes_str[0:1]==Chunk.CHUNK_ENCODING: bytes_str=bytes_str[1:] + else: bytes_str=None elif bytes_in!=None and bytes_in[0:1]==Chunk.CHUNK_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None diff --git a/Python/gradientGrid.py b/Python/gradientGrid.py index 2c06e03..466bf5a 100644 --- a/Python/gradientGrid.py +++ b/Python/gradientGrid.py @@ -78,6 +78,8 @@ def read(path: str=None, bytes_in : bytes=None) -> tuple[GradientGrid, bytes]: f=open(path,'rb') bytes_str=f.read() f.close() + if bytes_str[0:1]==GradientGrid.GRID_ENCODING: bytes_str=bytes_str[1:] + else: bytes_str=None elif bytes_in!=None and bytes_in[0:1]==GradientGrid.GRID_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None @@ -225,8 +227,8 @@ def regenerate(self, adjacent_grids: tuple[GradientGrid] = (None, None, None, No print(grid) print("\nTrying to encode and decode the grid :") - print(GradientGrid.write(grid)) - print(GradientGrid.read(None, GradientGrid.write(grid))[0]) + print(GradientGrid.write(grid,"../saves/test_completeMap.data")) + print(GradientGrid.read("../saves/test_completeMap.data")[0]) print("Trying to generate a grid at the north of the first one :") diff --git a/Python/interpreter.py b/Python/interpreter.py index 082c9dc..a204606 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -354,10 +354,8 @@ def bytesNumber(x : int | float | float64 | uint8) -> bytes: while exp<2**(FLOAT_BITS_EXP-1)-1 and x>=2**(FLOAT_BITS_MANTISS): exp+=1 x/=2 - print(x,exp) exp+=16 x=int(x) - print(x,exp) l = [temp + exp*2**(8-(1+FLOAT_BITS_EXP)) + x//2**(FLOAT_BITS_MANTISS-(8-(1+FLOAT_BITS_EXP)))] l += [x%2**(FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP)-i) // (2**(FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP)-i-8)) for i in range(8,FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP),8)] res = bytes(l) @@ -376,7 +374,6 @@ def nextFloat(bytes_str : bytes) -> tuple[float, bytes]: exp=x//(2**(FLOAT_BITS_MANTISS)) exp-=16 x=x%(2**(FLOAT_BITS_MANTISS)) - print(s,x,exp) return s*x*2**exp,bytes_str[FLOAT_BITS_NBR//8:] def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: diff --git a/Python/layer.py b/Python/layer.py index 20a23b2..be1e01e 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -197,6 +197,8 @@ def read(path: str = None, bytes_in: bytes=None, altitude: bool=False) -> tuple[ f=open(path,'rb') bytes_str=f.read() f.close() + if bytes_str[0:1]==Layer.LAYER_ENCODING: bytes_str=bytes_str[1:] + else: bytes_str=None elif bytes_in!=None and bytes_in[0:1]==Layer.LAYER_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None diff --git a/Python/map.py b/Python/map.py index 3fd79de..42f62ac 100644 --- a/Python/map.py +++ b/Python/map.py @@ -141,6 +141,8 @@ def read(path: str, bytes_in : bytes=None) -> tuple[Map, bytes]: f=open(path,'rb') bytes_str=f.read() f.close() + if bytes_str[0:1]==Map.MAP_ENCODING: bytes_str=bytes_str[1:] + else: bytes_str=None elif bytes_in!=None and bytes_in[0:1]==Map.MAP_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index e34e8a3..3b820ab 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -127,6 +127,8 @@ def read(path: str, bytes_in : bytes=None) -> tuple[CompleteMap, bytes]: f=open(path,'rb') bytes_str=f.read() f.close() + if bytes_str[0:1]==CompleteMap.COMPLETE_MAP_ENCODING: bytes_str=bytes_str[1:] + else: bytes_str=None elif bytes_in!=None and bytes_in[0:1]==CompleteMap.COMPLETE_MAP_ENCODING: bytes_str=bytes_in[1:] else: bytes_str=None @@ -550,7 +552,7 @@ def plotCompleteMap(complete_map: CompleteMap) -> None: print("\nTesting completeMap encoding: ") print(CompleteMap.write(complete_map,"../saves/test_completeMap.data")) - MapGenerator.plotCompleteMap(CompleteMap.read("../saves/test_completeMap.data")) + MapGenerator.plotCompleteMap(CompleteMap.read("../saves/test_completeMap.data")[0]) From d8e53ea551c6d8067f635270718870ea817b11f3 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 24 Jul 2024 19:23:09 +0200 Subject: [PATCH 33/84] global read function --- Python/interpreter.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/Python/interpreter.py b/Python/interpreter.py index a204606..231f8f4 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -324,6 +324,11 @@ class DecodeDictError(InterpreterError): ### ---------- Binary encoding methods ---------- ### from numpy import uint8, float64 +from layer import Layer +from gradientGrid import GradientGrid +from chunk import Chunk +from map import Map +from mapGenerator import CompleteMap BYTES_TRUE = b'\x01' BYTES_FALSE = b'\x00' @@ -381,6 +386,43 @@ def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: x = uint8(x) return x,bytes_str[1:] +#TODO lists + +def read(path: str) -> object: + bytes_str : bytes + if path!=None: + f=open(path,'rb') + bytes_str=f.read() + f.close() + else: bytes_str=None + + if bytes_str!=None: + if bytes_str[0:1]==GradientGrid.GRID_ENCODING: + return GradientGrid.read(None,bytes_str)[0] + elif bytes_str[0:1]==Layer.LAYER_ENCODING: + return Layer.read(None,bytes_str)[0] + elif bytes_str[0:1]==Chunk.CHUNK_ENCODING: + return Chunk.read(None,bytes_str)[0] + elif bytes_str[0:1]==Map.MAP_ENCODING: + return Map.read(None,bytes_str)[0] + elif bytes_str[0:1]==CompleteMap.COMPLETE_MAP_ENCODING: + return CompleteMap.read(None,bytes_str)[0] + + else: return None + +def write(path: str, obj: object): + bytes_str : bytes + if path!=None: + f=open(path,'wb') + bytes_str: bytes + + if type(obj)==GradientGrid: + bytes_str+=GradientGrid.write(obj) + elif type(obj)==Layer: + bytes_str+=Layer.write(obj,True) + + f.write(bytes_str) + f.close() From 6be914eafa4faf76a45ca50bb0c46a4424a9a9a9 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 24 Jul 2024 19:24:47 +0200 Subject: [PATCH 34/84] wrtie global function --- Python/interpreter.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Python/interpreter.py b/Python/interpreter.py index 231f8f4..84ed7cb 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -420,6 +420,12 @@ def write(path: str, obj: object): bytes_str+=GradientGrid.write(obj) elif type(obj)==Layer: bytes_str+=Layer.write(obj,True) + elif type(obj)==Chunk: + bytes_str+=Chunk.write(obj) + elif type(obj)==Chunk: + bytes_str+=Chunk.write(obj) + elif type(obj)==Map: + bytes_str+=Map.write(obj) f.write(bytes_str) f.close() From fb56c0e522a03e3c06f6e4314abd83faa489f648 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 24 Jul 2024 19:33:27 +0200 Subject: [PATCH 35/84] testing global read and write --- Python/interpreter.py | 124 ++++++++++++++++++++++++++---------------- 1 file changed, 78 insertions(+), 46 deletions(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index 84ed7cb..3f6e08f 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -324,11 +324,6 @@ class DecodeDictError(InterpreterError): ### ---------- Binary encoding methods ---------- ### from numpy import uint8, float64 -from layer import Layer -from gradientGrid import GradientGrid -from chunk import Chunk -from map import Map -from mapGenerator import CompleteMap BYTES_TRUE = b'\x01' BYTES_FALSE = b'\x00' @@ -389,46 +384,59 @@ def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: #TODO lists def read(path: str) -> object: - bytes_str : bytes - if path!=None: - f=open(path,'rb') - bytes_str=f.read() - f.close() - else: bytes_str=None + from layer import Layer + from gradientGrid import GradientGrid + from chunk import Chunk + from map import Map + from mapGenerator import CompleteMap + + bytes_str : bytes + + if path!=None: + f=open(path,'rb') + bytes_str=f.read() + f.close() + else: bytes_str=None + + if bytes_str!=None: + if bytes_str[0:1]==GradientGrid.GRID_ENCODING: + return GradientGrid.read(None,bytes_str)[0] + elif bytes_str[0:1]==Layer.LAYER_ENCODING: + return Layer.read(None,bytes_str)[0] + elif bytes_str[0:1]==Chunk.CHUNK_ENCODING: + return Chunk.read(None,bytes_str)[0] + elif bytes_str[0:1]==Map.MAP_ENCODING: + return Map.read(None,bytes_str)[0] + elif bytes_str[0:1]==CompleteMap.COMPLETE_MAP_ENCODING: + return CompleteMap.read(None,bytes_str)[0] - if bytes_str!=None: - if bytes_str[0:1]==GradientGrid.GRID_ENCODING: - return GradientGrid.read(None,bytes_str)[0] - elif bytes_str[0:1]==Layer.LAYER_ENCODING: - return Layer.read(None,bytes_str)[0] - elif bytes_str[0:1]==Chunk.CHUNK_ENCODING: - return Chunk.read(None,bytes_str)[0] - elif bytes_str[0:1]==Map.MAP_ENCODING: - return Map.read(None,bytes_str)[0] - elif bytes_str[0:1]==CompleteMap.COMPLETE_MAP_ENCODING: - return CompleteMap.read(None,bytes_str)[0] - - else: return None + else: return None def write(path: str, obj: object): - bytes_str : bytes - if path!=None: - f=open(path,'wb') - bytes_str: bytes + from layer import Layer + from gradientGrid import GradientGrid + from chunk import Chunk + from map import Map + from mapGenerator import CompleteMap + + bytes_str : bytes + if path!=None: + f=open(path,'wb') + bytes_str: bytes + + if type(obj)==GradientGrid: + bytes_str=GradientGrid.write(obj) + elif type(obj)==Layer: + bytes_str=Layer.write(obj,True) + elif type(obj)==Chunk: + bytes_str=Chunk.write(obj) + elif type(obj)==Map: + bytes_str=Map.write(obj) + elif type(obj)==CompleteMap: + bytes_str=CompleteMap.write(obj) - if type(obj)==GradientGrid: - bytes_str+=GradientGrid.write(obj) - elif type(obj)==Layer: - bytes_str+=Layer.write(obj,True) - elif type(obj)==Chunk: - bytes_str+=Chunk.write(obj) - elif type(obj)==Chunk: - bytes_str+=Chunk.write(obj) - elif type(obj)==Map: - bytes_str+=Map.write(obj) - - f.write(bytes_str) - f.close() + f.write(bytes_str) + f.close() @@ -445,9 +453,33 @@ def write(path: str, obj: object): # print(b.name) # print(b.bio.altitude_range) - t = temp() - t.obj=bytearray("A",'utf-8') + # t = temp() + # t.obj=bytearray("A",'utf-8') + + # print(encode(t)) + # print(decode(encode(t),True).obj) + + + + grid_dim = [3, 5] + size_factors = [8, 4] + layer_factors = [1, .1] + map_dimensions = (2, 3) + + print("Generating a new map from scratch with parameters : ") + print(" - map dimensions : ", map_dimensions) + print(" - grids square dimensions : ", grid_dim) + print(" - layers size_factors : ", size_factors) + print(" - chunk layer factors : ", layer_factors) + + from map import Map + map = Map.generateMapFromScratch(grid_dim, grid_dim, size_factors, layer_factors, map_dimensions[0], map_dimensions[1]) + + print(map) + + print("Writing map in file") + write("../saves/testing.data",map) - print(encode(t)) - print(decode(encode(t),True).obj) - \ No newline at end of file + print("Reading map in file") + map=read("../saves/testing.data") + print(map) \ No newline at end of file From a2a07022b1949fcaa50784ed57c29fb61a0a3361 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sat, 27 Jul 2024 13:17:09 +0200 Subject: [PATCH 36/84] lists encoding --- Python/interpreter.py | 72 +++++++++++++++++++++++++++++-------------- 1 file changed, 49 insertions(+), 23 deletions(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index 3f6e08f..06b4456 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -328,10 +328,12 @@ class DecodeDictError(InterpreterError): BYTES_TRUE = b'\x01' BYTES_FALSE = b'\x00' INT_BITS_NBR = 24 #24 should be a multiple of 8 -FLOAT_BITS_EXP = 5 #5 sould be < 8 +FLOAT_BITS_EXP = 5 #5 should be < 8 FLOAT_BITS_MANTISS = 18 FLOAT_BITS_NBR = 1 + FLOAT_BITS_EXP + FLOAT_BITS_MANTISS #24 should be a multiple of 8 +BYTES_VERSION = b'\x00' + def bytesNumber(x : int | float | float64 | uint8) -> bytes: if type(x)==uint8: res=bytes([x]) @@ -383,7 +385,7 @@ def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: #TODO lists -def read(path: str) -> object: +def read(path: str) -> tuple[object, bytes]: from layer import Layer from gradientGrid import GradientGrid from chunk import Chunk @@ -395,48 +397,72 @@ def read(path: str) -> object: if path!=None: f=open(path,'rb') bytes_str=f.read() + if bytes_str[0:1]==BYTES_VERSION: + bytes_str==bytes_str[1:] + else: bytes_str==None f.close() else: bytes_str=None if bytes_str!=None: - if bytes_str[0:1]==GradientGrid.GRID_ENCODING: - return GradientGrid.read(None,bytes_str)[0] + isList=bytes_str[0:1]==BYTES_TRUE + + bytes_str=bytes_str[1:] + + if isList: + nbr, bytes_str = nextInt(bytes_str) + res = [] + for _ in range(nbr): + x, bytes_str = read(bytes_str) + res.append(x) + return res, bytes_str + + elif bytes_str[0:1]==GradientGrid.GRID_ENCODING: + return GradientGrid.read(None,bytes_str) elif bytes_str[0:1]==Layer.LAYER_ENCODING: - return Layer.read(None,bytes_str)[0] + return Layer.read(None,bytes_str) elif bytes_str[0:1]==Chunk.CHUNK_ENCODING: - return Chunk.read(None,bytes_str)[0] + return Chunk.read(None,bytes_str) elif bytes_str[0:1]==Map.MAP_ENCODING: - return Map.read(None,bytes_str)[0] + return Map.read(None,bytes_str) elif bytes_str[0:1]==CompleteMap.COMPLETE_MAP_ENCODING: - return CompleteMap.read(None,bytes_str)[0] + return CompleteMap.read(None,bytes_str) else: return None -def write(path: str, obj: object): +def write(obj: object, path: str): from layer import Layer from gradientGrid import GradientGrid from chunk import Chunk from map import Map from mapGenerator import CompleteMap - bytes_str : bytes + bytes_str: bytes = b'' + bytes_str += BYTES_VERSION + + if type(obj)==list or type(obj)==tuple: + bytes_str += BYTES_TRUE + bytes_str += bytesNumber(len(obj)) + for x in obj: + bytes_str += write(x) + else: bytes_str += BYTES_FALSE + + if type(obj)==GradientGrid: + bytes_str+=GradientGrid.write(obj) + elif type(obj)==Layer: + bytes_str+=Layer.write(obj,True) + elif type(obj)==Chunk: + bytes_str+=Chunk.write(obj) + elif type(obj)==Map: + bytes_str+=Map.write(obj) + elif type(obj)==CompleteMap: + bytes_str+=CompleteMap.write(obj) + if path!=None: f=open(path,'wb') - bytes_str: bytes - - if type(obj)==GradientGrid: - bytes_str=GradientGrid.write(obj) - elif type(obj)==Layer: - bytes_str=Layer.write(obj,True) - elif type(obj)==Chunk: - bytes_str=Chunk.write(obj) - elif type(obj)==Map: - bytes_str=Map.write(obj) - elif type(obj)==CompleteMap: - bytes_str=CompleteMap.write(obj) - f.write(bytes_str) f.close() + + return bytes_str From 61688dc260200cd6d397866d32fcce21dda97f03 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sat, 27 Jul 2024 13:34:01 +0200 Subject: [PATCH 37/84] debugging --- Python/interpreter.py | 68 ++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 37 deletions(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index 06b4456..2d1637c 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -383,9 +383,8 @@ def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: x = uint8(x) return x,bytes_str[1:] -#TODO lists -def read(path: str) -> tuple[object, bytes]: +def read(data_in: str|bytes) -> tuple[object, bytes]: from layer import Layer from gradientGrid import GradientGrid from chunk import Chunk @@ -394,13 +393,18 @@ def read(path: str) -> tuple[object, bytes]: bytes_str : bytes - if path!=None: - f=open(path,'rb') + if type(data_in)==str: + f=open(data_in,'rb') bytes_str=f.read() if bytes_str[0:1]==BYTES_VERSION: - bytes_str==bytes_str[1:] + bytes_str=bytes_str[1:] else: bytes_str==None f.close() + elif type(data_in)==bytes: + bytes_str=data_in + if bytes_str[0:1]==BYTES_VERSION: + bytes_str=bytes_str[1:] + else: bytes_str==None else: bytes_str=None if bytes_str!=None: @@ -429,7 +433,7 @@ def read(path: str) -> tuple[object, bytes]: else: return None -def write(obj: object, path: str): +def write(obj: object, path: str=None): from layer import Layer from gradientGrid import GradientGrid from chunk import Chunk @@ -444,18 +448,19 @@ def write(obj: object, path: str): bytes_str += bytesNumber(len(obj)) for x in obj: bytes_str += write(x) - else: bytes_str += BYTES_FALSE - - if type(obj)==GradientGrid: - bytes_str+=GradientGrid.write(obj) - elif type(obj)==Layer: - bytes_str+=Layer.write(obj,True) - elif type(obj)==Chunk: - bytes_str+=Chunk.write(obj) - elif type(obj)==Map: - bytes_str+=Map.write(obj) - elif type(obj)==CompleteMap: - bytes_str+=CompleteMap.write(obj) + else: + bytes_str += BYTES_FALSE + + if type(obj)==GradientGrid: + bytes_str+=GradientGrid.write(obj) + elif type(obj)==Layer: + bytes_str+=Layer.write(obj,True) + elif type(obj)==Chunk: + bytes_str+=Chunk.write(obj) + elif type(obj)==Map: + bytes_str+=Map.write(obj) + elif type(obj)==CompleteMap: + bytes_str+=CompleteMap.write(obj) if path!=None: f=open(path,'wb') @@ -487,25 +492,14 @@ def write(obj: object, path: str): - grid_dim = [3, 5] - size_factors = [8, 4] - layer_factors = [1, .1] - map_dimensions = (2, 3) - - print("Generating a new map from scratch with parameters : ") - print(" - map dimensions : ", map_dimensions) - print(" - grids square dimensions : ", grid_dim) - print(" - layers size_factors : ", size_factors) - print(" - chunk layer factors : ", layer_factors) - - from map import Map - map = Map.generateMapFromScratch(grid_dim, grid_dim, size_factors, layer_factors, map_dimensions[0], map_dimensions[1]) - - print(map) + from gradientGrid import GradientGrid + + grid = GradientGrid(1, 1) + print(grid) - print("Writing map in file") - write("../saves/testing.data",map) + print("Writing grid in file") + write(grid,"../saves/testing.data") print("Reading map in file") - map=read("../saves/testing.data") - print(map) \ No newline at end of file + gridl=read("../saves/testing.data")[0] + print(gridl) \ No newline at end of file From 7ffc4aee815cacf364ba7a39176f51d4a758833f Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sat, 27 Jul 2024 13:51:33 +0200 Subject: [PATCH 38/84] comments on general functions --- Python/interpreter.py | 102 ++++++++++++++++++++++++++++++++---------- 1 file changed, 78 insertions(+), 24 deletions(-) diff --git a/Python/interpreter.py b/Python/interpreter.py index 2d1637c..e8b0bc8 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -335,64 +335,107 @@ class DecodeDictError(InterpreterError): BYTES_VERSION = b'\x00' def bytesNumber(x : int | float | float64 | uint8) -> bytes: + """Returns the encoding of a given number. + + Args: + x (int | float | float64 | uint8): the given number + + Returns: + bytes: the encoding corresponding + """ if type(x)==uint8: - res=bytes([x]) + res=bytes([x]) #stored on one byte return res - elif type(x)==int and int.bit_length(x)0 else 128 + elif type(x)==int and int.bit_length(x)0 else 128 #sign bit x = abs(x) - l=[temp + x // (2**(INT_BITS_NBR-8))] + [x % (2**(INT_BITS_NBR-i)) // (2**(INT_BITS_NBR-i-8)) for i in range(8,INT_BITS_NBR,8)] + l=[temp + x // (2**(INT_BITS_NBR-8))] + [x % (2**(INT_BITS_NBR-i)) // (2**(INT_BITS_NBR-i-8)) for i in range(8,INT_BITS_NBR,8)] #[sign bit + first numeral bits to get a byte] + [remaining bytes] res = bytes(l) return res - elif type(x)==float or type(x)==float64: - temp = 0 if x>0 else 128 + elif type(x)==float or type(x)==float64: + temp = 0 if x>0 else 128 #sign bit x = abs(x) exp = 0 - if x<2**(FLOAT_BITS_MANTISS): + if x<2**(FLOAT_BITS_MANTISS): #negative exponant while exp>-2**(FLOAT_BITS_EXP-1) and x<2**(FLOAT_BITS_MANTISS-1): exp-=1 x*=2 - else: + else: #positive exponant while exp<2**(FLOAT_BITS_EXP-1)-1 and x>=2**(FLOAT_BITS_MANTISS): exp+=1 x/=2 - exp+=16 + exp+=16 #offsetting exponant x=int(x) - l = [temp + exp*2**(8-(1+FLOAT_BITS_EXP)) + x//2**(FLOAT_BITS_MANTISS-(8-(1+FLOAT_BITS_EXP)))] + l = [temp + exp*2**(8-(1+FLOAT_BITS_EXP)) + x//2**(FLOAT_BITS_MANTISS-(8-(1+FLOAT_BITS_EXP)))] #sign bit + exponant bits + first numeral bits to get a byte + #remaining numeral bytes l += [x%2**(FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP)-i) // (2**(FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP)-i-8)) for i in range(8,FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP),8)] res = bytes(l) return res def nextInt(bytes_str : bytes) -> tuple[int, bytes]: - x = int.from_bytes(bytes_str[:INT_BITS_NBR//8]) - if x//2**23==1: x=-x%2**23 + """Returns the next int from the first bytes of a given byte string. + + Args: + bytes_str (bytes): the given byte string + + Returns: + tuple[int, bytes]: the int and the remaining bytes + """ + x = int.from_bytes(bytes_str[:INT_BITS_NBR//8]) #easier to work with ints + if x//2**23==1: x=-x%2**23 #first bit is a sign bit return x,bytes_str[INT_BITS_NBR//8:] def nextFloat(bytes_str : bytes) -> tuple[float, bytes]: - x = int.from_bytes(bytes_str[:FLOAT_BITS_NBR//8]) - if x//(2**(FLOAT_BITS_NBR-1))==1: s=-1 + """Returns the next float from the first bytes of a given byte string. + + Args: + bytes_str (bytes): the given byte string + + Returns: + tuple[float, bytes]: the float and the remaining bytes + """ + x = int.from_bytes(bytes_str[:FLOAT_BITS_NBR//8]) #easier to work with ints + if x//(2**(FLOAT_BITS_NBR-1))==1: s=-1 #first bit is a sign bit else: s=1 - x=x%(2**(FLOAT_BITS_NBR-1)) - exp=x//(2**(FLOAT_BITS_MANTISS)) - exp-=16 - x=x%(2**(FLOAT_BITS_MANTISS)) - return s*x*2**exp,bytes_str[FLOAT_BITS_NBR//8:] + x=x%(2**(FLOAT_BITS_NBR-1)) #getting rid of first sign bit + exp=x//(2**(FLOAT_BITS_MANTISS)) #obtaining exponants bits + exp-=16 #de-offsetting exponant + x=x%(2**(FLOAT_BITS_MANTISS)) #getting rid of exponants bits + return s*x*2**exp,bytes_str[FLOAT_BITS_NBR//8:] #reconstructing float number def nextUInt8(bytes_str : bytes) -> tuple[uint8, bytes]: + """Returns the next uint8 (numpy) from the first byte of a given byte string. + + Args: + bytes_str (bytes): the byte string + + Returns: + tuple[uint8, bytes]: the uint8 decoded and the remaining bytes + """ x = int.from_bytes(bytes_str[0:1]) x = uint8(x) return x,bytes_str[1:] def read(data_in: str|bytes) -> tuple[object, bytes]: + """Decodes an object from a given binary file or string + + Args: + data_in (str | bytes): either path to file to decode, or bytes to be decoded + + Returns: + tuple[object, bytes]: the decoded object and eventual residual bytes + """ + + #importing objects to be matched from layer import Layer from gradientGrid import GradientGrid from chunk import Chunk from map import Map from mapGenerator import CompleteMap + #bytes to be decoded bytes_str : bytes - if type(data_in)==str: f=open(data_in,'rb') bytes_str=f.read() @@ -407,13 +450,13 @@ def read(data_in: str|bytes) -> tuple[object, bytes]: else: bytes_str==None else: bytes_str=None + #decoding bytes if bytes_str!=None: isList=bytes_str[0:1]==BYTES_TRUE - bytes_str=bytes_str[1:] if isList: - nbr, bytes_str = nextInt(bytes_str) + nbr, bytes_str = nextInt(bytes_str) #number of elements in the list res = [] for _ in range(nbr): x, bytes_str = read(bytes_str) @@ -431,9 +474,20 @@ def read(data_in: str|bytes) -> tuple[object, bytes]: elif bytes_str[0:1]==CompleteMap.COMPLETE_MAP_ENCODING: return CompleteMap.read(None,bytes_str) - else: return None + else: return None #failed + +def write(obj: object, path: str=None) -> bytes: + """Encodes a given object into a binary file or string. + + Args: + obj (object): the object to be encoded + path (str, optional): the file path where to store encoded bytes. Defaults to None. -def write(obj: object, path: str=None): + Returns: + bytes: encoded bytes + """ + + #importing object to match from layer import Layer from gradientGrid import GradientGrid from chunk import Chunk From 4bc6baaa4da9d7fd503fff1ba9b34f1fd10a31c5 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sat, 27 Jul 2024 18:38:16 +0200 Subject: [PATCH 39/84] write func documentation --- Python/chunk.py | 13 ++++++++++++- Python/gradientGrid.py | 17 ++++++++++++++--- Python/layer.py | 13 ++++++++++++- Python/map.py | 16 +++++++++++++--- Python/mapGenerator.py | 10 ++++++++++ 5 files changed, 61 insertions(+), 8 deletions(-) diff --git a/Python/chunk.py b/Python/chunk.py index 24cd83c..6261e0d 100644 --- a/Python/chunk.py +++ b/Python/chunk.py @@ -272,12 +272,23 @@ def newVirtualChunk(chunk_width: int, chunk_height: int, base_altitude: int = No @staticmethod def write(chunk: Chunk, virtual: bool=False, path: str=None, append: bool=False) -> bytes: + """Encodes a Chunk object into a binary file or string. + + Args: + chunk (Chunk): the chunk object to encode + virtual (bool): is it a virtual chunk. Defaults to False. + path (str, optional): path to the file. Defaults to None. + append (bool, optional): should it append the binary string to the end of the file. Defaults to False. + + Returns: + bytes: the encoded bytes + """ bytes_str : bytes = b'' bytes_str += Chunk.CHUNK_ENCODING bytes_str += interp.bytesNumber(chunk.base_altitude) bytes_str += interp.bytesNumber(chunk.width) bytes_str += interp.bytesNumber(chunk.height) - if virtual: + if virtual: #uninitialised values bytes_str += interp.BYTES_TRUE else: bytes_str += interp.BYTES_FALSE diff --git a/Python/gradientGrid.py b/Python/gradientGrid.py index 466bf5a..ad34b8e 100644 --- a/Python/gradientGrid.py +++ b/Python/gradientGrid.py @@ -54,6 +54,16 @@ def setRandomSeed(seed: int | float | str | bytes | bytearray | None = rd.randin @staticmethod def write(grid: GradientGrid, path: str=None, append: bool=False) -> bytes: + """Encodes a GradientGrid object into a binary file or string. + + Args: + grid (GradientGrid): the grid object to encode + path (str, optional): path to the file. Defaults to None. + append (bool, optional): should it append the binary string to the end of the file. Defaults to False. + + Returns: + bytes: the encoded bytes + """ bytes_str : bytes = b'' bytes_str += GradientGrid.GRID_ENCODING bytes_str += interp.bytesNumber(grid.height) @@ -89,7 +99,7 @@ def read(path: str=None, bytes_in : bytes=None) -> tuple[GradientGrid, bytes]: if bytes_str!=None: height, bytes_str = interp.nextInt(bytes_str) width, bytes_str = interp.nextInt(bytes_str) - grid = GradientGrid(width,height) + grid = GradientGrid(width,height,False) for i in range(grid.height): for j in range(grid.width): grid.vectors[i,j,0], bytes_str = interp.nextFloat(bytes_str) @@ -103,7 +113,7 @@ def read(path: str=None, bytes_in : bytes=None) -> tuple[GradientGrid, bytes]: #? ------------------------ Instances ------------------------ # - def __init__(self, width: int = 2, height: int = 2, adjacent_grids: tuple = (None, None, None, None)) -> None: + def __init__(self, width: int = 2, height: int = 2, regenerate: bool = True, adjacent_grids: tuple = (None, None, None, None)) -> None: """Initialize a new random GradientGrid instance with given width and height values. Should be of size `2 x 2` at minimum. A tuple of adjacent GradientGrids can additionally be provided to apply the corresponding boundary conditions with the following order : @@ -112,6 +122,7 @@ def __init__(self, width: int = 2, height: int = 2, adjacent_grids: tuple = (Non Args: `width` (int, optional): the width of the generated random GradientGrid. Defaults to `2`. `height` (int, optional): the height of the generated random GradientGrid. Defaults to `2`. + `regenerate`(bool, optional): if the grid should be (re)generated or not. Defaults to `True`. `adjacent_grids` (tuple, optional): the tuple of adjacent GradientGrids to generate a smooth transition in terrain with correct boundary conditions. The tuple is in order `(NORTH, EAST, SOUTH, WEST)`. @@ -122,7 +133,7 @@ def __init__(self, width: int = 2, height: int = 2, adjacent_grids: tuple = (Non self.width = width self.height = height self.vectors = np.array([[np.zeros((2)) for j in range(self.width)] for i in range(self.height)]) - self.regenerate(adjacent_grids) + if regenerate: self.regenerate(adjacent_grids) diff --git a/Python/layer.py b/Python/layer.py index be1e01e..2b92a18 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -171,11 +171,22 @@ def generateLayerFromScratch(grid_width: int, grid_height: int, size_factor: int @staticmethod def write(layer: Layer, altitude: bool=False, path: str=None, append: bool=False) -> bytes: + """Encodes a Layer object into a binary file or string. + + Args: + layer (Layer): the layer object to encode + altitude (bool, optional): should the altitude be encoded. Defaults to False. + path (str, optional): path to the file. Defaults to None. + append (bool, optional): should it append the binary string to the end of the file. Defaults to False. + + Returns: + bytes: the encoded bytes + """ bytes_str : bytes = b'' bytes_str += Layer.LAYER_ENCODING bytes_str += interp.bytesNumber(layer.size_factor) bytes_str += GradientGrid.write(layer.grid) - if altitude: + if altitude: #altitude values (optional) bytes_str += interp.BYTES_TRUE for i in range(layer.height): for j in range(layer.width): diff --git a/Python/map.py b/Python/map.py index 42f62ac..501ea5d 100644 --- a/Python/map.py +++ b/Python/map.py @@ -115,15 +115,25 @@ def generateMapFromScratch(grid_widths: list[int], grid_heights: list[int], size @staticmethod def write(map: Map, path: str=None, append: bool=False) -> bytes: + """Encodes a Map object into a binary file or string. + + Args: + map (Map): the map object to encode + path (str, optional): path to the file. Defaults to None. + append (bool, optional): should it append the binary string to the end of the file. Defaults to False. + + Returns: + bytes: the encoded bytes + """ bytes_str : bytes = b'' bytes_str += Map.MAP_ENCODING bytes_str += interp.bytesNumber(map.map_height) bytes_str += interp.bytesNumber(map.map_width) - for i in range(map.map_height): + for i in range(map.map_height): #proper chunks for j in range(map.map_width): bytes_str += Chunk.write(map.chunks[i][j]) - n = 2 * (map.map_width+2) + 2 * map.map_height - for i in range(n): + n = 2 * (map.map_width+2) + 2 * map.map_height #nbr of virtual chunks + for i in range(n): #virtual chunks bytes_str += Chunk.write(map.virtual_chunks[i],True) if path!=None: if append: f=open(path,"ab") diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index 3b820ab..fc69b57 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -99,6 +99,16 @@ def generateCompleteMapFromScratch(grid_widths: list[int], grid_heights: list[in @staticmethod def write(complete_map: CompleteMap, path: str=None, append: bool=False) -> bytes: + """Encodes a CompleteMap object into a binary file or string. + + Args: + complete_map (CompleteMap): the complete map object to encode + path (str, optional): path to the file. Defaults to None. + append (bool, optional): should it append the binary string to the end of the file. Defaults to False. + + Returns: + bytes: the encoded bytes + """ bytes_str : bytes = b'' bytes_str += CompleteMap.COMPLETE_MAP_ENCODING bytes_str += Map.write(complete_map.map) From 70c42592c65f37b8005041c1a93178299fdc36d7 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sat, 27 Jul 2024 18:52:05 +0200 Subject: [PATCH 40/84] read func doc --- Python/chunk.py | 23 ++++++++++++++++++----- Python/gradientGrid.py | 9 +++++++++ Python/layer.py | 22 ++++++++++++++++++---- Python/map.py | 15 ++++++++++++++- Python/mapGenerator.py | 10 ++++++++++ 5 files changed, 69 insertions(+), 10 deletions(-) diff --git a/Python/chunk.py b/Python/chunk.py index 6261e0d..b1728c2 100644 --- a/Python/chunk.py +++ b/Python/chunk.py @@ -311,6 +311,15 @@ def write(chunk: Chunk, virtual: bool=False, path: str=None, append: bool=False) @staticmethod def read(path: str, bytes_in : bytes=None) -> tuple[Chunk, bytes]: + """Decodes a Chunk object from a binary file or a bytes string. + + Args: + path (str, optional): path to the binary file. Defaults to None. + bytes_in (bytes, optional): encoded bytes. Defaults to None. + + Returns: + tuple[Chunk, bytes]: the chunk object and remaining bytes + """ bytes_str : bytes if path!=None: f=open(path,'rb') @@ -328,10 +337,10 @@ def read(path: str, bytes_in : bytes=None) -> tuple[Chunk, bytes]: base_altitude, bytes_str = interp.nextFloat(bytes_str) height, bytes_str = interp.nextInt(bytes_str) width, bytes_str = interp.nextInt(bytes_str) - if bytes_str[0:1]==interp.BYTES_TRUE: + if bytes_str[0:1]==interp.BYTES_TRUE: #is virtual chunk chunk = Chunk.newVirtualChunk(width, height, base_altitude) bytes_str = bytes_str[1:] - else: + else: #is proper chunk bytes_str = bytes_str[1:] layer_number, bytes_str = interp.nextInt(bytes_str) layers: list[Layer] = [] @@ -356,13 +365,14 @@ def read(path: str, bytes_in : bytes=None) -> tuple[Chunk, bytes]: #? ------------------------ Instances ------------------------ # - def __init__(self, layers: list[Layer], layers_factors: list[float], regenerate = True) -> None: + def __init__(self, layers: list[Layer], layers_factors: list[float], regenerate: bool = True) -> None: """Initializes a new Chunk structure from the given list of already existing layers and factors. If layers should be generated in the process, please use one of the designated static methods. Args: - `layers` (list[Layer], optional): the list of existing chunks to be averaged to generate the chunk. - `layers_factors` (list[float], optional): the list of factors to be used in the weighted average to generate the chunk. + `layers` (list[Layer]): the list of existing chunks to be averaged to generate the chunk. + `layers_factors` (list[float]): the list of factors to be used in the weighted average to generate the chunk. + `regenerate`(bool, optional): should altitude values be (re)generated. Defaults to `True`. """ self.layers_factors = None @@ -442,6 +452,9 @@ def __str__(self) -> str: def regenerate(self, regenerate: bool = True) -> None: """Regenerates the altitude values of the chunk based on its `layers` and `layer_factors` parameters. + + Args: + `regenerate`(bool, optional): should altitude values be (re)generated. Defaults to `True`. """ #* -------------- Verifications : Begin -------------- diff --git a/Python/gradientGrid.py b/Python/gradientGrid.py index ad34b8e..bfba439 100644 --- a/Python/gradientGrid.py +++ b/Python/gradientGrid.py @@ -83,6 +83,15 @@ def write(grid: GradientGrid, path: str=None, append: bool=False) -> bytes: @staticmethod def read(path: str=None, bytes_in : bytes=None) -> tuple[GradientGrid, bytes]: + """Decodes a GradientGrid object from a binary file or a bytes string. + + Args: + path (str, optional): path to the binary file. Defaults to None. + bytes_in (bytes, optional): encoded bytes. Defaults to None. + + Returns: + tuple[GradientGrid, bytes]: the grid object and remaining bytes + """ bytes_str : bytes if path!=None: f=open(path,'rb') diff --git a/Python/layer.py b/Python/layer.py index 2b92a18..bc50c2b 100644 --- a/Python/layer.py +++ b/Python/layer.py @@ -203,6 +203,16 @@ def write(layer: Layer, altitude: bool=False, path: str=None, append: bool=False @staticmethod def read(path: str = None, bytes_in: bytes=None, altitude: bool=False) -> tuple[Layer, bytes]: + """Decodes a Layer object from a binary file or a bytes string. + + Args: + path (str, optional): path to the binary file. Defaults to None. + bytes_in (bytes, optional): encoded bytes. Defaults to None. + altitude (bool, optional): should eventual altitude values be decoded or regenerated. Defaults to False. + + Returns: + tuple[Layer, bytes]: the layer object and remaining bytes + """ bytes_str : bytes if path!=None: f=open(path,'rb') @@ -219,19 +229,19 @@ def read(path: str = None, bytes_in: bytes=None, altitude: bool=False) -> tuple[ if bytes_str!=None: size_factor, bytes_str = interp.nextInt(bytes_str) grid, bytes_str = GradientGrid.read(None,bytes_str) - if bytes_str[0:1]==interp.BYTES_TRUE: + if bytes_str[0:1]==interp.BYTES_TRUE: #altitude values encoded bytes_str=bytes_str[1:] layer = Layer(grid,size_factor,False) - if altitude: + if altitude: #decoding altitude values layer.altitude=np.zeros((layer.height,layer.width)) for i in range(layer.height): for j in range(layer.width): layer.altitude[i,j], bytes_str = interp.nextFloat(bytes_str) - else: + else: #getting rid of altitude values for i in range(layer.height): for j in range(layer.width): _, bytes_str = interp.nextFloat(bytes_str) - else: + else: #altitude values not encoded, eventually regenerated bytes_str=bytes_str[1:] layer = Layer(grid,size_factor,altitude) @@ -253,6 +263,7 @@ def __init__(self, grid: GradientGrid, size_factor: int, regenerate: bool=True) `grid` (GradientGrid): the gradient grid to build the layer from. `size_factor` (int): the size factor to be used to generate the layer. The layer dimensions will be `(gradient_grid_dimensions - 1) * size_factor`. + `regenerate`(bool, optional): should altitude values be (re)generated. Defaults to `True`. """ self.grid = None @@ -304,6 +315,9 @@ def __str__(self) -> str: def regenerate(self, regenerate: bool=True) -> None: """Regenerates the altitude values of the layer based on its `grid` and `size_factor` parameters. + + Args: + `regenerate`(bool, optional): should altitude values be (re)generated. Defaults to `True`. """ if not (type(self.grid) is GradientGrid and type(self.size_factor) is int and self.size_factor > 1): diff --git a/Python/map.py b/Python/map.py index 501ea5d..8490786 100644 --- a/Python/map.py +++ b/Python/map.py @@ -146,6 +146,15 @@ def write(map: Map, path: str=None, append: bool=False) -> bytes: @staticmethod def read(path: str, bytes_in : bytes=None) -> tuple[Map, bytes]: + """Decodes a Map object from a binary file or a bytes string. + + Args: + path (str, optional): path to the binary file. Defaults to None. + bytes_in (bytes, optional): encoded bytes. Defaults to None. + + Returns: + tuple[Map, bytes]: the map object and remaining bytes + """ bytes_str : bytes if path!=None: f=open(path,'rb') @@ -169,7 +178,7 @@ def read(path: str, bytes_in : bytes=None) -> tuple[Map, bytes]: for _ in range(width): x, bytes_str = Chunk.read(None, bytes_str) chunks[i].append(x) - n = 2 * (width+2) + 2 * height + n = 2 * (width+2) + 2 * height #nbr of virtual chunks for _ in range(n): x, bytes_str = Chunk.read(None, bytes_str) virtual_chunks.append(x) @@ -225,6 +234,7 @@ def __init__(self, map_width: int, map_height: int, chunks: list[list[Chunk]], v `chunks` (list[list[Chunk]]): two-dimension matrix-like structure of chunks. First dimension is height, second is width. `virtual_chunks` (list[Chunk]): list of virtual chunks to generate the map altitudes. Virtual chunks should be stored in the following order : `Column0, ColumnN, Row0, RowN` without any repetition of the corners. + `regenerate`(bool, optional): should altitude values be (re)generated. Defaults to `True`. """ @@ -277,6 +287,9 @@ def __str__(self) -> str: def regenerate(self, regenerate: bool = True) -> None: """Regenerates the altitude values of the map based on its chunks. + + Args: + `regenerate`(bool, optional): should altitude values be (re)generated. Defaults to `True`. """ #* -------------- Verifications : Begin -------------- diff --git a/Python/mapGenerator.py b/Python/mapGenerator.py index fc69b57..5430abc 100644 --- a/Python/mapGenerator.py +++ b/Python/mapGenerator.py @@ -132,6 +132,15 @@ def write(complete_map: CompleteMap, path: str=None, append: bool=False) -> byte @staticmethod def read(path: str, bytes_in : bytes=None) -> tuple[CompleteMap, bytes]: + """Decodes a CompleteMap object from a binary file or a bytes string. + + Args: + path (str, optional): path to the binary file. Defaults to None. + bytes_in (bytes, optional): encoded bytes. Defaults to None. + + Returns: + tuple[CompleteMap, bytes]: the complete map object and remaining bytes + """ bytes_str : bytes if path!=None: f=open(path,'rb') @@ -175,6 +184,7 @@ def __init__(self, map: Map, sea_level: float, regenerate: bool = True) -> None: Args: map (Map): the map structure to build the complete map from. sea_level (float): the altitude of the sea. + regenerate (bool, optional): should sea map and color map be (re)generated """ self.map = None From c82e86c04ffd40262e25cfe1d6920b842ee5750f Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sat, 27 Jul 2024 18:58:46 +0200 Subject: [PATCH 41/84] readAll --- Python/interpreter.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Python/interpreter.py b/Python/interpreter.py index e8b0bc8..81b6440 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -523,6 +523,33 @@ def write(obj: object, path: str=None) -> bytes: return bytes_str +def readAll(data_in: str|bytes) -> list[object]: + """Decodes object from a given binary file or string up to bytes depletion. + + Args: + data_in (str | bytes): path to the file or bytes + + Returns: + list[object]: all decoded ojects + """ + + #bytes to be decoded + bytes_str : bytes + if type(data_in)==str: + f=open(data_in,'rb') + bytes_str=f.read() + f.close() + elif type(data_in)==bytes: + bytes_str=data_in + else: return None + + #decoding + res = [] + while len(bytes_str)>0: + x, bytes_str = read(bytes_str) + res.append(x) + return res + if __name__ == "__main__": From 102d7e6b6ea795f5198cb88c913f5aa716f0ea08 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sat, 27 Jul 2024 22:14:03 +0200 Subject: [PATCH 42/84] C basic file structure --- C/Makefile | 5 ++++- C/headers/interpreter.h | 19 +++++++++++++++++++ C/src/interpreter.c | 16 ++++++++++++++++ C/src/test_interpreter.c | 0 4 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 C/headers/interpreter.h create mode 100644 C/src/interpreter.c create mode 100644 C/src/test_interpreter.c diff --git a/C/Makefile b/C/Makefile index fdb50f2..c5e06cb 100644 --- a/C/Makefile +++ b/C/Makefile @@ -74,8 +74,11 @@ test_map: $(COMP)test_map.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gr test_mapGenerator: $(COMP)test_mapGenerator.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) + +test_interpreter: $(COMP)test_interpreter.o $(COMP)interpeter.o $(COMP)gradientGrid.o $(COMP)loadingBar.o + $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_all : test_unicode test_loadingBar test_gradientGrid test_layer test_chunk test_map test_mapGenerator +test_all : test_unicode test_loadingBar test_gradientGrid test_layer test_chunk test_map test_mapGenerator test_interpreter # Valgrind ---------------------------------- diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h new file mode 100644 index 0000000..79faddf --- /dev/null +++ b/C/headers/interpreter.h @@ -0,0 +1,19 @@ +/** + * @file interpreter.h + * @author BlueNZ + * @brief Header to interpreter functions + * @version 0.1 + * @date 2024-07-27 + * + */ + +#ifndef CHUNK +#define CHUNK + +// ------- Structure definition ------- // + +typedef char byte; + + + +#endif \ No newline at end of file diff --git a/C/src/interpreter.c b/C/src/interpreter.c new file mode 100644 index 0000000..56c91d3 --- /dev/null +++ b/C/src/interpreter.c @@ -0,0 +1,16 @@ +/** + * @file interpreter.c + * @author BlueNZ + * @brief interpreter functions implementation + * @version 0.1 + * @date 2024-07-27 + * + */ + + +#include "interpreter.h" + + + +// ------- Binary functions ------- // + diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c new file mode 100644 index 0000000..e69de29 From be92dbbb23730d5ad03a91ca98b308ddf8ee7b75 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sat, 27 Jul 2024 22:54:13 +0200 Subject: [PATCH 43/84] C encoding numbers --- C/headers/interpreter.h | 18 +++++++++-- C/src/interpreter.c | 67 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index 79faddf..57ca5a6 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -7,13 +7,27 @@ * */ -#ifndef CHUNK -#define CHUNK +#ifndef INTERP +#define INTERP + +#include "map.h" // ------- Structure definition ------- // typedef char byte; +// ------- Constants ------- // + +#define BYTE_TRUE (byte) 1 +#define BYTE_FALSE (byte) 0 +#define INT_BITS_NBR 24 //24 should be a multiple of 8 +#define FLOAT_BITS_EXP 5 //5 should be < 8 +#define FLOAT_BITS_MANTISS 18 +#define FLOAT_BITS_NBR 1 + FLOAT_BITS_EXP + FLOAT_BITS_MANTISS //24 should be a multiple of 8 + +#define BYTES_VERSION (byte) 0 + + #endif \ No newline at end of file diff --git a/C/src/interpreter.c b/C/src/interpreter.c index 56c91d3..04f8542 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -7,10 +7,77 @@ * */ +#include +#include +#include "map.h" #include "interpreter.h" +// ------- General functions ------- // + +int pow(int nbr, int exp) { + if (exp==0) return 1; + else if (exp==1) return nbr; + else if (exp%2==0) return pow(nbr*nbr,exp/2); + else return nbr*pow(nbr,exp-1); +} + + // ------- Binary functions ------- // +byte* bytesUint8(__uint8_t nbr) { + byte* res = malloc(1); + *res = nbr; + return res; +} + +byte* bytesInt(int nbr) { + byte* res = malloc(INT_BITS_NBR/8); + + byte sign = 0; + if (nbr<0) { + sign = 128; + nbr = -nbr; + } + + res[0] = sign + (byte) (nbr/(pow(2,(INT_BITS_NBR-8)))); + for (int i=8; i-pow(2,FLOAT_BITS_EXP-1) && nbr=pow(2,FLOAT_BITS_MANTISS)) { + exp+=1; + nbr/=2; + } + } + exp+=16; + + res[0] = sign + (byte) (exp * pow(2,8-(1+FLOAT_BITS_EXP)) + ((int)nbr)/pow(2,FLOAT_BITS_MANTISS-(8-(1+FLOAT_BITS_EXP)))); + for (int i=8; i Date: Sat, 27 Jul 2024 22:58:38 +0200 Subject: [PATCH 44/84] C encoding number headers --- C/headers/interpreter.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index 57ca5a6..5f09df2 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -30,4 +30,17 @@ typedef char byte; +// ------- Functions ------- // + +int pow(int nbr, int exp); + +byte* bytesUint8(__uint8_t nbr); + +byte* bytesInt(int nbr); + +byte* bytesDouble(double nbr); + + + + #endif \ No newline at end of file From 455b5d4d5f358ff01b74d2e365865230ecab1077 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sat, 27 Jul 2024 23:39:56 +0200 Subject: [PATCH 45/84] C number decoding --- C/headers/interpreter.h | 17 +++++++++++ C/src/interpreter.c | 64 ++++++++++++++++++++++++++++++++++++++++- Python/interpreter.py | 2 +- 3 files changed, 81 insertions(+), 2 deletions(-) diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index 5f09df2..57f4236 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -15,6 +15,13 @@ // ------- Structure definition ------- // typedef char byte; +typedef char* object; //an alias for pointers + +typedef struct tuple_obj_bytes { + object object; + byte* bytes; + int start; +} tuple_obj_bytes; // ------- Constants ------- // @@ -42,5 +49,15 @@ byte* bytesDouble(double nbr); +tuple_obj_bytes* nextUint8(int start, byte* bytes); + +tuple_obj_bytes* nextInt(int start, byte* bytes); + +tuple_obj_bytes* nextDouble(int start, byte* bytes); + + + + + #endif \ No newline at end of file diff --git a/C/src/interpreter.c b/C/src/interpreter.c index 04f8542..c3cce4a 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -17,7 +17,7 @@ // ------- General functions ------- // int pow(int nbr, int exp) { - if (exp==0) return 1; + if (exp<=0) return 1; else if (exp==1) return nbr; else if (exp%2==0) return pow(nbr*nbr,exp/2); else return nbr*pow(nbr,exp-1); @@ -79,5 +79,67 @@ byte* bytesDouble(double nbr) { res[i/8] = (byte) ((((int)nbr) % pow(2,FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP)-i) / pow(2,FLOAT_BITS_MANTISS+(1+FLOAT_BITS_EXP)-i-8))); } + return res; +} + + + +tuple_obj_bytes* nextUint8(int start, byte* bytes) { + tuple_obj_bytes* res = malloc(sizeof(tuple_obj_bytes)); + + __uint8_t* obj = malloc(1); + *obj = bytes[start]; + + res->object = (object) obj; + res->bytes = bytes; + res->start = start+1; + + return res; +} + +tuple_obj_bytes* nextInt(int start, byte* bytes) { + tuple_obj_bytes* res = malloc(sizeof(tuple_obj_bytes)); + + int* obj = malloc(sizeof(int)); + *obj = 0; + for (int i=0; iobject = (object) obj; + res->bytes = bytes; + res->start = start+INT_BITS_NBR/8; + + return res; +} + +tuple_obj_bytes* nextDouble(int start, byte* bytes) { + tuple_obj_bytes* res = malloc(sizeof(tuple_obj_bytes)); + + double* obj = malloc(sizeof(double)); + *obj = 0; + for (int i=0; i=0) *obj = sign * (*obj) * pow(2,exp); + else *obj = sign * (*obj) / pow(2,-exp); + + res->object = (object) obj; + res->bytes = bytes; + res->start = start+1; + return res; } \ No newline at end of file diff --git a/Python/interpreter.py b/Python/interpreter.py index 81b6440..0c3bf99 100644 --- a/Python/interpreter.py +++ b/Python/interpreter.py @@ -382,7 +382,7 @@ def nextInt(bytes_str : bytes) -> tuple[int, bytes]: tuple[int, bytes]: the int and the remaining bytes """ x = int.from_bytes(bytes_str[:INT_BITS_NBR//8]) #easier to work with ints - if x//2**23==1: x=-x%2**23 #first bit is a sign bit + if x//2**(INT_BITS_NBR-1)==1: x=-x%2**(INT_BITS_NBR-1) #first bit is a sign bit return x,bytes_str[INT_BITS_NBR//8:] def nextFloat(bytes_str : bytes) -> tuple[float, bytes]: From acc125c0b73d329ba92e6721a971ea56f9e2000d Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 00:13:26 +0200 Subject: [PATCH 46/84] C number encoding testing --- C/Makefile | 2 +- C/headers/interpreter.h | 2 +- C/src/interpreter.c | 32 +++++++++++++++--------------- C/src/test_interpreter.c | 42 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 18 deletions(-) diff --git a/C/Makefile b/C/Makefile index c5e06cb..acb1beb 100644 --- a/C/Makefile +++ b/C/Makefile @@ -75,7 +75,7 @@ test_map: $(COMP)test_map.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gr test_mapGenerator: $(COMP)test_mapGenerator.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_interpreter: $(COMP)test_interpreter.o $(COMP)interpeter.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) test_all : test_unicode test_loadingBar test_gradientGrid test_layer test_chunk test_map test_mapGenerator test_interpreter diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index 57f4236..9000545 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -39,7 +39,7 @@ typedef struct tuple_obj_bytes { // ------- Functions ------- // -int pow(int nbr, int exp); +int intpow(int nbr, int exp); byte* bytesUint8(__uint8_t nbr); diff --git a/C/src/interpreter.c b/C/src/interpreter.c index c3cce4a..c3c9c1d 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -16,11 +16,11 @@ // ------- General functions ------- // -int pow(int nbr, int exp) { +int intpow(int nbr, int exp) { if (exp<=0) return 1; else if (exp==1) return nbr; - else if (exp%2==0) return pow(nbr*nbr,exp/2); - else return nbr*pow(nbr,exp-1); + else if (exp%2==0) return intpow(nbr*nbr,exp/2); + else return nbr*intpow(nbr,exp-1); } @@ -42,9 +42,9 @@ byte* bytesInt(int nbr) { nbr = -nbr; } - res[0] = sign + (byte) (nbr/(pow(2,(INT_BITS_NBR-8)))); + res[0] = sign + (byte) (nbr/(intpow(2,(INT_BITS_NBR-8)))); for (int i=8; i-pow(2,FLOAT_BITS_EXP-1) && nbr-intpow(2,FLOAT_BITS_EXP-1) && nbr=pow(2,FLOAT_BITS_MANTISS)) { + while (exp=intpow(2,FLOAT_BITS_MANTISS)) { exp+=1; nbr/=2; } } exp+=16; - res[0] = sign + (byte) (exp * pow(2,8-(1+FLOAT_BITS_EXP)) + ((int)nbr)/pow(2,FLOAT_BITS_MANTISS-(8-(1+FLOAT_BITS_EXP)))); + res[0] = sign + (byte) (exp * intpow(2,8-(1+FLOAT_BITS_EXP)) + ((int)nbr)/intpow(2,FLOAT_BITS_MANTISS-(8-(1+FLOAT_BITS_EXP)))); for (int i=8; iobject = (object) obj; res->bytes = bytes; @@ -126,16 +126,16 @@ tuple_obj_bytes* nextDouble(int start, byte* bytes) { } int sign = 1; - if (*obj / pow(2,FLOAT_BITS_NBR-1)==1) { + if (*obj / intpow(2,FLOAT_BITS_NBR-1)==1) { *obj=(long)*obj%FLOAT_BITS_NBR-1; sign = -1; } - int exp = (int)*obj/pow(2,FLOAT_BITS_MANTISS); + int exp = (int)*obj/intpow(2,FLOAT_BITS_MANTISS); exp-=16; - *obj = (long)*obj%pow(2,FLOAT_BITS_MANTISS); - if (exp>=0) *obj = sign * (*obj) * pow(2,exp); - else *obj = sign * (*obj) / pow(2,-exp); + *obj = (long)*obj%intpow(2,FLOAT_BITS_MANTISS); + if (exp>=0) *obj = sign * (*obj) * intpow(2,exp); + else *obj = sign * (*obj) / intpow(2,-exp); res->object = (object) obj; res->bytes = bytes; diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index e69de29..134da4d 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -0,0 +1,42 @@ +/** + * @file test_interpreter.c + * @author BlueNZ + * @brief a testing script for the interpreter functions + * @version 0.1 + * @date 2024-07-27 + * + */ + +#include + +#include "interpreter.h" + +int main() { + + __uint8_t d = 1; + int a=0,e=-5683; + double b=1.3,c=-99.9; + + printf("Encoding some numbers : %d, %d, %d, %f, %f\n",d,a,e,b,c); + + byte* db=bytesUint8(d); + byte* ab=bytesInt(a); + byte* eb=bytesInt(e); + byte* bb=bytesDouble(b); + byte* cb=bytesDouble(c); + + printf("\tUint8 : %d, %d\n",d,*db); + printf("\tint : %d, %d %d %d\n",a,ab[0],ab[1],ab[2]); + printf("\tint : %d, %d %d %d\n",e,eb[0],eb[1],eb[2]); + printf("\tdouble : %f, %d %d %d\n",b,bb[0],bb[1],bb[2]); + printf("\tdouble : %f, %d %d %d\n",c,cb[0],cb[1],cb[2]); + + d = *((__uint8_t*)nextUint8(0,db)->object); + a = *((int*)nextInt(0,ab)->object); + e = *((int*)nextInt(0,eb)->object); + b = *((double*)nextDouble(0,bb)->object); + c = *((double*)nextDouble(0,cb)->object); + + printf("Decoding numbers : %d,%d,%d,%f,%f\n",d,a,e,b,c); + +} \ No newline at end of file From 2b959921a183a3d9eb36991148d2c86c05c8c635 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 11:49:59 +0200 Subject: [PATCH 47/84] C bytes structure --- C/headers/interpreter.h | 9 +++-- C/src/interpreter.c | 73 +++++++++++++++++++++++++---------------- 2 files changed, 51 insertions(+), 31 deletions(-) diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index 9000545..b18e2f4 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -17,10 +17,15 @@ typedef char byte; typedef char* object; //an alias for pointers -typedef struct tuple_obj_bytes { - object object; +typedef struct bytes { byte* bytes; + int size; int start; +} bytes; + +typedef struct tuple_obj_bytes { + object object; + bytes bytes; } tuple_obj_bytes; diff --git a/C/src/interpreter.c b/C/src/interpreter.c index c3c9c1d..c868f73 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -25,16 +25,28 @@ int intpow(int nbr, int exp) { + + // ------- Binary functions ------- // -byte* bytesUint8(__uint8_t nbr) { - byte* res = malloc(1); - *res = nbr; +void freeBytes(bytes b) { + free(b.bytes); +} + +bytes bytesUint8(__uint8_t nbr) { + bytes res; + res.bytes = malloc(1); + res.bytes[0] = nbr; + res.size=1; + res.start=0; return res; } -byte* bytesInt(int nbr) { - byte* res = malloc(INT_BITS_NBR/8); +bytes bytesInt(int nbr) { + bytes res; + res.bytes = malloc(INT_BITS_NBR/8); + res.size=INT_BITS_NBR/8; + res.start=0; byte sign = 0; if (nbr<0) { @@ -42,16 +54,19 @@ byte* bytesInt(int nbr) { nbr = -nbr; } - res[0] = sign + (byte) (nbr/(intpow(2,(INT_BITS_NBR-8)))); + res.bytes[0] = sign + (byte) (nbr/(intpow(2,(INT_BITS_NBR-8)))); for (int i=8; iobject = (object) obj; - res->bytes = bytes; - res->start = start+1; + res.object = (object) obj; + res.bytes = bytes; + bytes.start += 1; return res; } -tuple_obj_bytes* nextInt(int start, byte* bytes) { - tuple_obj_bytes* res = malloc(sizeof(tuple_obj_bytes)); +tuple_obj_bytes nextInt(bytes bytes) { + tuple_obj_bytes res; int* obj = malloc(sizeof(int)); *obj = 0; for (int i=0; iobject = (object) obj; - res->bytes = bytes; - res->start = start+INT_BITS_NBR/8; + res.object = (object) obj; + res.bytes = bytes; + bytes.start = bytes.start+INT_BITS_NBR/8; return res; } -tuple_obj_bytes* nextDouble(int start, byte* bytes) { - tuple_obj_bytes* res = malloc(sizeof(tuple_obj_bytes)); +tuple_obj_bytes nextDouble(bytes bytes) { + tuple_obj_bytes res; double* obj = malloc(sizeof(double)); *obj = 0; for (int i=0; i=0) *obj = sign * (*obj) * intpow(2,exp); else *obj = sign * (*obj) / intpow(2,-exp); - res->object = (object) obj; - res->bytes = bytes; - res->start = start+1; + res.object = (object) obj; + res.bytes = bytes; + bytes.start = bytes.start+FLOAT_BITS_NBR/8; return res; } \ No newline at end of file From d78b977bf52454fa306d1cc78622f23eb705222d Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 11:51:00 +0200 Subject: [PATCH 48/84] C headers changes --- C/headers/interpreter.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index b18e2f4..816ed12 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -46,19 +46,19 @@ typedef struct tuple_obj_bytes { int intpow(int nbr, int exp); -byte* bytesUint8(__uint8_t nbr); +bytes bytesUint8(__uint8_t nbr); -byte* bytesInt(int nbr); +bytes bytesInt(int nbr); -byte* bytesDouble(double nbr); +bytes bytesDouble(double nbr); -tuple_obj_bytes* nextUint8(int start, byte* bytes); +tuple_obj_bytes nextUint8(bytes bytes); -tuple_obj_bytes* nextInt(int start, byte* bytes); +tuple_obj_bytes nextInt(bytes bytes); -tuple_obj_bytes* nextDouble(int start, byte* bytes); +tuple_obj_bytes nextDouble(bytes bytes); From 537beeb642efb94d510f52baf96eb22e542ab3cd Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 13:12:34 +0200 Subject: [PATCH 49/84] C testing binary number encoding --- C/headers/interpreter.h | 14 ++++++++-- C/src/interpreter.c | 28 ++++++++++++++++++++ C/src/test_interpreter.c | 55 +++++++++++++++++++++++++++++----------- 3 files changed, 80 insertions(+), 17 deletions(-) diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index 816ed12..2c9dfb1 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -14,7 +14,7 @@ // ------- Structure definition ------- // -typedef char byte; +typedef unsigned char byte; typedef char* object; //an alias for pointers typedef struct bytes { @@ -36,7 +36,7 @@ typedef struct tuple_obj_bytes { #define INT_BITS_NBR 24 //24 should be a multiple of 8 #define FLOAT_BITS_EXP 5 //5 should be < 8 #define FLOAT_BITS_MANTISS 18 -#define FLOAT_BITS_NBR 1 + FLOAT_BITS_EXP + FLOAT_BITS_MANTISS //24 should be a multiple of 8 +#define FLOAT_BITS_NBR (1 + FLOAT_BITS_EXP + FLOAT_BITS_MANTISS) //24 should be a multiple of 8 #define BYTES_VERSION (byte) 0 @@ -46,6 +46,16 @@ typedef struct tuple_obj_bytes { int intpow(int nbr, int exp); + + +void freeBytes(bytes b); + +char* hex(unsigned char c, char* res); + +void printBytes(bytes bytes, char* start, char* end); + + + bytes bytesUint8(__uint8_t nbr); bytes bytesInt(int nbr); diff --git a/C/src/interpreter.c b/C/src/interpreter.c index c868f73..0bf07df 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -33,6 +33,34 @@ void freeBytes(bytes b) { free(b.bytes); } +char* hex(unsigned char c, char* res) { + int a = c/16; + int b = c%16; + sprintf(res,"%x%x",a,b); + return res; +} + +void printBytes(bytes bytes, char* start, char* end) { + char* bytes_str=malloc(bytes.size * 2+4); + bytes_str[0] = 'b'; + bytes_str[1] = '\''; + bytes_str[bytes.size * 2+2] = '\''; + bytes_str[bytes.size * 2+3] = '\0'; + + for (int i=0; i +#include #include "interpreter.h" @@ -19,24 +20,48 @@ int main() { printf("Encoding some numbers : %d, %d, %d, %f, %f\n",d,a,e,b,c); - byte* db=bytesUint8(d); - byte* ab=bytesInt(a); - byte* eb=bytesInt(e); - byte* bb=bytesDouble(b); - byte* cb=bytesDouble(c); + bytes db=bytesUint8(d); + bytes ab=bytesInt(a); + bytes eb=bytesInt(e); + bytes bb=bytesDouble(b); + bytes cb=bytesDouble(c); - printf("\tUint8 : %d, %d\n",d,*db); - printf("\tint : %d, %d %d %d\n",a,ab[0],ab[1],ab[2]); - printf("\tint : %d, %d %d %d\n",e,eb[0],eb[1],eb[2]); - printf("\tdouble : %f, %d %d %d\n",b,bb[0],bb[1],bb[2]); - printf("\tdouble : %f, %d %d %d\n",c,cb[0],cb[1],cb[2]); + printf("\tUint8 : %d, ",d); + printBytes(db,"","\n"); + printf("\tint : %d, ",a); + printBytes(ab,"","\n"); + printf("\tint : %d, ",e); + printBytes(eb,"","\n"); + printf("\tdouble : %lf, ",b); + printBytes(bb,"","\n"); + printf("\tdouble : %lf, ",c); + printBytes(cb,"","\n"); - d = *((__uint8_t*)nextUint8(0,db)->object); - a = *((int*)nextInt(0,ab)->object); - e = *((int*)nextInt(0,eb)->object); - b = *((double*)nextDouble(0,bb)->object); - c = *((double*)nextDouble(0,cb)->object); + object od = nextUint8(db).object; + object oa = nextInt(ab).object; + object oe = nextInt(eb).object; + object ob = nextDouble(bb).object; + object oc = nextDouble(cb).object; + + d = *((__uint8_t*)od); + a = *((int*)oa); + e = *((int*)oe); + b = *((double*)ob); + c = *((double*)oc); + + free(od); + free(oa); + free(oe); + free(ob); + free(oc); + + freeBytes(db); + freeBytes(ab); + freeBytes(eb); + freeBytes(bb); + freeBytes(cb); printf("Decoding numbers : %d,%d,%d,%f,%f\n",d,a,e,b,c); + return 0; } \ No newline at end of file From 4e275858f98220f267eb5191a7c7a4ea47f7d7b2 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 13:15:29 +0200 Subject: [PATCH 50/84] C decoding ints --- C/src/interpreter.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C/src/interpreter.c b/C/src/interpreter.c index 0bf07df..acba162 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -149,7 +149,7 @@ tuple_obj_bytes nextInt(bytes bytes) { *obj*=256; *obj+=bytes.bytes[bytes.start+i]; } - if (*obj / intpow(2,INT_BITS_NBR-1)==1) *obj=-(*obj%INT_BITS_NBR-1); + if (((unsigned int)*obj) / intpow(2,INT_BITS_NBR-1)==1) *obj=-(((unsigned int)*obj)%intpow(2,INT_BITS_NBR-1)); res.object = (object) obj; res.bytes = bytes; From fcafdcae6d1eb100659fc35d39c40a9cc64929fa Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 13:21:42 +0200 Subject: [PATCH 51/84] C number decoding --- C/src/interpreter.c | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/C/src/interpreter.c b/C/src/interpreter.c index acba162..5be609d 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -144,12 +144,15 @@ tuple_obj_bytes nextInt(bytes bytes) { tuple_obj_bytes res; int* obj = malloc(sizeof(int)); - *obj = 0; + *obj = 1; + + unsigned int temp = 0; for (int i=0; i=0) *obj = sign * (*obj) * intpow(2,exp); - else *obj = sign * (*obj) / intpow(2,-exp); + temp = temp%intpow(2,FLOAT_BITS_MANTISS); + if (exp>=0) *obj = sign * ((double)temp) * intpow(2,exp); + else *obj = sign * ((double)temp) / intpow(2,-exp); res.object = (object) obj; res.bytes = bytes; From bb7ef8f297a2e22dfb63231c76dc05844dbc8972 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 17:58:51 +0200 Subject: [PATCH 52/84] C debugging double decoding --- C/src/interpreter.c | 2 +- C/src/test_interpreter.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/C/src/interpreter.c b/C/src/interpreter.c index 5be609d..e6470fb 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -175,7 +175,7 @@ tuple_obj_bytes nextDouble(bytes bytes) { int sign = 1; if (temp / intpow(2,FLOAT_BITS_NBR-1)==1) { - temp=temp%FLOAT_BITS_NBR-1; + temp=temp%intpow(2,FLOAT_BITS_NBR-1); sign = -1; } diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index a8f3cd2..fa97b7a 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -61,7 +61,7 @@ int main() { freeBytes(bb); freeBytes(cb); - printf("Decoding numbers : %d,%d,%d,%f,%f\n",d,a,e,b,c); + printf("Decoding numbers : %d, %d, %d, %f, %f\n",d,a,e,b,c); return 0; } \ No newline at end of file From 0151a3089559a44d1b7f78ad3cf0525b7fa912c4 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 18:35:50 +0200 Subject: [PATCH 53/84] C gradgrid encoding --- C/Makefile | 2 +- C/headers/gradientGrid.h | 5 +++++ C/headers/interpreter.h | 10 ++++++++-- C/src/gradientGrid.c | 36 ++++++++++++++++++++++++++++++++++-- C/src/interpreter.c | 8 ++++++++ C/src/test_interpreter.c | 10 +++++++++- 6 files changed, 65 insertions(+), 6 deletions(-) diff --git a/C/Makefile b/C/Makefile index acb1beb..1494b7d 100644 --- a/C/Makefile +++ b/C/Makefile @@ -75,7 +75,7 @@ test_map: $(COMP)test_map.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gr test_mapGenerator: $(COMP)test_mapGenerator.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o +test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) test_all : test_unicode test_loadingBar test_gradientGrid test_layer test_chunk test_map test_mapGenerator test_interpreter diff --git a/C/headers/gradientGrid.h b/C/headers/gradientGrid.h index bfa0f56..d883a8a 100644 --- a/C/headers/gradientGrid.h +++ b/C/headers/gradientGrid.h @@ -10,6 +10,8 @@ #ifndef GRADIENT_GRID #define GRADIENT_GRID +#include "interpreter.h" + // ----- Structure definition ----- /** @@ -145,6 +147,9 @@ gradientGrid* readGradientGridFile(char path[]); +bytes bytesGradientGrid(gradientGrid* grid); + + /** * @brief Prints in the terminal the given gradient grid. * diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index 2c9dfb1..13d6da5 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -10,8 +10,6 @@ #ifndef INTERP #define INTERP -#include "map.h" - // ------- Structure definition ------- // typedef unsigned char byte; @@ -38,6 +36,12 @@ typedef struct tuple_obj_bytes { #define FLOAT_BITS_MANTISS 18 #define FLOAT_BITS_NBR (1 + FLOAT_BITS_EXP + FLOAT_BITS_MANTISS) //24 should be a multiple of 8 +#define GRID_ENCODING (byte) 1 +#define LAYER_ENCODING (byte) 2 +#define CHUNK_ENCODING (byte) 3 +#define MAP_ENCODING (byte) 4 +#define COMPLETE_MAP_ENCODING (byte) 5 + #define BYTES_VERSION (byte) 0 @@ -54,6 +58,8 @@ char* hex(unsigned char c, char* res); void printBytes(bytes bytes, char* start, char* end); +void concatBytes(bytes b, bytes bb, int start); + bytes bytesUint8(__uint8_t nbr); diff --git a/C/src/gradientGrid.c b/C/src/gradientGrid.c index 18798b1..608bbf4 100644 --- a/C/src/gradientGrid.c +++ b/C/src/gradientGrid.c @@ -2,8 +2,8 @@ * @file gradientGrid.c * @author Zyno and BlueNZ * @brief gradientGrid structure implementation - * @version 0.2 - * @date 2024-06-19 + * @version 0.3 + * @date 2024-07-28 * */ @@ -13,6 +13,7 @@ #include #include "loadingBar.h" +#include "interpreter.h" #include "gradientGrid.h" void setRandomSeed(unsigned int seed) @@ -300,6 +301,37 @@ vector* copyVect(vector* vect) +bytes bytesGradientGrid(gradientGrid* grid) { + bytes bytes_str; + bytes_str.bytes = malloc(2*(grid->height*grid->width+1)*INT_BITS_NBR/8+1); + bytes_str.size = 2*(grid->height*grid->width+1)*INT_BITS_NBR/8+1; + bytes_str.start = 0; + + bytes_str.bytes[0] = GRID_ENCODING; + + bytes a = bytesInt(grid->height); + concatBytes(bytes_str, a, 1); + freeBytes(a); + a = bytesInt(grid->width); + concatBytes(bytes_str, a, 1+INT_BITS_NBR/8); + freeBytes(a); + + for (int i=0; iheight; i++) { + for (int j=0; jwidth; j++) { + vector vect = *getVector(grid,j,i); + a = bytesDouble(vect.x); + concatBytes(bytes_str, a, 1 + 2 * INT_BITS_NBR/8 + 2 * (i * grid->width + j) * FLOAT_BITS_NBR/8); + freeBytes(a); + a = bytesDouble(vect.y); + concatBytes(bytes_str, a, 1 + 2 * INT_BITS_NBR/8 + (2 * (i * grid->width + j) + 1) * FLOAT_BITS_NBR/8); + freeBytes(a); + } + } + + return bytes_str; + +} + void writeGradientGridFile(gradientGrid* gradGrid, char path[]) { FILE* f = NULL; diff --git a/C/src/interpreter.c b/C/src/interpreter.c index e6470fb..7297cf3 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -61,6 +61,14 @@ void printBytes(bytes bytes, char* start, char* end) { free(bytes_str); } +void concatBytes(bytes b, bytes bb, int start) { + for (int i=0; i #include "interpreter.h" +#include "gradientGrid.h" int main() { @@ -49,6 +50,8 @@ int main() { b = *((double*)ob); c = *((double*)oc); + printf("Decoding numbers : %d, %d, %d, %f, %f\n\n\n",d,a,e,b,c); + free(od); free(oa); free(oe); @@ -61,7 +64,12 @@ int main() { freeBytes(bb); freeBytes(cb); - printf("Decoding numbers : %d, %d, %d, %f, %f\n",d,a,e,b,c); + + gradientGrid* grid = newRandomGradGrid(1,1,0); + printGradientGrid(grid); + + bytes gridb = bytesGradientGrid(grid); + printBytes(gridb, "", "\n"); return 0; } \ No newline at end of file From 7a4d1692c93da91568dd63d29bae0e2f6f1806ae Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 18:46:58 +0200 Subject: [PATCH 54/84] C gradgrid decoding --- C/headers/gradientGrid.h | 2 ++ C/src/gradientGrid.c | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/C/headers/gradientGrid.h b/C/headers/gradientGrid.h index d883a8a..c296e2c 100644 --- a/C/headers/gradientGrid.h +++ b/C/headers/gradientGrid.h @@ -149,6 +149,8 @@ gradientGrid* readGradientGridFile(char path[]); bytes bytesGradientGrid(gradientGrid* grid); +tuple_obj_bytes nextGradientGrid(bytes bytes); + /** * @brief Prints in the terminal the given gradient grid. diff --git a/C/src/gradientGrid.c b/C/src/gradientGrid.c index 608bbf4..e9a20b1 100644 --- a/C/src/gradientGrid.c +++ b/C/src/gradientGrid.c @@ -332,6 +332,41 @@ bytes bytesGradientGrid(gradientGrid* grid) { } +tuple_obj_bytes nextGradientGrid(bytes bytes) { + tuple_obj_bytes res; + + if (bytes.bytes[1]==GRID_ENCODING) { + bytes.start += 1; + + tuple_obj_bytes a = nextInt(bytes); + int h = *((int*)a.object); + free(a.object); + a = nextInt(bytes); + int w = *((int*)a.object); + free(a.object); + + gradientGrid* obj = newGradGrid(w,h); + + for (int i=0; ix = *((int*)a.object); + free(a.object); + a = nextDouble(bytes); + vect->y = *((int*)a.object); + free(a.object); + } + } + + res.object = (object) obj; + res.bytes = bytes; + bytes.start += 1 + 2 * INT_BITS_NBR/8 + w*h*FLOAT_BITS_NBR/8; + } + + return res; +} + void writeGradientGridFile(gradientGrid* gradGrid, char path[]) { FILE* f = NULL; From 90a6d112e44fab463aee03b20d9bc5d09ef4fa57 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 19:03:00 +0200 Subject: [PATCH 55/84] C testing and debugging grid decoding --- C/src/gradientGrid.c | 11 +++++++---- C/src/interpreter.c | 4 ++-- C/src/test_interpreter.c | 9 ++++++++- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/C/src/gradientGrid.c b/C/src/gradientGrid.c index e9a20b1..294b1a6 100644 --- a/C/src/gradientGrid.c +++ b/C/src/gradientGrid.c @@ -335,14 +335,16 @@ bytes bytesGradientGrid(gradientGrid* grid) { tuple_obj_bytes nextGradientGrid(bytes bytes) { tuple_obj_bytes res; - if (bytes.bytes[1]==GRID_ENCODING) { + if (bytes.bytes[0]==GRID_ENCODING) { bytes.start += 1; tuple_obj_bytes a = nextInt(bytes); int h = *((int*)a.object); + bytes = a.bytes; free(a.object); a = nextInt(bytes); int w = *((int*)a.object); + bytes = a.bytes; free(a.object); gradientGrid* obj = newGradGrid(w,h); @@ -351,17 +353,18 @@ tuple_obj_bytes nextGradientGrid(bytes bytes) { for (int j=0; jx = *((int*)a.object); + vect->x = *((double*)a.object); + bytes = a.bytes; free(a.object); a = nextDouble(bytes); - vect->y = *((int*)a.object); + vect->y = *((double*)a.object); + bytes = a.bytes; free(a.object); } } res.object = (object) obj; res.bytes = bytes; - bytes.start += 1 + 2 * INT_BITS_NBR/8 + w*h*FLOAT_BITS_NBR/8; } return res; diff --git a/C/src/interpreter.c b/C/src/interpreter.c index 7297cf3..88eed3c 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -164,7 +164,7 @@ tuple_obj_bytes nextInt(bytes bytes) { res.object = (object) obj; res.bytes = bytes; - bytes.start = bytes.start+INT_BITS_NBR/8; + res.bytes.start += INT_BITS_NBR/8; return res; } @@ -195,7 +195,7 @@ tuple_obj_bytes nextDouble(bytes bytes) { res.object = (object) obj; res.bytes = bytes; - bytes.start = bytes.start+FLOAT_BITS_NBR/8; + res.bytes.start += FLOAT_BITS_NBR/8; return res; } \ No newline at end of file diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index 26c942e..f37d00a 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -17,7 +17,7 @@ int main() { __uint8_t d = 1; int a=0,e=-5683; - double b=1.3,c=-99.9; + double b=1.3,c=-0.394383; printf("Encoding some numbers : %d, %d, %d, %f, %f\n",d,a,e,b,c); @@ -71,5 +71,12 @@ int main() { bytes gridb = bytesGradientGrid(grid); printBytes(gridb, "", "\n"); + gradientGrid* gridd = ((gradientGrid*)nextGradientGrid(gridb).object); + printGradientGrid(gridd); + + freeGradGrid(grid); + freeBytes(gridb); + freeGradGrid(gridd); + return 0; } \ No newline at end of file From 90eeb839b1d48e14dc0bfd345aa81d96fbb56330 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 19:20:29 +0200 Subject: [PATCH 56/84] C layer encoding --- C/headers/layer.h | 10 ++++++ C/src/gradientGrid.c | 4 +-- C/src/layer.c | 76 ++++++++++++++++++++++++++++++++++++++-- C/src/test_interpreter.c | 5 +++ 4 files changed, 91 insertions(+), 4 deletions(-) diff --git a/C/headers/layer.h b/C/headers/layer.h index fcc0d48..f83bbb2 100644 --- a/C/headers/layer.h +++ b/C/headers/layer.h @@ -10,7 +10,10 @@ #ifndef LAYER #define LAYER +#include + #include "gradientGrid.h" +#include "interpreter.h" // ----- Structure definition ----- @@ -132,6 +135,13 @@ layer* copyLayer(layer * p_layer); + +bytes bytesLayer(layer* grid); + +tuple_obj_bytes nextLayer(bytes bytes); + + + /** * @brief Writes the layer structure to a file at the given path. * diff --git a/C/src/gradientGrid.c b/C/src/gradientGrid.c index 294b1a6..c054825 100644 --- a/C/src/gradientGrid.c +++ b/C/src/gradientGrid.c @@ -303,8 +303,8 @@ vector* copyVect(vector* vect) bytes bytesGradientGrid(gradientGrid* grid) { bytes bytes_str; - bytes_str.bytes = malloc(2*(grid->height*grid->width+1)*INT_BITS_NBR/8+1); - bytes_str.size = 2*(grid->height*grid->width+1)*INT_BITS_NBR/8+1; + bytes_str.bytes = malloc(2*(grid->height*grid->width)*FLOAT_BITS_NBR/8+2*INT_BITS_NBR/8+1); + bytes_str.size = 2*(grid->height*grid->width)*FLOAT_BITS_NBR/8+2*INT_BITS_NBR/8+1; bytes_str.start = 0; bytes_str.bytes[0] = GRID_ENCODING; diff --git a/C/src/layer.c b/C/src/layer.c index f6f5c5f..774ff75 100644 --- a/C/src/layer.c +++ b/C/src/layer.c @@ -2,8 +2,8 @@ * @file layer.c * @author Zyno and BlueNZ * @brief layer structure and functions implementation - * @version 0.2 - * @date 2024-06-19 + * @version 0.3 + * @date 2024-07-28 * */ @@ -206,6 +206,78 @@ layer* copyLayer(layer * p_layer) +bytes bytesLayer(layer* layer, bool altitude) { + bytes bytes_grid = bytesGradientGrid(layer->gradient_grid); + + bytes bytes_str; + bytes_str.bytes = malloc(2+(altitude?(layer->height*layer->width+1):(1))*FLOAT_BITS_NBR/8+bytes_grid.size); + bytes_str.size = 2+(altitude?(layer->height*layer->width+1):(1))*FLOAT_BITS_NBR/8+bytes_grid.size; + bytes_str.start = 0; + + bytes_str.bytes[0] = LAYER_ENCODING; + + bytes a = bytesDouble(layer->size_factor); + concatBytes(bytes_str, a, 1); + freeBytes(a); + concatBytes(bytes_str, bytes_grid, 1+FLOAT_BITS_NBR/8); + + if (altitude) { + bytes_str.bytes[1 + bytes_grid.size + FLOAT_BITS_NBR/8] = BYTE_TRUE; + for (int i=0; iheight; i++) { + for (int j=0; jwidth; j++) { + a = bytesDouble(*getLayerValue(layer,j,i)); + concatBytes(bytes_str, a, 2 + bytes_grid.size + (1 + 2 * (i * layer->width + j)) * FLOAT_BITS_NBR/8); + freeBytes(a); + } + } + } + else bytes_str.bytes[1 + bytes_grid.size + FLOAT_BITS_NBR/8] = BYTE_FALSE; + + freeBytes(bytes_grid); + + return bytes_str; + +} + +tuple_obj_bytes nextLayer(bytes bytes) { + tuple_obj_bytes res; + + if (bytes.bytes[0]==GRID_ENCODING) { + bytes.start += 1; + + tuple_obj_bytes a = nextInt(bytes); + int h = *((int*)a.object); + bytes = a.bytes; + free(a.object); + a = nextInt(bytes); + int w = *((int*)a.object); + bytes = a.bytes; + free(a.object); + + gradientGrid* obj = newGradGrid(w,h); + + for (int i=0; ix = *((double*)a.object); + bytes = a.bytes; + free(a.object); + a = nextDouble(bytes); + vect->y = *((double*)a.object); + bytes = a.bytes; + free(a.object); + } + } + + res.object = (object) obj; + res.bytes = bytes; + } + + return res; +} + + void writeLayerFile(layer* layer, char path[]) { diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index f37d00a..ba10427 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -78,5 +78,10 @@ int main() { freeBytes(gridb); freeGradGrid(gridd); + printf("\n\n"); + + + + return 0; } \ No newline at end of file From 25e0b4f3f21787b316535f2e7278d498b360cca9 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Sun, 28 Jul 2024 19:30:34 +0200 Subject: [PATCH 57/84] C testing layer encoding --- C/Makefile | 2 +- C/headers/layer.h | 2 +- C/src/layer.c | 10 +++++----- C/src/test_interpreter.c | 39 +++++++++++++++++++++++++++------------ 4 files changed, 34 insertions(+), 19 deletions(-) diff --git a/C/Makefile b/C/Makefile index 1494b7d..21dcc30 100644 --- a/C/Makefile +++ b/C/Makefile @@ -75,7 +75,7 @@ test_map: $(COMP)test_map.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gr test_mapGenerator: $(COMP)test_mapGenerator.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) test_all : test_unicode test_loadingBar test_gradientGrid test_layer test_chunk test_map test_mapGenerator test_interpreter diff --git a/C/headers/layer.h b/C/headers/layer.h index f83bbb2..99fd5e2 100644 --- a/C/headers/layer.h +++ b/C/headers/layer.h @@ -136,7 +136,7 @@ layer* copyLayer(layer * p_layer); -bytes bytesLayer(layer* grid); +bytes bytesLayer(layer* grid, bool altitude); tuple_obj_bytes nextLayer(bytes bytes); diff --git a/C/src/layer.c b/C/src/layer.c index 774ff75..c717165 100644 --- a/C/src/layer.c +++ b/C/src/layer.c @@ -210,23 +210,23 @@ bytes bytesLayer(layer* layer, bool altitude) { bytes bytes_grid = bytesGradientGrid(layer->gradient_grid); bytes bytes_str; - bytes_str.bytes = malloc(2+(altitude?(layer->height*layer->width+1):(1))*FLOAT_BITS_NBR/8+bytes_grid.size); - bytes_str.size = 2+(altitude?(layer->height*layer->width+1):(1))*FLOAT_BITS_NBR/8+bytes_grid.size; + bytes_str.bytes = malloc(2+INT_BITS_NBR/8+(altitude?(layer->height*layer->width):(0))*FLOAT_BITS_NBR/8+bytes_grid.size); + bytes_str.size = 2+INT_BITS_NBR/8+(altitude?(layer->height*layer->width):(0))*FLOAT_BITS_NBR/8+bytes_grid.size; bytes_str.start = 0; bytes_str.bytes[0] = LAYER_ENCODING; - bytes a = bytesDouble(layer->size_factor); + bytes a = bytesInt(layer->size_factor); concatBytes(bytes_str, a, 1); freeBytes(a); concatBytes(bytes_str, bytes_grid, 1+FLOAT_BITS_NBR/8); if (altitude) { - bytes_str.bytes[1 + bytes_grid.size + FLOAT_BITS_NBR/8] = BYTE_TRUE; + bytes_str.bytes[1 + bytes_grid.size + INT_BITS_NBR/8] = BYTE_TRUE; for (int i=0; iheight; i++) { for (int j=0; jwidth; j++) { a = bytesDouble(*getLayerValue(layer,j,i)); - concatBytes(bytes_str, a, 2 + bytes_grid.size + (1 + 2 * (i * layer->width + j)) * FLOAT_BITS_NBR/8); + concatBytes(bytes_str, a, 2 + INT_BITS_NBR/8 + bytes_grid.size + (i * layer->width + j) * FLOAT_BITS_NBR/8); freeBytes(a); } } diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index ba10427..3b69f1c 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -12,6 +12,7 @@ #include "interpreter.h" #include "gradientGrid.h" +#include "layer.h" int main() { @@ -52,6 +53,29 @@ int main() { printf("Decoding numbers : %d, %d, %d, %f, %f\n\n\n",d,a,e,b,c); + + gradientGrid* grid = newRandomGradGrid(1,1,0); + printGradientGrid(grid); + + bytes gridb = bytesGradientGrid(grid); + printBytes(gridb, "", "\n"); + + gradientGrid* gridd = ((gradientGrid*)nextGradientGrid(gridb).object); + printGradientGrid(gridd); + + printf("\n\n"); + + + layer* lay = newLayer(2,2,3,0); + printLayer(lay); + + bytes laybf = bytesLayer(lay,false); + printBytes(laybf,"","\n"); + bytes laybt = bytesLayer(lay,true); + printBytes(laybt,"","\n"); + + + free(od); free(oa); free(oe); @@ -65,23 +89,14 @@ int main() { freeBytes(cb); - gradientGrid* grid = newRandomGradGrid(1,1,0); - printGradientGrid(grid); - - bytes gridb = bytesGradientGrid(grid); - printBytes(gridb, "", "\n"); - - gradientGrid* gridd = ((gradientGrid*)nextGradientGrid(gridb).object); - printGradientGrid(gridd); - freeGradGrid(grid); freeBytes(gridb); freeGradGrid(gridd); - printf("\n\n"); - - + freeLayer(lay); + freeBytes(laybf); + freeBytes(laybt); return 0; } \ No newline at end of file From ae7658e7256c2b20714e823a4282361013e72e75 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Mon, 29 Jul 2024 12:24:51 +0200 Subject: [PATCH 58/84] C decoding layer --- C/headers/layer.h | 4 +-- C/src/gradientGrid.c | 2 +- C/src/layer.c | 76 +++++++++++++++++++++++++------------------- 3 files changed, 46 insertions(+), 36 deletions(-) diff --git a/C/headers/layer.h b/C/headers/layer.h index 99fd5e2..0160183 100644 --- a/C/headers/layer.h +++ b/C/headers/layer.h @@ -106,7 +106,7 @@ double* getLayerValue(layer* layer, int width_idx, int height_idx); * * @note Please be aware that the layer's dimensions are `(gradGrid_dimensions - 1) * size_factor` */ -layer* newLayerFromGradient(gradientGrid* gradient_grid, int size_factor, unsigned int display_loading); +layer* newLayerFromGradient(gradientGrid* gradient_grid, int size_factor, bool altitude, unsigned int display_loading); /** * @brief Generates a new layer structure from scratch with the given parameters. @@ -138,7 +138,7 @@ layer* copyLayer(layer * p_layer); bytes bytesLayer(layer* grid, bool altitude); -tuple_obj_bytes nextLayer(bytes bytes); +tuple_obj_bytes nextLayer(bytes bytes, bool altitude); diff --git a/C/src/gradientGrid.c b/C/src/gradientGrid.c index c054825..2acd44a 100644 --- a/C/src/gradientGrid.c +++ b/C/src/gradientGrid.c @@ -335,7 +335,7 @@ bytes bytesGradientGrid(gradientGrid* grid) { tuple_obj_bytes nextGradientGrid(bytes bytes) { tuple_obj_bytes res; - if (bytes.bytes[0]==GRID_ENCODING) { + if (bytes.bytes[bytes.start]==GRID_ENCODING) { bytes.start += 1; tuple_obj_bytes a = nextInt(bytes); diff --git a/C/src/layer.c b/C/src/layer.c index c717165..ccbfda9 100644 --- a/C/src/layer.c +++ b/C/src/layer.c @@ -116,7 +116,7 @@ double* getLayerValue(layer* layer, int width_idx, int height_idx) -layer* newLayerFromGradient(gradientGrid* gradient_grid, int size_factor, unsigned int display_loading) +layer* newLayerFromGradient(gradientGrid* gradient_grid, int size_factor, bool altitude, unsigned int display_loading) { clock_t start_time = clock(); @@ -129,7 +129,8 @@ layer* newLayerFromGradient(gradientGrid* gradient_grid, int size_factor, unsign // Initialization layer* new_layer = calloc(1, sizeof(layer)); - double* values = calloc(width * height, sizeof(double)); + double* values; + if (altitude) values = calloc(width * height, sizeof(double)); new_layer->width = width; new_layer->height = height; @@ -140,21 +141,23 @@ layer* newLayerFromGradient(gradientGrid* gradient_grid, int size_factor, unsign new_layer->values = values; // Setting correct double values - for (int i = 0; i < height; i++) - { - for (int j = 0; j < width; j++) + if (altitude) { + for (int i = 0; i < height; i++) { - double* value = getLayerValue(new_layer, j, i); + for (int j = 0; j < width; j++) + { + double* value = getLayerValue(new_layer, j, i); - *value = perlin((double) j/size_factor, (double) i/size_factor, gradient_grid); + *value = perlin((double) j/size_factor, (double) i/size_factor, gradient_grid); - if (display_loading != 0) - { - int nb_indents = display_loading - 1; + if (display_loading != 0) + { + int nb_indents = display_loading - 1; - char base_str[100] = "Generating layer... "; + char base_str[100] = "Generating layer... "; - predefined_loading_bar(j + i * width, width * height - 1, NUMBER_OF_SEGMENTS, base_str, nb_indents, start_time); + predefined_loading_bar(j + i * width, width * height - 1, NUMBER_OF_SEGMENTS, base_str, nb_indents, start_time); + } } } } @@ -173,7 +176,7 @@ layer* newLayer(int gradGrid_width, int gradGrid_height, int size_factor, unsign gradientGrid* gradient_grid = newRandomGradGrid(gradGrid_width, gradGrid_height, g_loading); // Generating layer from the new gradientGrid - return newLayerFromGradient(gradient_grid, size_factor, g_loading); + return newLayerFromGradient(gradient_grid, size_factor, true, g_loading); } @@ -239,36 +242,43 @@ bytes bytesLayer(layer* layer, bool altitude) { } -tuple_obj_bytes nextLayer(bytes bytes) { +tuple_obj_bytes nextLayer(bytes bytes, bool altitude) { tuple_obj_bytes res; - if (bytes.bytes[0]==GRID_ENCODING) { + if (bytes.bytes[bytes.start]==LAYER_ENCODING) { bytes.start += 1; tuple_obj_bytes a = nextInt(bytes); - int h = *((int*)a.object); - bytes = a.bytes; - free(a.object); - a = nextInt(bytes); - int w = *((int*)a.object); + int sf = *((int*)a.object); bytes = a.bytes; free(a.object); - gradientGrid* obj = newGradGrid(w,h); - - for (int i=0; ix = *((double*)a.object); - bytes = a.bytes; - free(a.object); - a = nextDouble(bytes); - vect->y = *((double*)a.object); - bytes = a.bytes; - free(a.object); + gradientGrid* grid = ((gradientGrid*)nextGradientGrid(bytes).object); + + layer * obj; + + if (altitude) { + if (bytes.bytes[bytes.start]==BYTE_TRUE) { + bytes.start += 1; + obj = newLayerFromGradient(grid,sf,false,0); + obj->values = calloc(obj->width * obj->height, sizeof(double)); + for (int i=0; iheight; i++) { + for (int j=0; jwidth; j++) { + a = nextDouble(bytes); + *getLayerValue(obj,j,i) = *((double*)a.object); + bytes = a.bytes; + free(a.object); + } + } + } + else { + bytes.start += 1; + obj = newLayerFromGradient(grid,sf,true,0); } } + else { + obj = newLayerFromGradient(grid,sf,false,0); + } res.object = (object) obj; res.bytes = bytes; From e7f2da493fff67495b6253e6c39fa9638cbb9a63 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Mon, 29 Jul 2024 12:46:53 +0200 Subject: [PATCH 59/84] layer decoding testing --- C/src/layer.c | 20 +++++++++++++------- C/src/test_interpreter.c | 13 ++++++++++++- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/C/src/layer.c b/C/src/layer.c index ccbfda9..c3a01f0 100644 --- a/C/src/layer.c +++ b/C/src/layer.c @@ -129,7 +129,7 @@ layer* newLayerFromGradient(gradientGrid* gradient_grid, int size_factor, bool a // Initialization layer* new_layer = calloc(1, sizeof(layer)); - double* values; + double* values = NULL; if (altitude) values = calloc(width * height, sizeof(double)); new_layer->width = width; @@ -253,7 +253,9 @@ tuple_obj_bytes nextLayer(bytes bytes, bool altitude) { bytes = a.bytes; free(a.object); - gradientGrid* grid = ((gradientGrid*)nextGradientGrid(bytes).object); + tuple_obj_bytes temp = nextGradientGrid(bytes); + gradientGrid* grid = ((gradientGrid*)temp.object); + bytes = temp.bytes; layer * obj; @@ -349,16 +351,20 @@ void printLayer(layer* layer) printf("-------------------------------------------\n"); printf("Printing layer of size = (%d, %d)\n\n", height, width); - for (int i = 0; i < height; i++) + if (layer->values!=NULL) { - for (int j = 0; j < width; j++) + for (int i = 0; i < height; i++) { - double* value = getLayerValue(layer, j, i); + for (int j = 0; j < width; j++) + { + double* value = getLayerValue(layer, j, i); - printf("%lf ", *value); + printf("%lf ", *value); + } + printf("\n"); } - printf("\n"); } + else printf("Null values\n"); printf("-------------------------------------------\n"); } diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index 3b69f1c..31e3528 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -74,7 +74,14 @@ int main() { bytes laybt = bytesLayer(lay,true); printBytes(laybt,"","\n"); - + layer* laydff = ((layer*)nextLayer(laybf,false).object); + printLayer(laydff); + layer* laydft = ((layer*)nextLayer(laybf,true).object); + printLayer(laydft); + layer* laydtf = ((layer*)nextLayer(laybt,false).object); + printLayer(laydtf); + layer* laydtt = ((layer*)nextLayer(laybt,true).object); + printLayer(laydtt); free(od); free(oa); @@ -97,6 +104,10 @@ int main() { freeLayer(lay); freeBytes(laybf); freeBytes(laybt); + freeLayer(laydff); + freeLayer(laydft); + freeLayer(laydtf); + freeLayer(laydtt); return 0; } \ No newline at end of file From b809b88317c394c4c537bafd0debed2a27476a1f Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Mon, 29 Jul 2024 15:01:54 +0200 Subject: [PATCH 60/84] C layer decoding altitude or not --- C/src/layer.c | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/C/src/layer.c b/C/src/layer.c index c3a01f0..6d0e2c0 100644 --- a/C/src/layer.c +++ b/C/src/layer.c @@ -259,34 +259,30 @@ tuple_obj_bytes nextLayer(bytes bytes, bool altitude) { layer * obj; - if (altitude) { - if (bytes.bytes[bytes.start]==BYTE_TRUE) { - bytes.start += 1; - obj = newLayerFromGradient(grid,sf,false,0); - obj->values = calloc(obj->width * obj->height, sizeof(double)); - for (int i=0; iheight; i++) { - for (int j=0; jwidth; j++) { - a = nextDouble(bytes); - *getLayerValue(obj,j,i) = *((double*)a.object); - bytes = a.bytes; - free(a.object); - } + if (bytes.bytes[bytes.start]==BYTE_TRUE) { + bytes.start += 1; + obj = newLayerFromGradient(grid,sf,false,0); + if (altitude) obj->values = calloc(obj->width * obj->height, sizeof(double)); + for (int i=0; iheight; i++) { + for (int j=0; jwidth; j++) { + a = nextDouble(bytes); + if (altitude) *getLayerValue(obj,j,i) = *((double*)a.object); + bytes = a.bytes; + free(a.object); } } - else { - bytes.start += 1; - obj = newLayerFromGradient(grid,sf,true,0); - } } else { - obj = newLayerFromGradient(grid,sf,false,0); + bytes.start += 1; + if (altitude) obj = newLayerFromGradient(grid,sf,true,0); + else obj = newLayerFromGradient(grid,sf,false,0); } res.object = (object) obj; res.bytes = bytes; - } - return res; + return res; + } } From beef888724ee91dd3a55f3ae0626776b6261df89 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Mon, 29 Jul 2024 15:35:56 +0200 Subject: [PATCH 61/84] C chunk encoding --- C/Makefile | 2 +- C/headers/chunk.h | 11 +++- C/src/chunk.c | 125 ++++++++++++++++++++++++++++++++++++++- C/src/test_interpreter.c | 1 - 4 files changed, 132 insertions(+), 7 deletions(-) diff --git a/C/Makefile b/C/Makefile index 21dcc30..2a65872 100644 --- a/C/Makefile +++ b/C/Makefile @@ -75,7 +75,7 @@ test_map: $(COMP)test_map.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gr test_mapGenerator: $(COMP)test_mapGenerator.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) test_all : test_unicode test_loadingBar test_gradientGrid test_layer test_chunk test_map test_mapGenerator test_interpreter diff --git a/C/headers/chunk.h b/C/headers/chunk.h index 75c12ad..70029e9 100644 --- a/C/headers/chunk.h +++ b/C/headers/chunk.h @@ -2,8 +2,8 @@ * @file chunk.h * @author Zyno and BlueNZ * @brief Header to chunk structure and functions - * @version 0.2 - * @date 2024-06-19 + * @version 0.3 + * @date 2024-07-29 * */ @@ -233,6 +233,13 @@ chunk* copyChunk(chunk* p_chunk); + +bytes bytesChunk(chunk* chk); + +tuple_obj_bytes nextChunk(bytes bytes); + + + /** * @brief Writes the chunk structure to a file at the given path. * diff --git a/C/src/chunk.c b/C/src/chunk.c index 0db3dba..70dc3f1 100644 --- a/C/src/chunk.c +++ b/C/src/chunk.c @@ -2,8 +2,8 @@ * @file chunk.c * @author Zyno and BlueNZ * @brief chunk structure and functions implementation - * @version 0.2 - * @date 2024-06-19 + * @version 0.3 + * @date 2024-07-27 * */ @@ -197,7 +197,7 @@ chunk* newChunkFromGradients(int width, int height, int number_of_layers, gradie } // Size_factors should match gradient_grids dimensions - 1 - layers[i] = newLayerFromGradient(gradient_grids[i], size_factors[i], g_loading); + layers[i] = newLayerFromGradient(gradient_grids[i], size_factors[i], true, g_loading); if (display_loading != 0) @@ -490,6 +490,125 @@ chunk* copyChunk(chunk* p_chunk) +bytes bytesChunk(chunk* chk) { + bytes bytes_str; + + if (chk->chunk_values==NULL) { //virtual chunk + bytes_str.bytes = malloc(2 + 2*INT_BITS_NBR/8 + FLOAT_BITS_NBR/8); + bytes_str.size = 2 + 2*INT_BITS_NBR/8 + FLOAT_BITS_NBR/8; + bytes_str.start = 0; + + bytes_str.bytes[0] = CHUNK_ENCODING; + + bytes a = bytesDouble(chk->base_altitude); + concatBytes(bytes_str, a, 1); + freeBytes(a); + a = bytesInt(chk->width); + concatBytes(bytes_str, a, 1+FLOAT_BITS_NBR/8); + freeBytes(a); + a = bytesInt(chk->height); + concatBytes(bytes_str, a, 1+FLOAT_BITS_NBR/8+INT_BITS_NBR/8); + freeBytes(a); + + bytes_str.bytes[1+FLOAT_BITS_NBR/8+2*INT_BITS_NBR/8] = BYTE_TRUE; + } + else { + bytes* bytes_layers[chk->number_of_layers]; + int layer_size=0; + for (int i=0; inumber_of_layers; i++) { + bytes bytes_lay = (bytesLayer(chk->layers[i],false)); + bytes_layers[i] = &bytes_lay; + layer_size += bytes_lay.size; + } + + bytes_str.bytes = malloc(2 + 3*INT_BITS_NBR/8 + (chk->height*chk->width+1+chk->number_of_layers)*FLOAT_BITS_NBR/8 + layer_size); + bytes_str.size = 2 + 3*INT_BITS_NBR/8 + (chk->height*chk->width+1+chk->number_of_layers)*FLOAT_BITS_NBR/8 + layer_size; + bytes_str.start = 0; + + bytes_str.bytes[0] = CHUNK_ENCODING; + + bytes a = bytesDouble(chk->base_altitude); + concatBytes(bytes_str, a, 1); + freeBytes(a); + a = bytesInt(chk->width); + concatBytes(bytes_str, a, 1+FLOAT_BITS_NBR/8); + freeBytes(a); + a = bytesInt(chk->height); + concatBytes(bytes_str, a, 1+FLOAT_BITS_NBR/8+INT_BITS_NBR/8); + freeBytes(a); + + bytes_str.bytes[1+FLOAT_BITS_NBR/8+2*INT_BITS_NBR/8] = BYTE_FALSE; + + a = bytesInt(chk->number_of_layers); + concatBytes(bytes_str, a, 2+FLOAT_BITS_NBR/8+2*INT_BITS_NBR/8); + freeBytes(a); + + for (int i=0; inumber_of_layers; i++) { + a = bytesDouble(chk->layers_factors[i]); + concatBytes(bytes_str, a, 2+(i+1)*FLOAT_BITS_NBR/8+3*INT_BITS_NBR/8); + freeBytes(a); + } + + layer_size=0; + for (int i=0; inumber_of_layers; i++) { + concatBytes(bytes_str, *(bytes_layers[i]), 2+(chk->number_of_layers+1)*FLOAT_BITS_NBR/8+3*INT_BITS_NBR/8+layer_size); + layer_size += (bytes_layers[i])->size; + freeBytes(*(bytes_layers[i])); + } + + for (int i=0; iheight; i++) { + for (int j=0; jwidth; j++) { + a = bytesDouble(*getChunkValue(chk,j,i)); + concatBytes(bytes_str, a, 2+(chk->number_of_layers+1)*FLOAT_BITS_NBR/8+3*INT_BITS_NBR/8+layer_size); + freeBytes(a); + } + } + } + + return bytes_str; + +} + +tuple_obj_bytes nextChunk(bytes bytes) { + tuple_obj_bytes res; + + if (bytes.bytes[bytes.start]==CHUNK_ENCODING) { + bytes.start += 1; + + tuple_obj_bytes a = nextInt(bytes); + int h = *((int*)a.object); + bytes = a.bytes; + free(a.object); + a = nextInt(bytes); + int w = *((int*)a.object); + bytes = a.bytes; + free(a.object); + + gradientGrid* obj = newGradGrid(w,h); + + for (int i=0; ix = *((double*)a.object); + bytes = a.bytes; + free(a.object); + a = nextDouble(bytes); + vect->y = *((double*)a.object); + bytes = a.bytes; + free(a.object); + } + } + + res.object = (object) obj; + res.bytes = bytes; + } + + return res; +} + + + void writeChunkFile(chunk* chunk, char path[]) { FILE* f = NULL; diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index 31e3528..c26145a 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -88,7 +88,6 @@ int main() { free(oe); free(ob); free(oc); - freeBytes(db); freeBytes(ab); freeBytes(eb); From 297d3845e543877515c4db16e16ba242414aac3e Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Mon, 29 Jul 2024 16:22:03 +0200 Subject: [PATCH 62/84] C testing and debugging chunk encoding --- C/src/chunk.c | 8 +++++--- C/src/layer.c | 4 ++-- C/src/test_interpreter.c | 13 +++++++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/C/src/chunk.c b/C/src/chunk.c index 70dc3f1..374e2f4 100644 --- a/C/src/chunk.c +++ b/C/src/chunk.c @@ -517,7 +517,8 @@ bytes bytesChunk(chunk* chk) { int layer_size=0; for (int i=0; inumber_of_layers; i++) { bytes bytes_lay = (bytesLayer(chk->layers[i],false)); - bytes_layers[i] = &bytes_lay; + bytes_layers[i] = malloc(sizeof(bytes_lay)); + *bytes_layers[i] = bytes_lay; layer_size += bytes_lay.size; } @@ -545,7 +546,7 @@ bytes bytesChunk(chunk* chk) { for (int i=0; inumber_of_layers; i++) { a = bytesDouble(chk->layers_factors[i]); - concatBytes(bytes_str, a, 2+(i+1)*FLOAT_BITS_NBR/8+3*INT_BITS_NBR/8); + concatBytes(bytes_str, a, 2+(i+1)*(FLOAT_BITS_NBR/8)+3*(INT_BITS_NBR/8)); freeBytes(a); } @@ -554,12 +555,13 @@ bytes bytesChunk(chunk* chk) { concatBytes(bytes_str, *(bytes_layers[i]), 2+(chk->number_of_layers+1)*FLOAT_BITS_NBR/8+3*INT_BITS_NBR/8+layer_size); layer_size += (bytes_layers[i])->size; freeBytes(*(bytes_layers[i])); + free(bytes_layers[i]); } for (int i=0; iheight; i++) { for (int j=0; jwidth; j++) { a = bytesDouble(*getChunkValue(chk,j,i)); - concatBytes(bytes_str, a, 2+(chk->number_of_layers+1)*FLOAT_BITS_NBR/8+3*INT_BITS_NBR/8+layer_size); + concatBytes(bytes_str, a, 2+(chk->number_of_layers+1+i*chk->width+j)*FLOAT_BITS_NBR/8+3*INT_BITS_NBR/8+layer_size); freeBytes(a); } } diff --git a/C/src/layer.c b/C/src/layer.c index 6d0e2c0..53a047a 100644 --- a/C/src/layer.c +++ b/C/src/layer.c @@ -280,9 +280,9 @@ tuple_obj_bytes nextLayer(bytes bytes, bool altitude) { res.object = (object) obj; res.bytes = bytes; - - return res; } + + return res; } diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index c26145a..88a95d4 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -13,6 +13,7 @@ #include "interpreter.h" #include "gradientGrid.h" #include "layer.h" +#include "chunk.h" int main() { @@ -83,6 +84,15 @@ int main() { layer* laydtt = ((layer*)nextLayer(laybt,true).object); printLayer(laydtt); + int grid_size[] = {2}; + int size_factor[] = {3}; + double layer_factor[] = {1.}; + chunk* chk = newChunk(1,grid_size,grid_size,size_factor,layer_factor,0); + printChunk(chk); + + bytes chkb = bytesChunk(chk); + printBytes(chkb,"","\n"); + free(od); free(oa); free(oe); @@ -108,5 +118,8 @@ int main() { freeLayer(laydtf); freeLayer(laydtt); + freeChunk(chk); + freeBytes(chkb); + return 0; } \ No newline at end of file From bbee8bd3c2e3dede18c9dbb4ba48ef2f9f20dfd0 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Mon, 29 Jul 2024 19:42:59 +0200 Subject: [PATCH 63/84] C chunk decoding --- C/headers/chunk.h | 3 +- C/src/chunk.c | 75 +++++++++++++++++++++++++++------------- C/src/test_interpreter.c | 8 +++++ Python/chunk.py | 2 +- 4 files changed, 61 insertions(+), 27 deletions(-) diff --git a/C/headers/chunk.h b/C/headers/chunk.h index 70029e9..e75bc0e 100644 --- a/C/headers/chunk.h +++ b/C/headers/chunk.h @@ -201,8 +201,7 @@ chunk* newChunk(int number_of_layers, int gradGrids_width[number_of_layers], int * * @note The arrays does not need to be dynamically allocated and their content will be copied in the structure. */ -chunk* newVirtualChunk(int number_of_layers, int gradGrids_width[number_of_layers], int gradGrids_height[number_of_layers], int size_factors[number_of_layers], - double layers_factors[number_of_layers]); +chunk* newVirtualChunk(int chunk_width, int chunk_height, bool regenereate); /** diff --git a/C/src/chunk.c b/C/src/chunk.c index 374e2f4..303b905 100644 --- a/C/src/chunk.c +++ b/C/src/chunk.c @@ -272,32 +272,25 @@ chunk* newChunk(int number_of_layers, int gradGrids_width[number_of_layers], int -//TODO ? signature could be changed to avoid passing useless parameters -> `chunk_width` and `chunk_height` instead of `gradGrids_width`, `gradGrids_height` and `size_factors` -chunk* newVirtualChunk(int number_of_layers, int gradGrids_width[number_of_layers], int gradGrids_height[number_of_layers], int size_factors[number_of_layers], double layers_factors[number_of_layers]) +chunk* newVirtualChunk(int chunk_width, int chunk_height, bool regenereate) { chunk* new_chunk = calloc(1, sizeof(chunk)); - new_chunk->number_of_layers = number_of_layers; + new_chunk->number_of_layers = 0; // size_factors should match gradient_grids dimensions - 1 - int width = (gradGrids_width[0] - 1) * size_factors[0]; - int height = (gradGrids_height[0] - 1) * size_factors[0]; + int width = chunk_width; + int height = chunk_height; new_chunk->width = width; new_chunk->height = height; - // copy layer factors to ensure dynamic allocation - double* factors = calloc(number_of_layers, sizeof(double)); - for (int i = 0; i < number_of_layers; i++) - { - factors[i] = layers_factors[i]; - } - new_chunk->layers_factors = factors; + new_chunk->layers_factors = NULL; new_chunk->chunk_values = NULL; new_chunk->layers = NULL; - new_chunk->base_altitude=generateBaseAltitude(); + if (regenereate) new_chunk->base_altitude=generateBaseAltitude(); return new_chunk; } @@ -531,10 +524,10 @@ bytes bytesChunk(chunk* chk) { bytes a = bytesDouble(chk->base_altitude); concatBytes(bytes_str, a, 1); freeBytes(a); - a = bytesInt(chk->width); + a = bytesInt(chk->height); concatBytes(bytes_str, a, 1+FLOAT_BITS_NBR/8); freeBytes(a); - a = bytesInt(chk->height); + a = bytesInt(chk->width); concatBytes(bytes_str, a, 1+FLOAT_BITS_NBR/8+INT_BITS_NBR/8); freeBytes(a); @@ -577,7 +570,11 @@ tuple_obj_bytes nextChunk(bytes bytes) { if (bytes.bytes[bytes.start]==CHUNK_ENCODING) { bytes.start += 1; - tuple_obj_bytes a = nextInt(bytes); + tuple_obj_bytes a = nextDouble(bytes); + double base_altitude = *((double*)a.object); + bytes = a.bytes; + free(a.object); + a = nextInt(bytes); int h = *((int*)a.object); bytes = a.bytes; free(a.object); @@ -586,20 +583,50 @@ tuple_obj_bytes nextChunk(bytes bytes) { bytes = a.bytes; free(a.object); - gradientGrid* obj = newGradGrid(w,h); + chunk* obj; - for (int i=0; ibase_altitude=base_altitude; + } + else { + bytes.start+=1; + obj = newVirtualChunk(w,h,false); + obj->base_altitude=base_altitude; + + a = nextInt(bytes); + int nbr = *((int*)a.object); + bytes = a.bytes; + free(a.object); + + double* layer_factors = calloc(nbr, sizeof(double)); + for (int i=0; ix = *((double*)a.object); + layer_factors[i]=*((double*)a.object); bytes = a.bytes; free(a.object); - a = nextDouble(bytes); - vect->y = *((double*)a.object); + } + obj->layers_factors = layer_factors; + + layer** layers = calloc(nbr, sizeof(layer*)); + for (int i=0; ilayers = layers; + + double* chunk_values = calloc(w * h, sizeof(double)); + for (int i=0; i Date: Tue, 30 Jul 2024 12:48:28 +0200 Subject: [PATCH 64/84] C chunk number of layer decoding --- C/src/chunk.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/C/src/chunk.c b/C/src/chunk.c index 303b905..4af9f5b 100644 --- a/C/src/chunk.c +++ b/C/src/chunk.c @@ -599,6 +599,7 @@ tuple_obj_bytes nextChunk(bytes bytes) { int nbr = *((int*)a.object); bytes = a.bytes; free(a.object); + obj->number_of_layers = nbr; double* layer_factors = calloc(nbr, sizeof(double)); for (int i=0; ilayers = layers; double* chunk_values = calloc(w * h, sizeof(double)); + obj->chunk_values = chunk_values; for (int i=0; i Date: Tue, 30 Jul 2024 21:21:11 +0200 Subject: [PATCH 65/84] Encoding testing --- C/Makefile | 2 +- C/headers/map.h | 8 +++ C/src/chunk.c | 38 ++++++----- C/src/map.c | 142 ++++++++++++++++++++++++++++++++++++++- C/src/test_interpreter.c | 11 +++ 5 files changed, 182 insertions(+), 19 deletions(-) diff --git a/C/Makefile b/C/Makefile index 2a65872..390790c 100644 --- a/C/Makefile +++ b/C/Makefile @@ -75,7 +75,7 @@ test_map: $(COMP)test_map.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gr test_mapGenerator: $(COMP)test_mapGenerator.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) test_all : test_unicode test_loadingBar test_gradientGrid test_layer test_chunk test_map test_mapGenerator test_interpreter diff --git a/C/headers/map.h b/C/headers/map.h index cfd2b86..dc7acea 100644 --- a/C/headers/map.h +++ b/C/headers/map.h @@ -11,6 +11,7 @@ #define MAP #include "chunk.h" +#include "interpreter.h" // ----- Structure definition ----- @@ -162,6 +163,13 @@ map* copyMap(map* p_map) ; + +bytes bytesMap(map* map); + +tuple_obj_bytes nextMap(bytes bytes); + + + /** * @brief Writes the map structure into a file at the given path. * diff --git a/C/src/chunk.c b/C/src/chunk.c index 4af9f5b..d00801d 100644 --- a/C/src/chunk.c +++ b/C/src/chunk.c @@ -708,31 +708,35 @@ void printChunk(chunk* chunk) printf("-------------------------------------------\n"); printf("Printing chunk of size = (%d, %d)\n", height, width); - printf("It has %d layers with factors : {", nb_layer); + if (nb_layer>0) { - for (int k = 0; k < nb_layer; k++) - { - if (k < nb_layer - 1) - { - printf("%lf, ", factors[k]); - } - else + printf("It has %d layers with factors : {", nb_layer); + + for (int k = 0; k < nb_layer; k++) { - printf("%lf}\n", factors[k]); + if (k < nb_layer - 1) + { + printf("%lf, ", factors[k]); + } + else + { + printf("%lf}\n", factors[k]); + } } - } - printf("\n"); + printf("\n"); - for (int i = 0; i < height; i++) - { - for (int j = 0; j < width; j++) + for (int i = 0; i < height; i++) { - double* value = getChunkValue(chunk, j, i); + for (int j = 0; j < width; j++) + { + double* value = getChunkValue(chunk, j, i); - printf("%lf ", *value); + printf("%lf ", *value); + } + printf("\n"); } - printf("\n"); } + else printf("virtual chunk\n"); printf("-------------------------------------------\n"); } diff --git a/C/src/map.c b/C/src/map.c index 923df87..39b4b1f 100644 --- a/C/src/map.c +++ b/C/src/map.c @@ -422,7 +422,10 @@ map* newMap(int number_of_layers, int gradGrids_width[number_of_layers], int gra predefined_loading_bar(j+1,(map_height+2+map_width+2)*2-4, NUMBER_OF_SEGMENTS, base_str, nb_indents, v_start_time); } - current_chunk = newVirtualChunk(number_of_layers, gradGrids_width, gradGrids_height, size_factors, layers_factors); + int width = (gradGrids_width[0] - 1) * size_factors[0]; + int height = (gradGrids_height[0] - 1) * size_factors[0]; + + current_chunk = newVirtualChunk(width, height, true); virtual_chunks[j] = current_chunk; } @@ -487,6 +490,143 @@ map* copyMap(map* p_map) +bytes bytesMap(map* map) { + bytes bytes_str; + + bytes* bytes_chunks[map->map_width * map->map_height]; + int chunk_size=0; + for (int i=0; imap_height; i++) { + for (int j=0; jmap_width; j++) { + bytes bytes_chunk = (bytesChunk(getChunk(map,j,i))); + bytes_chunks[i*map->map_width+j] = calloc(1,sizeof(bytes_chunk)); + *bytes_chunks[i*map->map_width+j] = bytes_chunk; + chunk_size += bytes_chunk.size; + } + } + + int nbr = (map->map_height+2+map->map_width+2)*2-4; + bytes* bytes_vchunks[nbr]; + int vchunk_size=0; + chunk** virtual_chunks = map->virtual_chunks; //! map->vitual_chunks changes value during execution (???) + for (int i=0; ivirtual_chunks,virtual_chunks); + bytes bytes_vchunk = (bytesChunk(virtual_chunks[i])); + bytes_vchunks[i] = calloc(1,sizeof(bytes_vchunk)); + *bytes_vchunks[i] = bytes_vchunk; + vchunk_size += bytes_vchunk.size; + } + + bytes_str.bytes = calloc(1 + 2*INT_BITS_NBR/8 + chunk_size + vchunk_size, sizeof(byte)); + bytes_str.size = 1 + 2*INT_BITS_NBR/8 + chunk_size + vchunk_size; + bytes_str.start = 0; + + bytes_str.bytes[0] = MAP_ENCODING; + + bytes a = bytesInt(map->map_height); + concatBytes(bytes_str, a, 1); + freeBytes(a); + a = bytesInt(map->map_width); + concatBytes(bytes_str, a, 1+INT_BITS_NBR/8); + freeBytes(a); + + chunk_size=0; + for (int i=0; imap_height; i++) { + for (int j=0; jmap_width; j++) { + concatBytes(bytes_str, *(bytes_chunks[i*map->map_width+j]), 1+2*INT_BITS_NBR/8+chunk_size); + chunk_size += (bytes_chunks[i*map->map_width+j])->size; + freeBytes(*(bytes_chunks[i*map->map_width+j])); + free(bytes_chunks[i*map->map_width+j]); + } + } + + vchunk_size=0; + for (int i=0; isize; + freeBytes(*(bytes_vchunks[i])); + free(bytes_vchunks[i]); + } + + return bytes_str; + +} + +tuple_obj_bytes nextMap(bytes bytes) { + tuple_obj_bytes res; + + if (bytes.bytes[bytes.start]==CHUNK_ENCODING) { + bytes.start += 1; + + tuple_obj_bytes a = nextDouble(bytes); + double base_altitude = *((double*)a.object); + bytes = a.bytes; + free(a.object); + a = nextInt(bytes); + int h = *((int*)a.object); + bytes = a.bytes; + free(a.object); + a = nextInt(bytes); + int w = *((int*)a.object); + bytes = a.bytes; + free(a.object); + + chunk* obj; + + if (bytes.bytes[bytes.start]==BYTE_TRUE) { + bytes.start+=1; + obj = newVirtualChunk(w,h,false); + obj->base_altitude=base_altitude; + } + else { + bytes.start+=1; + obj = newVirtualChunk(w,h,false); + obj->base_altitude=base_altitude; + + a = nextInt(bytes); + int nbr = *((int*)a.object); + bytes = a.bytes; + free(a.object); + obj->number_of_layers = nbr; + + double* layer_factors = calloc(nbr, sizeof(double)); + for (int i=0; ilayers_factors = layer_factors; + + layer** layers = calloc(nbr, sizeof(layer*)); + for (int i=0; ilayers = layers; + + double* chunk_values = calloc(w * h, sizeof(double)); + obj->chunk_values = chunk_values; + for (int i=0; i Date: Wed, 31 Jul 2024 12:11:05 +0200 Subject: [PATCH 66/84] C map decoding and testing --- C/headers/map.h | 2 +- C/src/map.c | 72 ++++++++++++---------------------------- C/src/test_interpreter.c | 5 +++ 3 files changed, 27 insertions(+), 52 deletions(-) diff --git a/C/headers/map.h b/C/headers/map.h index dc7acea..350d675 100644 --- a/C/headers/map.h +++ b/C/headers/map.h @@ -125,7 +125,7 @@ map* addMeanAltitude(map* p_map, unsigned int display_loading); * * @note The chunks array does not need to be dynamically allocated and its content will be copied in the structure. */ -map* newMapFromChunks(int map_width, int map_height, chunk* chunks[map_width * map_height], chunk* virtual_chunks[(map_height+2+map_width+2)*2-4], unsigned int display_loading); +map* newMapFromChunks(int map_width, int map_height, chunk* chunks[map_width * map_height], chunk* virtual_chunks[(map_height+2+map_width+2)*2-4], bool regenerate, unsigned int display_loading); /** * @brief Creates a new map from scratch with the given parameters. diff --git a/C/src/map.c b/C/src/map.c index 39b4b1f..dffc169 100644 --- a/C/src/map.c +++ b/C/src/map.c @@ -252,7 +252,7 @@ map* addMeanAltitude(map* p_map, unsigned int display_loading) -map* newMapFromChunks(int map_width, int map_height, chunk* chunks[map_width * map_height], chunk* virtual_chunks[(map_height+2+map_width+2)*2-4], unsigned int display_loading) +map* newMapFromChunks(int map_width, int map_height, chunk* chunks[map_width * map_height], chunk* virtual_chunks[(map_height+2+map_width+2)*2-4], bool regenerate, unsigned int display_loading) { // clock_t start_time = clock(); @@ -321,7 +321,7 @@ map* newMapFromChunks(int map_width, int map_height, chunk* chunks[map_width * m // } - new_map = addMeanAltitude(new_map,display_loading); + if (regenerate) new_map = addMeanAltitude(new_map,display_loading); return new_map; } @@ -431,7 +431,7 @@ map* newMap(int number_of_layers, int gradGrids_width[number_of_layers], int gra } // Generating the map from the new chunks - map* new_map = newMapFromChunks(map_width, map_height, chunks, virtual_chunks, display_loading); + map* new_map = newMapFromChunks(map_width, map_height, chunks, virtual_chunks, true, display_loading); if (display_loading == 1) { @@ -554,70 +554,40 @@ bytes bytesMap(map* map) { tuple_obj_bytes nextMap(bytes bytes) { tuple_obj_bytes res; - if (bytes.bytes[bytes.start]==CHUNK_ENCODING) { + if (bytes.bytes[bytes.start]==MAP_ENCODING) { bytes.start += 1; - tuple_obj_bytes a = nextDouble(bytes); - double base_altitude = *((double*)a.object); + tuple_obj_bytes a = nextInt(bytes); + int map_height = *((int*)a.object); bytes = a.bytes; free(a.object); a = nextInt(bytes); - int h = *((int*)a.object); - bytes = a.bytes; - free(a.object); - a = nextInt(bytes); - int w = *((int*)a.object); + int map_width = *((int*)a.object); bytes = a.bytes; free(a.object); - chunk* obj; + int nbr = (map_height+2+map_width+2)*2-4; - if (bytes.bytes[bytes.start]==BYTE_TRUE) { - bytes.start+=1; - obj = newVirtualChunk(w,h,false); - obj->base_altitude=base_altitude; - } - else { - bytes.start+=1; - obj = newVirtualChunk(w,h,false); - obj->base_altitude=base_altitude; + chunk* chunks [map_height*map_width]; - a = nextInt(bytes); - int nbr = *((int*)a.object); - bytes = a.bytes; - free(a.object); - obj->number_of_layers = nbr; + chunk* vchunks [nbr]; - double* layer_factors = calloc(nbr, sizeof(double)); - for (int i=0; ilayers_factors = layer_factors; - - layer** layers = calloc(nbr, sizeof(layer*)); - for (int i=0; ilayers = layers; - - double* chunk_values = calloc(w * h, sizeof(double)); - obj->chunk_values = chunk_values; - for (int i=0; i Date: Wed, 31 Jul 2024 12:16:09 +0200 Subject: [PATCH 67/84] C ensuring proper functions args in tests --- C/Makefile | 10 +++++----- C/src/test_chunk.c | 4 ++-- C/src/test_layer.c | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/C/Makefile b/C/Makefile index 390790c..9e28607 100644 --- a/C/Makefile +++ b/C/Makefile @@ -60,19 +60,19 @@ test_unicode: $(COMP)test_unicode.o test_loadingBar: $(COMP)test_loadingBar.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ -test_gradientGrid: $(COMP)test_gradientGrid.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_gradientGrid: $(COMP)test_gradientGrid.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(COMP)interpreter.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_layer: $(COMP)test_layer.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_layer: $(COMP)test_layer.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(COMP)interpreter.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_chunk: $(COMP)test_chunk.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_chunk: $(COMP)test_chunk.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(COMP)interpreter.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_map: $(COMP)test_map.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_map: $(COMP)test_map.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(COMP)interpreter.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_mapGenerator: $(COMP)test_mapGenerator.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_mapGenerator: $(COMP)test_mapGenerator.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(COMP)interpreter.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o diff --git a/C/src/test_chunk.c b/C/src/test_chunk.c index 3e40563..eca82bd 100644 --- a/C/src/test_chunk.c +++ b/C/src/test_chunk.c @@ -50,10 +50,10 @@ int main() layer_height1, layer_width1, layer_height2, layer_width2); - layer* layer1 = newLayerFromGradient(gradGrid1, sizeFactor1, display_loading); + layer* layer1 = newLayerFromGradient(gradGrid1, sizeFactor1, true, display_loading); // printLayer(layer1); - layer* layer2 = newLayerFromGradient(gradGrid2, sizeFactor2, display_loading); + layer* layer2 = newLayerFromGradient(gradGrid2, sizeFactor2, true, display_loading); // printLayer(layer2); diff --git a/C/src/test_layer.c b/C/src/test_layer.c index 979d74e..1c9405b 100644 --- a/C/src/test_layer.c +++ b/C/src/test_layer.c @@ -34,7 +34,7 @@ int main() printf("Creating a layer of size (height x width) = (%d x %d)\n", sizeFactor*(height-1), sizeFactor*(width-1)); - layer* layer1 = newLayerFromGradient(gradGrid, sizeFactor, display_loading); + layer* layer1 = newLayerFromGradient(gradGrid, sizeFactor, true, display_loading); printLayer(layer1); From e360774309049bedaaa039649cff3f8b8669af6c Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 31 Jul 2024 14:08:25 +0200 Subject: [PATCH 68/84] C color encoding and decoding + testing --- C/Makefile | 2 +- C/headers/mapGenerator.h | 16 +++- C/src/interpreter.c | 2 +- C/src/mapGenerator.c | 159 ++++++++++++++++++++++++++++++++++++++- C/src/test_interpreter.c | 11 +++ 5 files changed, 184 insertions(+), 6 deletions(-) diff --git a/C/Makefile b/C/Makefile index 9e28607..2ec1a10 100644 --- a/C/Makefile +++ b/C/Makefile @@ -75,7 +75,7 @@ test_map: $(COMP)test_map.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gr test_mapGenerator: $(COMP)test_mapGenerator.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(COMP)interpreter.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) -test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +test_interpreter: $(COMP)test_interpreter.o $(COMP)interpreter.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) test_all : test_unicode test_loadingBar test_gradientGrid test_layer test_chunk test_map test_mapGenerator test_interpreter diff --git a/C/headers/mapGenerator.h b/C/headers/mapGenerator.h index 0efff1c..ef831bb 100644 --- a/C/headers/mapGenerator.h +++ b/C/headers/mapGenerator.h @@ -2,8 +2,8 @@ * @file mapGenerator.h * @author Zyno and BlueNZ * @brief Header to mapGenerator structure and functions - * @version 0.2 - * @date 2024-06-19 + * @version 0.3 + * @date 2024-07-31 * */ @@ -11,6 +11,7 @@ #define MAP_GENERATOR #include "map.h" +#include "interpreter.h" // ----- Structure definition ----- @@ -229,6 +230,17 @@ void printCompleteMap(completeMap* completeMap); + +bytes bytesColor(color c); + +tuple_obj_bytes nextColor(bytes bytes); + +bytes bytesCompleteMap(completeMap* cmap); + +tuple_obj_bytes nextCompleteMap(bytes bytes); + + + /** * @brief Writes the sea_map in a file at the given path. * diff --git a/C/src/interpreter.c b/C/src/interpreter.c index 88eed3c..de4ef55 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -140,10 +140,10 @@ tuple_obj_bytes nextUint8(bytes bytes) { __uint8_t* obj = malloc(1); *obj = bytes.bytes[bytes.start]; + bytes.start += 1; res.object = (object) obj; res.bytes = bytes; - bytes.start += 1; return res; } diff --git a/C/src/mapGenerator.c b/C/src/mapGenerator.c index c545808..3887c6e 100644 --- a/C/src/mapGenerator.c +++ b/C/src/mapGenerator.c @@ -2,8 +2,8 @@ * @file mapGenerator.c * @author Zyno and BlueNZ * @brief mapGenerator structure and functions implementations - * @version 0.2 - * @date 2024-06-19 + * @version 0.3 + * @date 2024-07-31 * */ @@ -500,6 +500,161 @@ completeMap* fullGen(int number_of_layers, int gradGrids_dimension[number_of_lay + +bytes bytesColor(color c) { + bytes res; + res.bytes = malloc(3); + res.size = 3; + res.start = 0; + + bytes a = bytesUint8(c.red); + concatBytes(res,a,0); + freeBytes(a); + + a = bytesUint8(c.green); + concatBytes(res,a,1); + freeBytes(a); + + a = bytesUint8(c.blue); + concatBytes(res,a,2); + freeBytes(a); + + return res; +} + +tuple_obj_bytes nextColor(bytes bytes) { + tuple_obj_bytes res; + + color* c = malloc(sizeof(color)); + + tuple_obj_bytes a = nextUint8(bytes); + c->red = *((__uint8_t*)a.object); + bytes = a.bytes; + free(a.object); + + a = nextUint8(bytes); + c->green = *((__uint8_t*)a.object); + bytes = a.bytes; + free(a.object); + + a = nextUint8(bytes); + c->blue = *((__uint8_t*)a.object); + bytes = a.bytes; + free(a.object); + + res.object = (object)c; + res.bytes = bytes; + + return res; +} + +bytes bytesCompleteMap(completeMap* cmap) { + bytes bytes_str; + + // bytes* bytes_chunks[map->map_width * map->map_height]; + // int chunk_size=0; + // for (int i=0; imap_height; i++) { + // for (int j=0; jmap_width; j++) { + // bytes bytes_chunk = (bytesChunk(getChunk(map,j,i))); + // bytes_chunks[i*map->map_width+j] = calloc(1,sizeof(bytes_chunk)); + // *bytes_chunks[i*map->map_width+j] = bytes_chunk; + // chunk_size += bytes_chunk.size; + // } + // } + + // int nbr = (map->map_height+2+map->map_width+2)*2-4; + // bytes* bytes_vchunks[nbr]; + // int vchunk_size=0; + // chunk** virtual_chunks = map->virtual_chunks; //! map->vitual_chunks changes value during execution (???) + // for (int i=0; ivirtual_chunks,virtual_chunks); + // bytes bytes_vchunk = (bytesChunk(virtual_chunks[i])); + // bytes_vchunks[i] = calloc(1,sizeof(bytes_vchunk)); + // *bytes_vchunks[i] = bytes_vchunk; + // vchunk_size += bytes_vchunk.size; + // } + + // bytes_str.bytes = calloc(1 + 2*INT_BITS_NBR/8 + chunk_size + vchunk_size, sizeof(byte)); + // bytes_str.size = 1 + 2*INT_BITS_NBR/8 + chunk_size + vchunk_size; + // bytes_str.start = 0; + + // bytes_str.bytes[0] = MAP_ENCODING; + + // bytes a = bytesInt(map->map_height); + // concatBytes(bytes_str, a, 1); + // freeBytes(a); + // a = bytesInt(map->map_width); + // concatBytes(bytes_str, a, 1+INT_BITS_NBR/8); + // freeBytes(a); + + // chunk_size=0; + // for (int i=0; imap_height; i++) { + // for (int j=0; jmap_width; j++) { + // concatBytes(bytes_str, *(bytes_chunks[i*map->map_width+j]), 1+2*INT_BITS_NBR/8+chunk_size); + // chunk_size += (bytes_chunks[i*map->map_width+j])->size; + // freeBytes(*(bytes_chunks[i*map->map_width+j])); + // free(bytes_chunks[i*map->map_width+j]); + // } + // } + + // vchunk_size=0; + // for (int i=0; isize; + // freeBytes(*(bytes_vchunks[i])); + // free(bytes_vchunks[i]); + // } + + return bytes_str; + +} + +tuple_obj_bytes nextCompleteMap(bytes bytes) { + tuple_obj_bytes res; + + if (bytes.bytes[bytes.start]==MAP_ENCODING) { + bytes.start += 1; + + tuple_obj_bytes a = nextInt(bytes); + int map_height = *((int*)a.object); + bytes = a.bytes; + free(a.object); + a = nextInt(bytes); + int map_width = *((int*)a.object); + bytes = a.bytes; + free(a.object); + + int nbr = (map_height+2+map_width+2)*2-4; + + chunk* chunks [map_height*map_width]; + + chunk* vchunks [nbr]; + + for (int i=0; ired, cold->green, cold->blue); + + free(od); free(oa); free(oe); @@ -145,5 +154,7 @@ int main() { freeBytes(mb); freeMap(md); + freeBytes(colb); + return 0; } \ No newline at end of file From 57c6f45a908ec34aa2e506fbfde72e2f3b230c9c Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 31 Jul 2024 14:26:05 +0200 Subject: [PATCH 69/84] C completeMap encoding --- C/src/mapGenerator.c | 78 +++++++++++++--------------------------- C/src/test_interpreter.c | 10 ++++++ 2 files changed, 35 insertions(+), 53 deletions(-) diff --git a/C/src/mapGenerator.c b/C/src/mapGenerator.c index 3887c6e..9446078 100644 --- a/C/src/mapGenerator.c +++ b/C/src/mapGenerator.c @@ -551,59 +551,31 @@ tuple_obj_bytes nextColor(bytes bytes) { bytes bytesCompleteMap(completeMap* cmap) { bytes bytes_str; - // bytes* bytes_chunks[map->map_width * map->map_height]; - // int chunk_size=0; - // for (int i=0; imap_height; i++) { - // for (int j=0; jmap_width; j++) { - // bytes bytes_chunk = (bytesChunk(getChunk(map,j,i))); - // bytes_chunks[i*map->map_width+j] = calloc(1,sizeof(bytes_chunk)); - // *bytes_chunks[i*map->map_width+j] = bytes_chunk; - // chunk_size += bytes_chunk.size; - // } - // } - - // int nbr = (map->map_height+2+map->map_width+2)*2-4; - // bytes* bytes_vchunks[nbr]; - // int vchunk_size=0; - // chunk** virtual_chunks = map->virtual_chunks; //! map->vitual_chunks changes value during execution (???) - // for (int i=0; ivirtual_chunks,virtual_chunks); - // bytes bytes_vchunk = (bytesChunk(virtual_chunks[i])); - // bytes_vchunks[i] = calloc(1,sizeof(bytes_vchunk)); - // *bytes_vchunks[i] = bytes_vchunk; - // vchunk_size += bytes_vchunk.size; - // } - - // bytes_str.bytes = calloc(1 + 2*INT_BITS_NBR/8 + chunk_size + vchunk_size, sizeof(byte)); - // bytes_str.size = 1 + 2*INT_BITS_NBR/8 + chunk_size + vchunk_size; - // bytes_str.start = 0; - - // bytes_str.bytes[0] = MAP_ENCODING; - - // bytes a = bytesInt(map->map_height); - // concatBytes(bytes_str, a, 1); - // freeBytes(a); - // a = bytesInt(map->map_width); - // concatBytes(bytes_str, a, 1+INT_BITS_NBR/8); - // freeBytes(a); - - // chunk_size=0; - // for (int i=0; imap_height; i++) { - // for (int j=0; jmap_width; j++) { - // concatBytes(bytes_str, *(bytes_chunks[i*map->map_width+j]), 1+2*INT_BITS_NBR/8+chunk_size); - // chunk_size += (bytes_chunks[i*map->map_width+j])->size; - // freeBytes(*(bytes_chunks[i*map->map_width+j])); - // free(bytes_chunks[i*map->map_width+j]); - // } - // } - - // vchunk_size=0; - // for (int i=0; isize; - // freeBytes(*(bytes_vchunks[i])); - // free(bytes_vchunks[i]); - // } + bytes bytes_map = bytesMap(cmap->map); + + bytes_str.bytes = calloc(1 + bytes_map.size + FLOAT_BITS_NBR/8 + cmap->height*cmap->width * (FLOAT_BITS_NBR/8 + 3), sizeof(byte)); + bytes_str.size = 1 + bytes_map.size + FLOAT_BITS_NBR/8 + cmap->height*cmap->width * (FLOAT_BITS_NBR/8 + 3); + bytes_str.start = 0; + + bytes_str.bytes[0] = COMPLETE_MAP_ENCODING; + + concatBytes(bytes_str,bytes_map,1); + freeBytes(bytes_map); + + bytes a = bytesDouble(cmap->sea_level); + concatBytes(bytes_str, a, 1+bytes_map.size); + freeBytes(a); + + for (int i=0; iheight; i++) { + for (int j=0; jwidth; j++) { + a = bytesDouble(*getCompleteMapSeaValue(cmap,j,i)); + concatBytes(bytes_str, a, 1+bytes_map.size+FLOAT_BITS_NBR/8 + (FLOAT_BITS_NBR/8+3)*(i*cmap->width+j)); + freeBytes(a); + a = bytesColor(*getCompleteMapColor(cmap,j,i)); + concatBytes(bytes_str, a, 1+bytes_map.size+2*FLOAT_BITS_NBR/8 + (FLOAT_BITS_NBR/8+3)*(i*cmap->width+j)); + freeBytes(a); + } + } return bytes_str; diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index e6460ef..2108705 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -120,6 +120,12 @@ int main() { color* cold = ((color*)nextColor(colb).object); printf("color: %u - %u - %u\n", cold->red, cold->green, cold->blue); + completeMap* cmap = newCompleteMap(1,grid_size,grid_size,size_factor,layer_factor,1,1,0,0); + printMap(cmap->map); + bytes cmapb = bytesCompleteMap(cmap); + printBytes(cmapb,"","\n"); + + free(od); free(oa); @@ -155,6 +161,10 @@ int main() { freeMap(md); freeBytes(colb); + free(cold); + + freeCompleteMap(cmap); + freeBytes(cmapb); return 0; } \ No newline at end of file From c5ac0482247fd1dbe704eb425ce36d9253159ebf Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 31 Jul 2024 14:50:51 +0200 Subject: [PATCH 70/84] C completemap decoding and testing --- C/src/mapGenerator.c | 46 +++++++++++++++++++--------------------- C/src/test_interpreter.c | 3 +++ 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/C/src/mapGenerator.c b/C/src/mapGenerator.c index 9446078..0def5ed 100644 --- a/C/src/mapGenerator.c +++ b/C/src/mapGenerator.c @@ -584,41 +584,39 @@ bytes bytesCompleteMap(completeMap* cmap) { tuple_obj_bytes nextCompleteMap(bytes bytes) { tuple_obj_bytes res; - if (bytes.bytes[bytes.start]==MAP_ENCODING) { + if (bytes.bytes[bytes.start]==COMPLETE_MAP_ENCODING) { bytes.start += 1; - tuple_obj_bytes a = nextInt(bytes); - int map_height = *((int*)a.object); - bytes = a.bytes; - free(a.object); - a = nextInt(bytes); - int map_width = *((int*)a.object); + completeMap* cmap = calloc(1,sizeof(completeMap)); + + tuple_obj_bytes a = nextMap(bytes); + cmap->map = ((map*)a.object); bytes = a.bytes; - free(a.object); - int nbr = (map_height+2+map_width+2)*2-4; + cmap->height = cmap->map->chunk_height * cmap->map->map_height; + cmap->width = cmap->map->chunk_width * cmap->map->map_width; - chunk* chunks [map_height*map_width]; + a = nextDouble(bytes); + cmap->sea_level = *((double*)a.object); + bytes = a.bytes; + free(a.object); - chunk* vchunks [nbr]; + cmap->color_map = calloc(cmap->height*cmap->width,sizeof(color*)); + cmap->sea_values = calloc(cmap->height*cmap->width,sizeof(double)); - for (int i=0; iheight; i++) { + for (int j=0; jwidth; j++) { + a = nextDouble(bytes); + *getCompleteMapSeaValue(cmap,j,i) = *((double*)a.object); + bytes = a.bytes; + free(a.object); + a = nextColor(bytes); + cmap->color_map[i*cmap->width+j] = ((color*)a.object); bytes = a.bytes; } } - for (int i=0; imap); bytes cmapb = bytesCompleteMap(cmap); printBytes(cmapb,"","\n"); + completeMap* cmapd = ((completeMap*)nextCompleteMap(cmapb).object); + printMap(cmapd->map); @@ -165,6 +167,7 @@ int main() { freeCompleteMap(cmap); freeBytes(cmapb); + freeCompleteMap(cmapd); return 0; } \ No newline at end of file From 939613a7a6968aecd9c98c8c52766ede02b009f4 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 31 Jul 2024 14:58:53 +0200 Subject: [PATCH 71/84] C testing more readable --- C/src/test_interpreter.c | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index a32b107..e9311cf 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -18,12 +18,13 @@ #include "mapGenerator.h" int main() { + printf("Testing binary encoding and decoding: \n\n\n"); __uint8_t d = 1; int a=0,e=-5683; double b=1.3,c=-0.394383; - printf("Encoding some numbers : %d, %d, %d, %f, %f\n",d,a,e,b,c); + printf("\tEncoding some numbers : %d, %d, %d, %f, %f\n",d,a,e,b,c); bytes db=bytesUint8(d); bytes ab=bytesInt(a); @@ -31,15 +32,15 @@ int main() { bytes bb=bytesDouble(b); bytes cb=bytesDouble(c); - printf("\tUint8 : %d, ",d); + printf("\t\tUint8 : %d, ",d); printBytes(db,"","\n"); - printf("\tint : %d, ",a); + printf("\t\tint : %d, ",a); printBytes(ab,"","\n"); - printf("\tint : %d, ",e); + printf("\t\tint : %d, ",e); printBytes(eb,"","\n"); - printf("\tdouble : %lf, ",b); + printf("\t\tdouble : %lf, ",b); printBytes(bb,"","\n"); - printf("\tdouble : %lf, ",c); + printf("\t\tdouble : %lf, ",c); printBytes(cb,"","\n"); object od = nextUint8(db).object; @@ -54,9 +55,11 @@ int main() { b = *((double*)ob); c = *((double*)oc); - printf("Decoding numbers : %d, %d, %d, %f, %f\n\n\n",d,a,e,b,c); + printf("\tDecoding numbers : %d, %d, %d, %f, %f\n\n\n",d,a,e,b,c); + + printf("\tTesting for gradients:\n"); gradientGrid* grid = newRandomGradGrid(1,1,0); printGradientGrid(grid); @@ -69,6 +72,7 @@ int main() { printf("\n\n"); + printf("\tTesting for layers:\n"); layer* lay = newLayer(2,2,3,0); printLayer(lay); @@ -88,6 +92,7 @@ int main() { + printf("\n\n\tTesting for chunks:\n"); int grid_size[] = {2}; int size_factor[] = {3}; double layer_factor[] = {1.}; @@ -102,6 +107,7 @@ int main() { + printf("\n\n\tTesting for maps:\n"); map* m = newMap(1,grid_size,grid_size,size_factor,layer_factor,1,1,0); printMap(m); @@ -113,6 +119,7 @@ int main() { + printf("\n\n\tTesting for colors:\n"); color col = {255,0,0}; printf("color: %u - %u - %u\n", col.red, col.green, col.blue); bytes colb = bytesColor(col); @@ -120,6 +127,7 @@ int main() { color* cold = ((color*)nextColor(colb).object); printf("color: %u - %u - %u\n", cold->red, cold->green, cold->blue); + printf("\n\n\tTesting for completeMaps:\n"); completeMap* cmap = newCompleteMap(1,grid_size,grid_size,size_factor,layer_factor,1,1,0,0); printMap(cmap->map); bytes cmapb = bytesCompleteMap(cmap); @@ -129,6 +137,7 @@ int main() { + printf("\n\nDeallocating...\n"); free(od); free(oa); free(oe); From 2e504b0bdc1a3c422d294800b738226342666704 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Thu, 1 Aug 2024 21:03:50 +0200 Subject: [PATCH 72/84] C doc encoding --- C/headers/chunk.h | 8 ++++++-- C/headers/gradientGrid.h | 6 ++++++ C/headers/layer.h | 10 ++++++++-- C/headers/map.h | 7 ++++++- C/headers/mapGenerator.h | 13 ++++++++++++- 5 files changed, 38 insertions(+), 6 deletions(-) diff --git a/C/headers/chunk.h b/C/headers/chunk.h index e75bc0e..d79fbbc 100644 --- a/C/headers/chunk.h +++ b/C/headers/chunk.h @@ -231,8 +231,12 @@ chunk* newAdjacentChunk(chunk* north_chunk, chunk* west_chunk, unsigned int disp chunk* copyChunk(chunk* p_chunk); - - +/** + * @brief Encodes a chunk struct in a binary format. + * + * @param chk (chunk*) : a pointer to the chunk struct. + * @return bytes : the byte string representing the encoded struct. + */ bytes bytesChunk(chunk* chk); tuple_obj_bytes nextChunk(bytes bytes); diff --git a/C/headers/gradientGrid.h b/C/headers/gradientGrid.h index c296e2c..edd3041 100644 --- a/C/headers/gradientGrid.h +++ b/C/headers/gradientGrid.h @@ -147,6 +147,12 @@ gradientGrid* readGradientGridFile(char path[]); +/** + * @brief Encodes a gradient grid struct in a binary format. + * + * @param gradGrid (gradientGrid*) : a pointer to the gradient grid struct. + * @return bytes : the byte string representing the encoded struct. + */ bytes bytesGradientGrid(gradientGrid* grid); tuple_obj_bytes nextGradientGrid(bytes bytes); diff --git a/C/headers/layer.h b/C/headers/layer.h index 0160183..fe6376e 100644 --- a/C/headers/layer.h +++ b/C/headers/layer.h @@ -135,8 +135,14 @@ layer* copyLayer(layer * p_layer); - -bytes bytesLayer(layer* grid, bool altitude); +/** + * @brief Encodes a layer struct in a binary format. + * + * @param layer (layer*) : a pointer to the layer struct. + * @param altitude (bool) : should altitude values be encoded. + * @return bytes : the byte string representing the encoded struct. + */ +bytes bytesLayer(layer* layer, bool altitude); tuple_obj_bytes nextLayer(bytes bytes, bool altitude); diff --git a/C/headers/map.h b/C/headers/map.h index 350d675..e6d1d43 100644 --- a/C/headers/map.h +++ b/C/headers/map.h @@ -163,7 +163,12 @@ map* copyMap(map* p_map) ; - +/** + * @brief Encodes a map struct in a binary format. + * + * @param map (map*) : a pointer to the map struct. + * @return bytes : the byte string representing the encoded struct. + */ bytes bytesMap(map* map); tuple_obj_bytes nextMap(bytes bytes); diff --git a/C/headers/mapGenerator.h b/C/headers/mapGenerator.h index ef831bb..1de8bbb 100644 --- a/C/headers/mapGenerator.h +++ b/C/headers/mapGenerator.h @@ -230,11 +230,22 @@ void printCompleteMap(completeMap* completeMap); - +/** + * @brief Encodes a color struct in a binary format. + * + * @param c (color) : a color struct. + * @return bytes : the byte string representing the encoded struct. + */ bytes bytesColor(color c); tuple_obj_bytes nextColor(bytes bytes); +/** + * @brief Encodes a compltet map struct in a binary format. + * + * @param cmap (completeMap*) : a pointer to the complete map struct. + * @return bytes : the byte string representing the encoded struct. + */ bytes bytesCompleteMap(completeMap* cmap); tuple_obj_bytes nextCompleteMap(bytes bytes); From 2c2a4807c033ddb8b1a203728740d54ba4e515c4 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 2 Aug 2024 00:34:03 +0200 Subject: [PATCH 73/84] C doc interpreter functions and structs --- C/headers/interpreter.h | 87 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 81 insertions(+), 6 deletions(-) diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index 13d6da5..b7f139d 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -12,18 +12,24 @@ // ------- Structure definition ------- // -typedef unsigned char byte; +typedef unsigned char byte; //type used as bytes typedef char* object; //an alias for pointers +/** + * @brief a simple implementation of byte strings + */ typedef struct bytes { - byte* bytes; - int size; - int start; + byte* bytes; // the byte array + int size; // to keep track of the size of the byte array + int start; // where to look for the current byte in the array } bytes; +/** + * @brief a placeholder to return both an object (a number or a struct) and a byte string (bytes) + */ typedef struct tuple_obj_bytes { - object object; - bytes bytes; + object object; // a pointer to the object + bytes bytes; // the byte string } tuple_obj_bytes; @@ -48,32 +54,101 @@ typedef struct tuple_obj_bytes { // ------- Functions ------- // +/** + * @brief 'Fast' int powers. + * + * @param nbr (int) : the nbr to be exponantiated + * @param exp (int) : the exponant + * @return int : the result of nbr^exp. + */ int intpow(int nbr, int exp); +/** + * @brief Deallocates the byte array of a bytes struct + * + * @param b (bytes) : the bytes struct + */ void freeBytes(bytes b); +/** + * @brief Auxiliary function to print bytes (update a string with the hexadecimal representation of a byte). + * + * @param c (unsigned char) : the byte to print + * @param res (char*) : the string to update + * @return char* : the updated string + */ char* hex(unsigned char c, char* res); +/** + * @brief Prints a bytes struct + * + * @param bytes (bytes) : the bytes to print + * @param start (char*) : a string to print beforehand + * @param end (char*) : a string to print after ("\n" for instance) + */ void printBytes(bytes bytes, char* start, char* end); +/** + * @brief Updates a byte string starting from a given index with the values of another byte string + * + * @param b (bytes) : the bytes to update + * @param bb (bytes) : the bytes to use for updating + * @param start (int) : the starting index in b + */ void concatBytes(bytes b, bytes bb, int start); +/** + * @brief Encodes an unsigned 8bits int. + * + * @param nbr (__uint8_t) : the unsigned int. + * @return bytes : the byte string representing the encoded number. + */ bytes bytesUint8(__uint8_t nbr); +/** + * @brief Encodes an int. + * + * @param nbr (int) : the int. + * @return bytes : the byte string representing the encoded number. + */ bytes bytesInt(int nbr); +/** + * @brief Encodes a double. + * + * @param nbr (double) : the double. + * @return bytes : the byte string representing the encoded number. + */ bytes bytesDouble(double nbr); +/** + * @brief Decodes an encoded unsigned 8bits int. + * + * @param bytes (bytes) : the encoded byte string. + * @return tuple_obj_bytes : the byte string with updated start index and a pointer to the number decoded. + */ tuple_obj_bytes nextUint8(bytes bytes); +/** + * @brief Decodes an encoded int. + * + * @param bytes (bytes) : the encoded byte string. + * @return tuple_obj_bytes : the byte string with updated start index and a pointer to the number decoded. + */ tuple_obj_bytes nextInt(bytes bytes); +/** + * @brief Decodes an encoded double. + * + * @param bytes (bytes) : the encoded byte string. + * @return tuple_obj_bytes : the byte string with updated start index and a pointer to the number decoded. + */ tuple_obj_bytes nextDouble(bytes bytes); From eb4e0d317a1faccd33fdd3053a6f75f3950160b6 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 2 Aug 2024 00:38:53 +0200 Subject: [PATCH 74/84] C doc decoding functions --- C/headers/chunk.h | 6 ++++++ C/headers/gradientGrid.h | 6 ++++++ C/headers/layer.h | 7 +++++++ C/headers/map.h | 6 ++++++ C/headers/mapGenerator.h | 6 ++++++ 5 files changed, 31 insertions(+) diff --git a/C/headers/chunk.h b/C/headers/chunk.h index d79fbbc..670df9c 100644 --- a/C/headers/chunk.h +++ b/C/headers/chunk.h @@ -239,6 +239,12 @@ chunk* copyChunk(chunk* p_chunk); */ bytes bytesChunk(chunk* chk); +/** + * @brief Decodes a chunk struct from a formatted byte string. + * + * @param bytes (bytes) : the formatted byte string. + * @return tuple_obj_bytes : the decoded chunk and the byte string (with the start index updated). + */ tuple_obj_bytes nextChunk(bytes bytes); diff --git a/C/headers/gradientGrid.h b/C/headers/gradientGrid.h index edd3041..530f084 100644 --- a/C/headers/gradientGrid.h +++ b/C/headers/gradientGrid.h @@ -155,6 +155,12 @@ gradientGrid* readGradientGridFile(char path[]); */ bytes bytesGradientGrid(gradientGrid* grid); +/** + * @brief Decodes a gradient grid struct from a formatted byte string. + * + * @param bytes (bytes) : the formatted byte string. + * @return tuple_obj_bytes : the decoded gradient grid and the byte string (with the start index updated). + */ tuple_obj_bytes nextGradientGrid(bytes bytes); diff --git a/C/headers/layer.h b/C/headers/layer.h index fe6376e..bfa0d4c 100644 --- a/C/headers/layer.h +++ b/C/headers/layer.h @@ -144,6 +144,13 @@ layer* copyLayer(layer * p_layer); */ bytes bytesLayer(layer* layer, bool altitude); +/** + * @brief Decodes a layer struct from a formatted byte string. + * + * @param bytes (bytes) : the formatted byte string. + * @param altitude (bool) : should altitude values be initialised and decoded (or regenerated) or not. + * @return tuple_obj_bytes : the decoded layer and the byte string (with the start index updated). + */ tuple_obj_bytes nextLayer(bytes bytes, bool altitude); diff --git a/C/headers/map.h b/C/headers/map.h index e6d1d43..14edef4 100644 --- a/C/headers/map.h +++ b/C/headers/map.h @@ -171,6 +171,12 @@ map* copyMap(map* p_map) ; */ bytes bytesMap(map* map); +/** + * @brief Decodes a map struct from a formatted byte string. + * + * @param bytes (bytes) : the formatted byte string. + * @return tuple_obj_bytes : the decoded map and the byte string (with the start index updated). + */ tuple_obj_bytes nextMap(bytes bytes); diff --git a/C/headers/mapGenerator.h b/C/headers/mapGenerator.h index 1de8bbb..2365d1f 100644 --- a/C/headers/mapGenerator.h +++ b/C/headers/mapGenerator.h @@ -248,6 +248,12 @@ tuple_obj_bytes nextColor(bytes bytes); */ bytes bytesCompleteMap(completeMap* cmap); +/** + * @brief Decodes a complete map struct from a formatted byte string. + * + * @param bytes (bytes) : the formatted byte string. + * @return tuple_obj_bytes : the decoded complete map and the byte string (with the start index updated). + */ tuple_obj_bytes nextCompleteMap(bytes bytes); From b416bdf2d15e70b850c9f93f432becf130f5931c Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Fri, 2 Aug 2024 00:46:28 +0200 Subject: [PATCH 75/84] C doc changed functions --- C/headers/chunk.h | 18 +++++------------- C/headers/layer.h | 1 + C/headers/map.h | 1 + C/src/chunk.c | 4 ++-- 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/C/headers/chunk.h b/C/headers/chunk.h index 670df9c..e29d9db 100644 --- a/C/headers/chunk.h +++ b/C/headers/chunk.h @@ -183,25 +183,17 @@ chunk* newChunkFromGradients(int width, int height, int number_of_layers, gradie chunk* newChunk(int number_of_layers, int gradGrids_width[number_of_layers], int gradGrids_height[number_of_layers], int size_factors[number_of_layers], double layers_factors[number_of_layers], unsigned int display_loading); -//TODO ? signature could be changed to avoid passing useless parameters -> `chunk_width` and `chunk_height` instead of `gradGrids_width`, `gradGrids_height` and `size_factors` /** * @brief Generates a new virtual chunk structure with the given parameters. It does not possess any altitude values and is used as a way to store * the data of boundary conditions with its `base_altitude` parameter. * - * @param number_of_layers (int) : the number of layers passed. - * @param gradGrids_width (int[number_of_layers]) : the array of gradientGrid width to compute the final width this virtual chunk should have. - * @param gradGrids_height (int[number_of_layers]) : the array of gradientGrid height to compute the final height this virtual chunk should have. - * @param size_factors (int[number_of_layers]) : the array of size factors to compute the final dimensions of this virtual chunk. - * @param layers_factors (double[number_of_layers]) : the array of layers factors to be stored in the virtual chunk. - * @return chunk* : the pointer to the newly generated virtual chunk structure. - * - * @warning The `size_factors` array should match the `gradGrids_width` and `gradGrids_height` arrays such that - * `(gradGrid_dimensions - 1) * size_factor = constant`. In case it would not be the case, the chunk structure will still - * be generated but its dimensions will be wrong : it will simply use the first value. + * @param chunk_width (int) : the width size of the virtuak chunk if it had altitude values. + * @param chunk_height (int) : the height size of the virtuak chunk if it had altitude values. + * @param regenerate (bool) : should the base altitude value be generated. * - * @note The arrays does not need to be dynamically allocated and their content will be copied in the structure. + * @return chunk* : the pointer to the newly generated virtual chunk structure. */ -chunk* newVirtualChunk(int chunk_width, int chunk_height, bool regenereate); +chunk* newVirtualChunk(int chunk_width, int chunk_height, bool regenerate); /** diff --git a/C/headers/layer.h b/C/headers/layer.h index bfa0d4c..45feb46 100644 --- a/C/headers/layer.h +++ b/C/headers/layer.h @@ -98,6 +98,7 @@ double* getLayerValue(layer* layer, int width_idx, int height_idx); * * @param gradient_grid (gradientGrid*) : the pointer to the gradientGrid structure to build the layer from. * @param size_factor (int) : the size_factor to rescale the layer's dimensions. + * @param altitude (bool) : should altitude values be initialised and generated. * @param display_loading (unsigned int) : the given value defines the behaviour. * * If `0` the loading bars won't be printed. * * If `> 0` the loading bars will be printed with a number of indent equal to `display_loading - 1`. diff --git a/C/headers/map.h b/C/headers/map.h index 14edef4..da5d3a9 100644 --- a/C/headers/map.h +++ b/C/headers/map.h @@ -118,6 +118,7 @@ map* addMeanAltitude(map* p_map, unsigned int display_loading); * @param map_height (int) : number of chunks in height. * @param chunks (chunk**) : array of size `map_width * map_height` of pointers to the chunk structures. * @param virtual_chunks (chunk**) : array of size `(map_height+2 + map_width+2)*2 - 4` of pointers to the virtual chunk structures. + * @param regenerate (bool) : should altitude values be initialised and regenerated (adds base altitude to its chunks' altitude values). * @param display_loading (unsigned int) : the given value defines the behaviour. * * If `0` the loading bars won't be printed. * * If `> 0` the loading bars will be printed with a number of indent equal to `display_loading - 1`. diff --git a/C/src/chunk.c b/C/src/chunk.c index d00801d..1543e8d 100644 --- a/C/src/chunk.c +++ b/C/src/chunk.c @@ -272,7 +272,7 @@ chunk* newChunk(int number_of_layers, int gradGrids_width[number_of_layers], int -chunk* newVirtualChunk(int chunk_width, int chunk_height, bool regenereate) +chunk* newVirtualChunk(int chunk_width, int chunk_height, bool regenerate) { chunk* new_chunk = calloc(1, sizeof(chunk)); @@ -290,7 +290,7 @@ chunk* newVirtualChunk(int chunk_width, int chunk_height, bool regenereate) new_chunk->layers = NULL; - if (regenereate) new_chunk->base_altitude=generateBaseAltitude(); + if (regenerate) new_chunk->base_altitude=generateBaseAltitude(); return new_chunk; } From 9ecd1501cd3b393dc5fa3566ea811cd2c1d0ec53 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 7 Aug 2024 20:28:26 +0200 Subject: [PATCH 76/84] C writes bytes in file --- C/src/interpreter.c | 28 ++++++++++++++++++++++++++++ C/src/mapGenerator.c | 2 +- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/C/src/interpreter.c b/C/src/interpreter.c index de4ef55..b27573c 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -9,6 +9,7 @@ #include #include +#include #include "map.h" #include "interpreter.h" @@ -198,4 +199,31 @@ tuple_obj_bytes nextDouble(bytes bytes) { res.bytes.start += FLOAT_BITS_NBR/8; return res; +} + + +void writeBytesFile(bytes bytes, char* path, char* name) { + struct stat st = {0}; + + // Generates a directory if it does not exist + if (stat(path, &st) == -1) + { + // 0700 is rwx permission for owner only + mkdir(path, 0700); + } + + // Generates the sea map file + char file_path[200] = ""; + snprintf(file_path, sizeof(file_path), "%s/%s", path, name); + + // Creates and opens the file (overrides already existing content) + FILE* f = NULL; + f = fopen(path, "w"); + + if (f != NULL) + { + // Writes bytes (unsigned char) in the file + fprintf(f, bytes.bytes); + fclose(f); + } } \ No newline at end of file diff --git a/C/src/mapGenerator.c b/C/src/mapGenerator.c index 0def5ed..eda90f7 100644 --- a/C/src/mapGenerator.c +++ b/C/src/mapGenerator.c @@ -729,7 +729,7 @@ void writeCompleteMapFiles(completeMap* complete_map, char folder_path[]) // Generates a directory if it does not exist if (stat(folder_path, &st) == -1) { - // Should check what 0700 permissions are exactly, but that's how it works to create a directory. + // 0700 is rwx permission for owner only. mkdir(folder_path, 0700); } From a635be3cbd8d4068d9bc381498871faf151edde2 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 7 Aug 2024 20:30:22 +0200 Subject: [PATCH 77/84] C write bytes inf file func header --- C/headers/interpreter.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index b7f139d..3f0a1c7 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -153,6 +153,17 @@ tuple_obj_bytes nextDouble(bytes bytes); +/** + * @brief Writes a bytes string in a specified file + * + * @param bytes (bytes) : the byte string. + * @param path (char*) : the folder path. + * @param name (char*) : the file name (should end with '.data'). + */ +void writeBytesFile(bytes bytes, char* path, char* name); + + + From dd56b5b72c0f15a6a68bffc568012aed41f87ac8 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 7 Aug 2024 20:43:35 +0200 Subject: [PATCH 78/84] C write file testing --- .gitignore | 2 +- C/src/interpreter.c | 6 +++--- C/src/test_interpreter.c | 5 +++++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 40b3a75..bad5b79 100644 --- a/.gitignore +++ b/.gitignore @@ -40,7 +40,7 @@ MANIFEST .vscode # Files saved -saves/ +saves/* # PyInstaller # Usually these files are written by a python script from a template diff --git a/C/src/interpreter.c b/C/src/interpreter.c index b27573c..3742d08 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -216,14 +216,14 @@ void writeBytesFile(bytes bytes, char* path, char* name) { char file_path[200] = ""; snprintf(file_path, sizeof(file_path), "%s/%s", path, name); - // Creates and opens the file (overrides already existing content) + // Creates and/or opens the binary file (overrides already existing content) FILE* f = NULL; - f = fopen(path, "w"); + f = fopen(file_path, "wb"); if (f != NULL) { // Writes bytes (unsigned char) in the file - fprintf(f, bytes.bytes); + fwrite(bytes.bytes, bytes.size, 1, f); fclose(f); } } \ No newline at end of file diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index e9311cf..f2af937 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -137,6 +137,11 @@ int main() { + printf("\n\n\tTesting file writing...\n"); + writeBytesFile(cmapb, "../saves","test.data"); + + + printf("\n\nDeallocating...\n"); free(od); free(oa); From fb5302f021227da93726d3c32957a4f8d36a4cf8 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 7 Aug 2024 20:52:08 +0200 Subject: [PATCH 79/84] C read bytes file --- C/headers/interpreter.h | 8 ++++++++ C/src/interpreter.c | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/C/headers/interpreter.h b/C/headers/interpreter.h index 3f0a1c7..7206c4b 100644 --- a/C/headers/interpreter.h +++ b/C/headers/interpreter.h @@ -162,6 +162,14 @@ tuple_obj_bytes nextDouble(bytes bytes); */ void writeBytesFile(bytes bytes, char* path, char* name); +/** + * @brief Read bytes from a specified file + * + * @param path (char*) : the file path. + * @return (bytes) : read bytes + */ +bytes readBytesFile(char* path); + diff --git a/C/src/interpreter.c b/C/src/interpreter.c index 3742d08..b363469 100644 --- a/C/src/interpreter.c +++ b/C/src/interpreter.c @@ -226,4 +226,29 @@ void writeBytesFile(bytes bytes, char* path, char* name) { fwrite(bytes.bytes, bytes.size, 1, f); fclose(f); } +} + +bytes readBytesFile(char* path) { + // Opens file + FILE* f = NULL; + f = fopen(path, "rb"); + bytes b; + + if (f != NULL) + { + // Get file size + fseek(f, 0, SEEK_END); // seek to end of file + long size = ftell(f); // get current file pointer + fseek(f, 0, SEEK_SET); // seek back to beginning of file + + // Read bytes (unsigned char) in the file + b.size = size; + b.start = 0; + b.bytes = malloc(size*sizeof(byte)); + fread(b.bytes, b.size, 1, f); + + fclose(f); + } + + return b; } \ No newline at end of file From 02b3faac0d568af95102c55338fd9bfc09a94837 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 7 Aug 2024 20:53:38 +0200 Subject: [PATCH 80/84] C test file reading --- C/src/test_interpreter.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index f2af937..92c30a2 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -137,8 +137,11 @@ int main() { - printf("\n\n\tTesting file writing...\n"); + printf("\n\n\tTesting file writing and reading...\n"); writeBytesFile(cmapb, "../saves","test.data"); + bytes cmapbr = readBytesFile("../saves/test.data"); + printBytes(cmapb,"","\n"); + printBytes(cmapbr,"","\n"); From 5c6af0ac429f5c17513bdff7eb03454d322f8b63 Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 7 Aug 2024 21:14:22 +0200 Subject: [PATCH 81/84] C main file saving --- C/src/main.c | 87 +++++++++++++++++++++++++++++++++++----- C/src/test_interpreter.c | 1 + 2 files changed, 79 insertions(+), 9 deletions(-) diff --git a/C/src/main.c b/C/src/main.c index 8775363..763db22 100644 --- a/C/src/main.c +++ b/C/src/main.c @@ -439,20 +439,89 @@ int main(int argc, char* argv[argc]) printf("The whole map generation took a total of %lf second(s) in CPU time\n", total_time); - // TODO : Ask for a path to save the map + // TODO : Ask for a path to save the map// Whether to display loading bars or not + int save_map = -1; // boolean + + // Reset tracking parameters + temp = -1; + nb_associated = 0; + snprintf(line, sizeof(line), ""); + + while ( temp != 0 && temp != 1 ) + { + printf("Do you want to save the generated map ? (1 for Yes, 0 for No) -> "); + + fgets(line, INPUT_MAX_SIZE, stdin); + + nb_associated = sscanf(line, " %d", &temp); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as an integer value. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + else if (temp != 0 && temp != 1) + { + printf("%s/!\\ Value Error : please enter 0 to hide loading bars or 1 to show them. /!\\%s\n", RED_COLOR, DEFAULT_COLOR); + } + } + + save_map = temp; - //? Comment this if you don't want to save it in a file. - //! WARNING : ../saves/ the folder must exist for it to work properly - printf("File creation...\n"); - start_time = clock(); - char folder_path[200] = "../saves/completeMap_test/"; + if (save_map==1) { + printf("Save file creation : \n"); + start_time = clock(); + + // Get folder name + temp = -1; + nb_associated = 0; + snprintf(line, sizeof(line), ""); + + char folder_path[100] = "../saves"; + + printf("Folder name (defaults to %s) -> ", folder_path); + fgets(line, INPUT_MAX_SIZE, stdin); + nb_associated = sscanf(line, " %s", &folder_path); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as a path name. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + + // Get file name + temp = -1; + nb_associated = 0; + snprintf(line, sizeof(line), ""); + + char name[100] = "save.data"; - writeCompleteMapFiles(new_complete_map, folder_path); + printf("File name (defaults to %s) -> ", name); + fgets(line, INPUT_MAX_SIZE, stdin); - total_time = (double) (clock() - start_time) / CLOCKS_PER_SEC; - printf("The map saving took a total of %lf second(s) in CPU time\n", total_time); + nb_associated = sscanf(line, " %s", &name); + if (nb_associated == 0) + { + printf("%s/!\\ Input Error : could not convert line '%s' as a file name. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); + } + + // Get bytes + bytes b; + bytes cb = bytesCompleteMap(new_complete_map); + b.size = cb.size +1; + b.start = 0; + b.bytes = malloc(b.size * sizeof(byte)); + b.bytes[0] = BYTES_VERSION; + concatBytes(b,cb,1); + + // Write binary file + writeBytesFile(b,folder_path,name); + + // Deallocating + freeBytes(b); + freeBytes(cb); + + total_time = (double) (clock() - start_time) / CLOCKS_PER_SEC; + printf("The map saving took a total of %lf second(s) in CPU time\n", total_time); + } diff --git a/C/src/test_interpreter.c b/C/src/test_interpreter.c index 92c30a2..0b88f18 100644 --- a/C/src/test_interpreter.c +++ b/C/src/test_interpreter.c @@ -185,6 +185,7 @@ int main() { freeCompleteMap(cmap); freeBytes(cmapb); freeCompleteMap(cmapd); + freeBytes(cmapbr); return 0; } \ No newline at end of file From abd7f7be84b09b77b43bdaf985119a17c0ac1dcc Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 7 Aug 2024 21:19:53 +0200 Subject: [PATCH 82/84] C main file saving works --- C/Makefile | 2 +- C/src/main.c | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/C/Makefile b/C/Makefile index 2ec1a10..9a46b8e 100644 --- a/C/Makefile +++ b/C/Makefile @@ -49,7 +49,7 @@ $(COMP)%.o : $(SRC)%.c # Main -------------------------------------- -main: $(COMP)main.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o +main: $(COMP)main.o $(COMP)mapGenerator.o $(COMP)map.o $(COMP)chunk.o $(COMP)layer.o $(COMP)gradientGrid.o $(COMP)loadingBar.o $(COMP)interpreter.o $(CC) $^ -o $(BIN)$@ $(LFLAGS) # Tests ------------------------------------- diff --git a/C/src/main.c b/C/src/main.c index 763db22..7cf3f63 100644 --- a/C/src/main.c +++ b/C/src/main.c @@ -9,9 +9,11 @@ #include #include +#include #include "loadingBar.h" #include "mapGenerator.h" +#include "interpreter.h" #define INPUT_MAX_SIZE 100 @@ -481,7 +483,7 @@ int main(int argc, char* argv[argc]) printf("Folder name (defaults to %s) -> ", folder_path); fgets(line, INPUT_MAX_SIZE, stdin); - nb_associated = sscanf(line, " %s", &folder_path); + nb_associated = sscanf(line, " %s", folder_path); if (nb_associated == 0) { printf("%s/!\\ Input Error : could not convert line '%s' as a path name. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); @@ -497,7 +499,7 @@ int main(int argc, char* argv[argc]) printf("File name (defaults to %s) -> ", name); fgets(line, INPUT_MAX_SIZE, stdin); - nb_associated = sscanf(line, " %s", &name); + nb_associated = sscanf(line, " %s", name); if (nb_associated == 0) { printf("%s/!\\ Input Error : could not convert line '%s' as a file name. /!\\%s\n", RED_COLOR, line, DEFAULT_COLOR); From b1fb93f8bf1ec97b284441e4b245a9e0802abc5a Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 7 Aug 2024 21:21:23 +0200 Subject: [PATCH 83/84] Comments --- C/src/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C/src/main.c b/C/src/main.c index 7cf3f63..a3ac60f 100644 --- a/C/src/main.c +++ b/C/src/main.c @@ -441,7 +441,7 @@ int main(int argc, char* argv[argc]) printf("The whole map generation took a total of %lf second(s) in CPU time\n", total_time); - // TODO : Ask for a path to save the map// Whether to display loading bars or not + // Whether to save the file or not int save_map = -1; // boolean From b67ed35b133d1cbe1e7bdd07d7e2ee3fa59fbb9a Mon Sep 17 00:00:00 2001 From: BlueNZ Date: Wed, 7 Aug 2024 21:24:43 +0200 Subject: [PATCH 84/84] File doc --- C/src/main.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C/src/main.c b/C/src/main.c index a3ac60f..6ede2e2 100644 --- a/C/src/main.c +++ b/C/src/main.c @@ -1,9 +1,9 @@ /** * @file main.c - * @author Zyno - * @brief main code to generate a new complete map - * @version 0.1 - * @date 2024-07-04 + * @author Zyno and BlueNZ + * @brief main code to generate and save a new complete map + * @version 0.2 + * @date 2024-08-07 * */