
#include <stdlib.h>
#include <stdio.h>
#include "drawing.h"

#ifdef PSP

#define XS 480
#define YS 272

#else

#define XS 320
#define YS 200

#endif
#define PAX 2

void ceegm_dot(unsigned char *s,int x,int y,unsigned char col)
{
    x=(x+2)>>2;
    y=(y+2)>>2;
    if(x<XS && x>=0 && y<YS && y>=0)
        s[y*XS+x]=col;
}

/* Now this is pretty BAD */
void ceegm_line(unsigned char *s,int *v,int thick,unsigned char col)
{
    int sx,sy,ex,ey,dx,dy,
        n,i,tmp;

    sx=v[0]; sy=v[1];
    ex=v[2]; ey=v[3];

    if(sx==ex && sy==ey)
    {
        for(i=0;i<thick;i++)
            ceegm_dot(s,sx+i*4-thick*2,sy,col);
        return;
    }

    dx=ex-sx;
    dy=ey-sy;

    if(abs(dx)>abs(dy)) /* Inc X */
    {
        if(sx>ex)
        {
            tmp=sx; sx=ex; ex=tmp;
            tmp=sy; sy=ey; ey=tmp;
            dx=-dx;
        }
        sy=(sy<<14)+8192; ey=(ey<<14)+8192;
        dy=(ey-sy)/dx;
        if(thick==1)
            for(n=sx;n<=ex;n++,sy+=dy)
                ceegm_dot(s,n,sy>>14,col);
        else
            for(n=sx;n<=ex;n++,sy+=dy)
                for(i=0;i<thick;i++)
                    ceegm_dot(s,n,i*4-thick*2+(sy>>14),col);
    }
    else /* Inc Y */
    {
        if(sy>ey)
        {
            tmp=sx; sx=ex; ex=tmp;
            tmp=sy; sy=ey; ey=tmp;
            dy=-dy;
        }
        sx=(sx<<14)+8192; ex=(ex<<14)+8192;
        dx=(ex-sx)/dy;
        if(thick==1)
            for(n=sy;n<=ey;n++,sx+=dx)
                ceegm_dot(s,sx>>14,n,col);
        else
            for(n=sy;n<=ey;n++,sx+=dx)
                for(i=0;i<thick;i++)
                    ceegm_dot(s,i*4-thick*2+(sx>>14),n,col);
    }
}

DRAWING *drawing_load(char *name)
{
    DRAWING *d;
    FILE    *f;
    int     i,n,line,tmp;

    d=malloc(sizeof(DRAWING));
    d->lines=0;

    f=fopen(name,"rb");
    if(f==NULL)
        return(NULL);

    line=0;
    i=0;
    while(1)
    {
        fscanf(f,"%d",&n);
        if(n==-1)
            break;

        d->verts[line]=n;
        d->v[line]=malloc(n*2*sizeof(short));
        for(i=0;i<n*2;i++)
        {
            fscanf(f,"%d",&tmp);
            d->v[line][i]=tmp>>1;
            if(i&1)
                d->v[line][i]-=26*4;
        }
        line++;
    }
    d->lines=line;

    fclose(f);
    
    return(d);
}

void drawing(unsigned char *s,DRAWING *d,int start,int end,unsigned char col)
{
    int n,i,v[4],total=0;

    for(n=0;n<d->lines;n++)
    {
        for(i=0;i<d->verts[n]-1;i++,total++)
        {
            if(total<start)
                continue;
            if(total>end)
                return;
            v[0]=d->v[n][i<<1]; v[1]=d->v[n][(i<<1)+1];
            v[2]=d->v[n][(i+1)<<1]; v[3]=d->v[n][(i+1<<1)+1];
            ceegm_line(s,v,PAX,col);
        }
    }
}
