/*
    PARTicle PART
    - Marq
*/

#include <stdlib.h>
#include "putpix.h"
#include "partikle.h"

static PARTICLE part[PARTS];

// Show some charged particles
void bang(buftype *buf,unsigned char *bg,int howmany,int reset)
{
    static int first=1;
    int n,m,tmp;
    PARTICLE *p=part;

// Fade the background a bit
#ifdef HICOLOR
    unsigned short *b16=(unsigned short *)bg,
                   *c16=(unsigned short *)buf;
#else
    unsigned *ubg=(unsigned *)bg,*bff=buf;
    unsigned char *cbuf,*bakkis;
    int j;
#endif

#ifdef HICOLOR // Fade image to bg
    if(reset!=-1)
    {
        b16+=60;
        c16+=60;
        for(m=0;m<YRES;m++)
        {
            for(n=60;n<XRES;n++,b16++,c16++)
            {
                if(*c16!=*b16) // Argh.
                {
                    if((*c16 & 0xf800) < (*b16 & 0xf800))
                        (*c16)+=0x800;
                    if((*c16 & 0x7c0) < (*b16 & 0x7c0))
                        (*c16)+=0x40;
                    if((*c16 & 0x1f) < (*b16 & 0x1f))
                        (*c16)++;
                }
            }
            b16+=60;
            c16+=60;
        }
    }
#else
    if(reset!=-1)
    {
        ubg+=60;
        bff+=60;
        for(m=0;m<YRES;m++)
        {
            for(n=60;n<XRES;n++,bff++,ubg++)
            {
                if(*bff!=*ubg)
                {
                    cbuf=(unsigned char *)bff;
                    bakkis=(unsigned char *)ubg;
                    for(j=0;j<4;j++,cbuf++,bakkis++)
                    {
                        if(*cbuf<*bakkis)
                            (*cbuf)++;
                    }
                }
            }
            ubg+=60;
            bff+=60;
        }
    }
#endif

    if(first || reset==1)
    {
        for(n=0;n<PARTS;n++)
        {
            part[n].x=75*1024;
            part[n].y=(150+rand()%30)*1024;
            part[n].vx=2400+rand()%5100/4;
            part[n].vy=-600-rand()%5100/8;
            part[n].chargesign=rand()%2;
            part[n].charge=rand()%10240/40+10;
        }
        first=0;
    }

    for(n=0;n<howmany;n++,p++)
    {
        p->x+=p->vx;
        p->y+=p->vy;

        p->vx=p->vx*SLOWDOWN>>10;
        p->vy=p->vy*SLOWDOWN>>10;

        if(p->chargesign)
        {
            tmp=p->vx;
            p->vx+=(FORCE*p->charge>>10)*p->vy>>10;
            p->vy+=-(FORCE*p->charge>>10)*tmp>>10;
        }
        else
        {
            tmp=p->vx;
            p->vx+=-(FORCE*p->charge>>10)*p->vy>>10;
            p->vy+=(FORCE*p->charge>>10)*tmp>>10;
        }

        if(p->x<(XRES-1)*1024 && p->y>=1024 && p->y<(YRES-1)*1024)
            putpix(buf,(p->y>>10)*XRES+(p->x>>10),0);
    }
}
