parsing_textures.c
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* parsing_textures.c :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: ll-hotel <ll-hotel@student.42lyon.fr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2024/07/26 13:35:34 by ll-hotel #+# #+# */ 9 /* Updated: 2024/10/20 17:25:05 by ll-hotel ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include "cub3D.h" 14 #include "ft_basics.h" 15 #include "ft_dprintf.h" 16 #include "mlx.h" 17 #include "parsing.h" 18 #include <fcntl.h> 19 #include <stdlib.h> 20 #include <unistd.h> 21 22 static char *get_texture_filename(t_line const *line); 23 static int store_texture(t_cube *cube, char const *key, char *filename); 24 25 int parsing_textures(t_cube *cube, t_line *lines) 26 { 27 char const *const keys[] = {"NO", "SO", "EA", "WE", NULL}; 28 char const *key; 29 t_line *line; 30 char *filename; 31 int key_i; 32 33 key_i = -1; 34 while (keys[++key_i]) 35 { 36 key = keys[key_i]; 37 line = find_line_by_key(lines, key); 38 if (line == NULL) 39 return (ft_dprintf(2, "Error\nMissing key '%s'\n", key), 0); 40 else if (find_line_by_key(line + 1, key) != NULL) 41 return (ft_dprintf(2, "Error\nDuplicate key '%s'\n", key), 0); 42 filename = get_texture_filename(line); 43 if (!filename) 44 return (0); 45 ft_strtrim_inplace(filename); 46 if (!store_texture(cube, key, filename)) 47 return (0); 48 } 49 return (1); 50 } 51 52 static char *get_texture_filename(t_line const *line) 53 { 54 if (line->value == NULL) 55 ft_dprintf(2, "Error\nMissing value for key '%s'\n", line->key); 56 else if (ft_strchr(line->value, ' ') != NULL) 57 ft_dprintf(2, "Error\nBad value '%s' for key '%s'\n", line->value, \ 58 line->key); 59 else if (ft_str_endswith(line->value, ".xpm") == 1) 60 return (line->value); 61 else 62 ft_dprintf(2, "Error\nFile %s is not a xpm file\n", line->value); 63 return (NULL); 64 } 65 66 static int store_texture(t_cube *cube, char const *key, char *filename) 67 { 68 t_img *texture; 69 70 if (ft_strcmp(key, "NO") == 0) 71 texture = &cube->no_texture; 72 else if (ft_strcmp(key, "SO") == 0) 73 texture = &cube->so_texture; 74 else if (ft_strcmp(key, "EA") == 0) 75 texture = &cube->ea_texture; 76 else if (ft_strcmp(key, "WE") == 0) 77 texture = &cube->we_texture; 78 else 79 return (0); 80 texture->ptr = mlx_xpm_file_to_image(cube->mlx.ptr, filename, \ 81 &texture->width, &texture->height); 82 if (texture->ptr == NULL) 83 { 84 ft_dprintf(2, "Error\nMlx failed to parse file '%s'\n", filename); 85 return (0); 86 } 87 texture->pixels = mlx_get_data_addr(texture->ptr, &texture->bpp, \ 88 &texture->size_line, &texture->endian); 89 return (1); 90 }