/*
** Falling Tower KAI
**	Copyright (c) 2000	ROYALPANDA	All rights reserved
**
**	May 25, 2000 Ver 1.0
*/

#include<stdio.h>
#include<X11/Xlib.h>

#include"xjump.h"
#include"xjump_xlib.h"
#include"key.h"

void HERO_delete( hero_t *hp )
{
	XClearArea(Disp,Scr_d,hp->erase_x,hp->erase_y,32,64,False);
}


void HERO_draw( hero_t *hp )
{
	int pic;
	int sx,sy;

	pic = hp->pic * 2 + hp->dir;
	sx = ( pic & 3 ) * 32;
	sy = ( pic >> 2 ) * 64;

	XSetClipOrigin(Disp,Gc_mask,hp->x-sx,hp->y-sy);
	XCopyArea(Disp,Char_p,Scr_d,Gc_mask,sx,sy,32,64,hp->x,hp->y);
}


int HERO_move( hero_t *hp, int scroll, int key )
{
	int acc,st,floor;
	int fv,mu,rv;
	floor_t *fp;

	hp->erase_x = hp->x;
	hp->erase_y = hp->y;

	hp->x += hp->vx/2;
	hp->y += hp->vy;

	if( scroll )
		hp->y += 16;

	if( hp->x < 16 ){
		hp->x = 16;
		hp->vx = -hp->vx/2;
	}else if( hp->x > WIDTH*16-48 ){
		hp->x = WIDTH*16-48;
		hp->vx = -hp->vx/2;
	}

	if( hp->vy >= 0 && (fp = FLOOR_check(hp->x,hp->y)) ){
		floor = fp->floor;
		st = 1;
		hp->pic &= 1;
		if( ++hp->g_count == 10 ){
			hp->g_count = 0;
			hp->pic ^= 1;
		}
		hp->y = ((hp->y + 64 ) & ~15) - 64;
		hp->vy = 0;

		fv = (fp->move_vector + fp->force_vector)*2;
		mu = fp->mu;
	}else{
		floor = 0;
		st = 0;
		fv = 0;
		mu = 0;
	}

	rv = hp->vx - fv;

	if( mu ){
		if( (key & (KEY_LEFT|KEY_RIGHT)) == KEY_LEFT ){
			rv -= (32+7 + rv) / 8;
			hp->dir = 0;
		}else if( (key & (KEY_RIGHT|KEY_LEFT)) == KEY_RIGHT ){
			rv += (32+7 - rv) / 8;
			hp->dir = 1;
		}else{
			if( abs(rv) < 4 )
				rv = 0;
			else
				rv += (rv > 0) ? -4 : 4;
		}
	}else{
		if( ((key & (KEY_LEFT|KEY_RIGHT)) == KEY_LEFT) && rv > -32 ){
			rv -= rv < 0 ? (32+15 + rv) / 16 : 2;
			hp->dir = 0;
		}else if( ((key & (KEY_RIGHT|KEY_LEFT)) == KEY_RIGHT)
		 						&& rv < 32 ){
			rv += rv > 0 ? (32+15 - rv) / 16 : 2;
			hp->dir = 1;
		}
	}
	hp->vx = rv + fv;

	if( !st ){
		if( hp->jump ){
			hp->vy = -hp->jump/2-12;
			if( key & (KEY_TRIG1|KEY_UP) )
				hp->jump--;
			else
				hp->jump = 0;
		}else{
			hp->vy+=2;
			if( hp->vy > 0 )
				hp->pic = 3;

			if( hp->vy > 16 )
				hp->vy = 16;
		}
	}else if( key & (KEY_TRIG1|KEY_UP) ){
		hp->jump = abs(rv)/4+7;
		hp->vy = -hp->jump/2-12;
		hp->pic = 2;
	}

	return floor;
}


void HERO_init( hero_t *hp )
{
	hp->x = WIDTH * 8 - 16;
	hp->y = (HEIGHT - 4)*16-64;
	hp->vx = hp->vy = 0;
	hp->pic = 0;
	hp->dir = 0;
	hp->g_count = 0;

	HERO_draw(hp);
}
