
#include "ball.h"

char	ball_collide (struct s_ball* ball, float x_old, float y_old, float x_new, float y_new, float w_min, float w_max, float h_min, float h_max)
{
	return collide (ball->coord.px, ball->coord.py, ball->mobile.x, ball->mobile.y, -BALL_SIZE_RADIUS, BALL_SIZE_RADIUS, -BALL_SIZE_RADIUS, BALL_SIZE_RADIUS, x_old, y_old, x_new, y_new, w_min, w_max, h_min, h_max);
}

void	ball_define (struct s_ball* ball, float x, float y, float weight, GLuint texture, GLUquadricObj* quadric)
{
	coord_set_pos (&ball->coord, x, y, 0);
	coord_set_rot (&ball->coord, 0, 0, 0);

	mobile_define (&ball->mobile, x, y, BALL_ANGLE_INITIAL + BALL_ANGLE_RANDOM * (rand () % 2000 * 0.001f - 1.0f), BALL_SPEED_INITIAL);
	ball_type (ball, weight, texture);

	ball->effect = 0;
	ball->quadric = quadric;
	ball->state = 0;
}

void	ball_draw (struct s_ball* ball)
{
	coord_item (&ball->coord);
		glColor3f (1, 1, 1);
		glEnable (GL_TEXTURE_2D);
		glBindTexture (GL_TEXTURE_2D, ball->texture);
		gluSphere (ball->quadric, BALL_SIZE_RADIUS, BALL_QUADRIC_SLICE, BALL_QUADRIC_SLICE);
		glDisable (GL_TEXTURE_2D);
	coord_stop ();
}

void	ball_loop (struct s_ball* ball, struct s_particle* particle)
{
	mobile_compose (&ball->mobile, BALL_ANGLE_GRAVITY, ball->weight * gl_vertex.speed);
	mobile_move (&ball->mobile, gl_vertex.speed);

	if (ball->effect <= gl_vertex.time)
	{
		if (ball->mobile.speed > BALL_SPEED_TRAIL)
			particle_create (particle, &ball->coord, particle_color_red, particle_define_ball_trail, ball->mobile.speed * BALL_FACTOR_TRAIL);

		if (ball->state & BALL_STATE_ONESHOT)
			particle_create (particle, &ball->coord, particle_color_orange, particle_define_ball_spark, 0);

		if (ball->state & BALL_STATE_TRAVERSE)
			particle_create (particle, &ball->coord, particle_color_cyan, particle_define_ball_spark, 0);

		ball->effect = gl_vertex.time + BALL_DELAY_TRAIL;
	}
}

void	ball_move (struct s_ball* ball)
{
	ball->coord.px = ball->mobile.x;
	ball->coord.py = ball->mobile.y;
	ball->coord.rx -= mobile_speed_y (&ball->mobile) * gl_vertex.speed * BALL_SIZE_RADIUS * BALL_FACTOR_ROLL;
	ball->coord.ry += mobile_speed_x (&ball->mobile) * gl_vertex.speed * BALL_SIZE_RADIUS * BALL_FACTOR_ROLL;
}

void	ball_type (struct s_ball* ball, float weight, GLuint texture)
{
	ball->texture = texture;
	ball->weight = weight;
}
