#include <math.h>
#include "main.h"
#include "sprite.h"
#include "tilemap.h"
#include "collide.h"
#include "sprhelp.h"
#include "s_exps.h"
#include "s_expp.h"
#include "options.h"
#include "sound2.h"
#include "log.h"


/* create_explosion(): spawns an explosion source which inherits the position
   and velocity of the sprite causing the explosion. It uses spawn_sprite()
   in sprite.h. 'size' is the size of the explosion.

   ELABORATE
*/
void create_explosion(SPRITE *sprite, float size) {

 SPRITE *newsprite = spawn_sprite(sprite);
 EXPSOURCE *exps;

 if (!newsprite)
	 return;

 size *= 1 + explosion_size;
 newsprite->life = (int)ceil(size * .8);

 newsprite->type = SPRITE_TYPE_EXPS;

 newsprite->x = sprite->x;
 newsprite->y = sprite->y;
 newsprite->z = sprite->z;

 newsprite->xv = sprite->xv;
 newsprite->yv = sprite->yv;
 newsprite->zv = sprite->zv;

 newsprite->r = 0.4;

 exps = newsprite->data = malloc(sizeof(EXPSOURCE));

 if (!exps) exit(37);

 exps->size = size;
 exps->damage_size = 50 * (1 + explosion_size);
 exps->part = 0;

 play_sound(Sample.Explosion[random()%2], newsprite->x, newsprite->y, newsprite->z, 255, 939 + (random() & 127), FALSE);
}


/* update_exps(): this is the explosion source's sprite_update_proc entry
   (see sprite.h). Each frame it should do the following:

   - Add the velocity to the position, and severely damp the velocity.

   - Use sprite_tilemap_collision() in collide.h. For the callback, use
     stc_stop() in sprhelp.h; the explosion source will stop if it hits a
     wall.

   - Create some explosion particles (see s_expp.h). ELABORATE. The number of
     particles created should be proportional to the 'life' field of the
     source.

   - Decrement the 'life' field.
*/
void update_exps(TILEMAP *map, SPRITE *sprite) {

 EXPSOURCE *exps = sprite->data;

 sprite->xv *= 0.95;
 sprite->yv *= 0.95;
 sprite->zv *= 0.95;

 extrapolate_sprite_no_th(sprite);

 sprite_tilemap_collision(map, sprite, stc_stop);

 exps->part += sprite->life;

 while (exps->part >= 100) {
  exps->part -= 100;
  spawn_expp(sprite, exps->size);
 }

 sprite->life--;
}
