42_cub3d/src/input.c
2024-11-07 18:39:42 +01:00

76 lines
2.5 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* input.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mc <mc@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/17 14:43:36 by mcolonna #+# #+# */
/* Updated: 2024/11/07 18:37:52 by mc ### ########.fr */
/* */
/* ************************************************************************** */
#include "input.h"
#include "global.h"
#include "const.h"
t_input_actions g_input_actions;
static int set_quit(void *_)
{
(void)_;
g_input_actions.quit = true;
return (0);
}
static void set_action(int keycode, bool value)
{
if (keycode == XK_Up || keycode == XK_z || keycode == XK_w)
g_input_actions.up = value;
if (keycode == XK_Down || keycode == XK_s)
g_input_actions.down = value;
if (keycode == XK_Right || keycode == XK_d)
g_input_actions.right = value;
if (keycode == XK_Left || keycode == XK_q || keycode == XK_a)
g_input_actions.left = value;
if (keycode == XK_Escape)
set_quit(NULL);
}
int hook_keypress(int keycode)
{
set_action(keycode, true);
return (0);
}
int hook_keyrelease(int keycode)
{
set_action(keycode, false);
return (0);
}
static int hook_mousemove(int x, int y)
{
static const t_point_int window_middle = {
SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2};
static bool first_call = true;
const int dx = x - window_middle.x;
if (!first_call && dx)
g_input_actions.rotate += dx;
first_call = false;
if (x != window_middle.x || y != window_middle.y)
mlx_mouse_move(g_mlx, g_win, window_middle.x, window_middle.y);
return (0);
}
// TODO hide cursor without leak?
void input_init(void *mlx_ptr, void *win_ptr)
{
(void)mlx_ptr;
ft_memset(&g_input_actions, 0, sizeof(g_input_actions));
mlx_hook(win_ptr, DestroyNotify, StructureNotifyMask, set_quit, NULL);
mlx_hook(win_ptr, KeyPress, KeyPressMask, hook_keypress, NULL);
mlx_hook(win_ptr, KeyRelease, KeyReleaseMask, hook_keyrelease, NULL);
mlx_hook(win_ptr, MotionNotify, PointerMotionMask, hook_mousemove, NULL);
}