#include <math.h>
#include "main.h"
#include "tilemap.h"
#include "sprite.h"
#include "sprhelp.h"
#include "s_player.h"
#include "collide.h"
#include "player.h"
#include "game.h"
#include "s_camera.h"



void camera_set_target(TILEMAP *map, CAMERA *camera, SPRITE *sprite) {
 camera->xt = sprite->x - 2*XVECT(sprite->th);
 camera->yt = sprite->y - 2*YVECT(sprite->th);
 camera->zt = sprite->z + 4.5;
 camera->tht = sprite->th;

 camera->xt = MID(0.5, camera->xt, map->w - 0.5);
 camera->yt = MID(0.5, camera->yt, map->h - 0.5);
 camera->zt = MAX(6.0, camera->zt);
}



/* WARNING: This leaves the camera coordinates uninitialised. */

SPRITE *add_camera_sprite(TILEMAP *map, SPRITE *sprite, OUTPUTDEV *dev) {

 (void)map;

 sprite = add_sprite(sprite);

 sprite->life = 1;

 sprite->type = SPRITE_TYPE_CAMERA;

 sprite->r = 0.5;

 sprite->data = malloc(sizeof(CAMERA));
 if (!sprite->data) exit(37);
 dev->player->camspr = sprite;

 return sprite;
}



/* update_camera()
*  Moves the camera in a proper position.
*/
void update_camera(TILEMAP *map, SPRITE *sprite) {

 CAMERA *camera = sprite->data;

 float dth;
 sprite->x = 0.9 * sprite->x + 0.1 * camera->xt;
 sprite->y = 0.9 * sprite->y + 0.1 * camera->yt;
 sprite->z = 0.9 * sprite->z + 0.1 * camera->zt;

 dth = camera->tht - sprite->th;

 while (dth >= M_PI) dth -= 2*M_PI;
 while (dth < -M_PI) dth += 2*M_PI;

 sprite->th += 0.1 * dth;

 while (sprite->th >= 2*M_PI) sprite->th -= 2*M_PI;
 while (sprite->th < 0) sprite->th += 2*M_PI;

 sprite_tilemap_collision(map, sprite, NULL);
}


