/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   draw.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pblagoje <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/05/04 13:55:29 by pblagoje          #+#    #+#             */
/*   Updated: 2022/05/04 13:55:31 by pblagoje         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "cube3d.h"

static int	pxl_out_limits(t_img *img, int x, int y)
{
	int	xmax;
	int	ymax;

	xmax = img->szl / (img->bpp / 8);
	ymax = img->height;
	if (x < 0 || y < 0 || x > xmax || y > ymax)
		return (1);
	return (0);
}

void	draw_pixel(t_img *img, int x, int y, int color)
{
	unsigned int	position;

	if (pxl_out_limits(img, x, y))
		return ;
	position = y * img->szl + x * (img->bpp / 8);
	*(unsigned int *)(img->data + position) = color;
}

void	draw_line(t_img *img, t_vec *vec, int color)
{
	t_coord	dist;
	int		i;
	int		j;

	dist.x = (*vec).end.x - (*vec).start.x;
	dist.y = (*vec).end.y - (*vec).start.y;
	i = 0;
	j = 0;
	while (ft_abs(i) <= ft_abs(dist.x) && ft_abs(j) <= ft_abs(dist.y))
	{
		draw_pixel(img, (*vec).start.x + i, (*vec).start.y + j, color);
		if (!ft_abs(dist.x) || ft_abs(j) < ft_abs(i * dist.y / dist.x))
			j += ft_sign(dist.y);
		else
			i += ft_sign(dist.x);
	}
}

void	draw(t_game *game)
{
	raycast(game, &(game->rcast));
	mlx_put_image_to_window(game->mlx_ptr, game->win.ptr, game->img.ptr, 0, 0);
}
