init.c
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* init.c :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: omougel <omougel@student.42lyon.fr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2024/07/26 14:59:03 by omougel #+# #+# */ 9 /* Updated: 2024/11/12 17:56:00 by omougel ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include "cub3D.h" 14 #include "ft_dprintf.h" 15 #include "ft_ptr.h" 16 #include "mlx.h" 17 #include "vec2f.h" 18 #include <stdio.h> 19 #include <stdlib.h> 20 #include <math.h> 21 22 static int cube_init_mlx(t_cube *cube); 23 static float sign_of(float x); 24 25 int init_cube(t_cube *cube, const char *file_name) 26 { 27 float const fov = (float)SCREEN_WIDTH / (float)SCREEN_HEIGHT; 28 29 cube->mlx.ptr = mlx_init(); 30 if (cube->mlx.ptr == NULL) 31 return (ft_dprintf(2, "Error\nMlx failed\n"), 0); 32 if (!cube_parse_file(cube, file_name) || !cube_init_mlx(cube)) 33 { 34 destroy_cube(cube); 35 return (0); 36 } 37 cube->player.dir.x = cosf(cube->player.axis); 38 cube->player.dir.y = -sinf(cube->player.axis); 39 if (roundf(cube->player.dir.x) == 0) 40 cube->player.camera.x = fov * sign_of(cube->player.dir.y); 41 else if (roundf(cube->player.dir.y) == 0) 42 cube->player.camera.y = -fov * sign_of(cube->player.dir.x); 43 cube->player.use_pointer = false; 44 cube->player.mouse = vec2f(0, 0); 45 return (1); 46 } 47 48 static int cube_init_mlx(t_cube *cube) 49 { 50 cube->mlx.win = mlx_new_window(cube->mlx.ptr, \ 51 SCREEN_WIDTH, SCREEN_HEIGHT, NAME); 52 if (cube->mlx.win == NULL) 53 return (ft_dprintf(2, "Error\nMlx failed\n"), 0); 54 cube->mlx.img.ptr = mlx_new_image(cube->mlx.ptr, \ 55 SCREEN_WIDTH, SCREEN_HEIGHT); 56 if (cube->mlx.img.ptr == NULL) 57 return (ft_dprintf(2, "Error\nMlx failed\n"), 0); 58 cube->mlx.img.width = SCREEN_WIDTH; 59 cube->mlx.img.height = SCREEN_HEIGHT; 60 cube->mlx.img.pixels = mlx_get_data_addr(cube->mlx.img.ptr, \ 61 &cube->mlx.img.bpp, \ 62 &cube->mlx.img.size_line, \ 63 &cube->mlx.img.endian); 64 return (1); 65 } 66 67 void destroy_cube(t_cube *cube) 68 { 69 if (!cube->mlx.ptr) 70 return ; 71 if (cube->map.cells) 72 ft_free2((void **)cube->map.cells, free); 73 if (cube->no_texture.ptr) 74 mlx_destroy_image(cube->mlx.ptr, cube->no_texture.ptr); 75 if (cube->ea_texture.ptr) 76 mlx_destroy_image(cube->mlx.ptr, cube->ea_texture.ptr); 77 if (cube->so_texture.ptr) 78 mlx_destroy_image(cube->mlx.ptr, cube->so_texture.ptr); 79 if (cube->we_texture.ptr) 80 mlx_destroy_image(cube->mlx.ptr, cube->we_texture.ptr); 81 if (cube->mlx.img.ptr) 82 mlx_destroy_image(cube->mlx.ptr, cube->mlx.img.ptr); 83 if (cube->mlx.win) 84 mlx_destroy_window(cube->mlx.ptr, cube->mlx.win); 85 mlx_destroy_display(cube->mlx.ptr); 86 free(cube->mlx.ptr); 87 } 88 89 static float sign_of(float x) 90 { 91 return ((x >= 0.f) - (x < 0.f)); 92 }