#define __RAWKS_EXPL__
#define DBG 0

#include "defines.h"
#include "gl.h"
#include "struct.h"
#include "protos.h"
#include "globals.h"

#define EXPL_TIME_TO_LIVE	40

void explode(int numsparks,trajectory *obj)
{
  int i;
  for(i=0;i<numsparks;i++) new_particle(obj);
}

void new_particle(trajectory *traj)
{
  int temp,direction;
  float speed;

  if((temp = INC_STUFF(Nextpartic_i))==Firstpartic_i) return;
  else {
    if(S[Nextpartic_i].ttl) return; /* System out of trajectories */

    /* Copy player trajectory */
    memcpy(&S[Nextpartic_i],traj,sizeof(trajectory));

    if(!traj->ttl) S[Nextpartic_i].ttl =
      (float)(EXPL_TIME_TO_LIVE * fast_rand() +(EXPL_TIME_TO_LIVE>>1));
    S[Nextpartic_i].player = 0;

    /* add random trajectory */
    direction = fast_rand()*255;
    speed     = fast_rand()*0.0035;
    S[Nextpartic_i].inertiax+=-Sintable[direction]*speed;
    S[Nextpartic_i].inertiay+= Costable[direction]*speed;

    Nextpartic_i = temp;
  }
}

void update_partics(void)
{
  int i;

#if DBG
  DEBUG("update_partics()");
#endif
  if(Firstpartic_i==Nextpartic_i) { /* Cache friendly */
    Firstpartic_i = Nextpartic_i = 0;
#if DBG
  DEBUG("update_partics complete");
#endif
    return;
  }
  for(i=Firstpartic_i;i!=Nextpartic_i;i=INC_STUFF(i)) {
    if(!S[i].ttl) /* THis is necess 'cause diff speeds, dude */
    {
      if(i==Firstpartic_i) Firstpartic_i = INC_STUFF(Firstpartic_i);
      continue;
    }

    bgnline();
    C_BLACK;
    v2f(&S[i].V[Frm].x);
    v2f(&S[i].V[2+Frm].x);
    endline();

    update_trajectory(&S[i]);


    if(S[i].ttl > D_time) {
      bgnline();
      v2f(&S[i].V[Frm].x); /* Assumes color is already black (no cpack) */
      cpack(S[i].color);   /* interpolates from black to this color */
      v2f(&S[i].V[2+Frm].x);
      endline();
      S[i].ttl -= D_time;
    }
    else if(S[i].ttl == -1.0) {
      S[i].ttl = 0.0;
      if(i == Firstpartic_i) Firstpartic_i = INC_STUFF(Firstpartic_i);
    }
    else S[i].ttl = -1.0; /* Flag to erase next frame also */

  }
#if DBG
  DEBUG("update_partics complete");
#endif
}
