/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   shaders.c                                          :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/05/08 18:27:59 by qmennen       #+#    #+#                 */
/*   Updated: 2025/05/23 15:24:19 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "cub3d.h"
#include "glad.h"
#include "MLX42_Int.h"

// extern char	*vert_shader;
// extern char	*frag_shader;

void	set_uniforms(t_game *game)
{
	mlx_ctx_t	*ctx;

	ctx = (mlx_ctx_t *)game->screen->mlx->context;
	glUniform1f(glGetUniformLocation(ctx->shaderprogram, "u_time"),
		glfwGetTime());
	glUniform1f(glGetUniformLocation(ctx->shaderprogram, "u_battery"),
		game->player->battery);
	glUniform2f(glGetUniformLocation(ctx->shaderprogram, "u_resolution"),
		game->screen->width, game->screen->height);
}

const char	*read_shader(int type)
{
	char	*shader;
	char	*target;
	int		fd;

	if (type == 1)
		target = "./assets/shaders/vert.glsl";
	else
		target = "./assets/shaders/frag.glsl";
	fd = open(target, O_RDONLY);
	if (fd < 0)
	{
		perror("Error opening shader file");
		return (NULL);
	}
	shader = malloc(4096);
	if (!shader)
	{
		perror("Error allocating memory for shader");
		close(fd);
		return (NULL);
	}
	read(fd, shader, 4096);
	close(fd);
	return (shader);
}

int	shader_init(t_game **game)
{
	vert_shader = read_shader(1);
	if (!vert_shader)
		return (FAILURE);
	frag_shader = read_shader(2);
	if (!frag_shader)
		return (FAILURE);
	return (SUCCESS);
}
