/*
    Heart-shaped L-system, or something
    -Marq
*/

#include <math.h>
#include <stdlib.h>
#include "heart.h"
#include "putpix.h"

static MATO mato[MAXMATOS];

// Heart L-system-like effect
void heart(buftype *buf,PNG *hart)
{
    int n,i,livematos=0,off;
    buftype *piccy=(buftype *)hart->data;
    static int first=1;

    if(first)
    {
        for(n=0;n<MAXMATOS;n++)
            mato[n].alive=0;

        mato[0].x=215; // First line
        mato[0].y=180;
        mato[0].xd=-1;
        mato[0].yd=-1;
        mato[0].maxlife=60;
        mato[0].life=0;
        mato[0].alive=1;

        first=0;
    }

    for(n=0;n<MAXMATOS;n++)
    {
        if(mato[n].alive)
        {
            mato[n].x+=mato[n].xd;
            mato[n].y+=mato[n].yd;

            off=mato[n].y*XRES+mato[n].x;

#ifdef HICOLOR
            if((piccy[off]&0x8410)==0x8410 ||
                !(buf[off]&0x410))
#else
            if((piccy[off]&0x808080)==0x808080 ||
                !(buf[off]&0x8080))
#endif
            {
                mato[n].alive=0;
                continue;
            }

            putpix(buf,off,piccy[off]);

            mato[n].life++;

            // Span new ones at end and somewhere in the middle
            if(mato[n].life==mato[n].maxlife
               || mato[n].life==mato[n].maxlife/3*2
               || mato[n].life==mato[n].maxlife/3)
            {
                for(i=0;i<MAXMATOS;i++) // Brutal...
                {
                    if(!mato[i].alive && n!=i)
                    {
                        mato[i].x=mato[n].x; // First line
                        mato[i].y=mato[n].y;

                        if(mato[n].life==mato[n].maxlife/3*2)
                        {
                            mato[i].xd=-mato[n].yd;
                            mato[i].yd=mato[n].xd;
                        }
                        else
                        {
                            mato[i].xd=mato[n].yd;
                            mato[i].yd=-mato[n].xd;
                        }

                        mato[i].maxlife=13+rand()%10;
                        mato[i].life=0;
                        mato[i].alive=1;
                        break;
                    }
                }

                if(mato[n].life==mato[n].maxlife)
                    mato[n].alive=0;
            }

            livematos++;
            if(livematos==MAXRUN)
                return;
        }
    }
}
