#include <vga.h>
#include <stdlib.h>

#include "sintab.h"

#define S() (srand48(getpid()))
#define R(x) (drand48()*x)
#define RR(x,y) (drand48()*(x-y+1)+y)

#define NOSHOW (0)
#define XSIZE (320/XMAG)
#define YSIZE ((200/YMAG)+NOSHOW)
#define XMAG (4)
#define YMAG (4)
#define MOVE (TABSIZE/16)
#define CMOVE (TABSIZE/64)
#define SPOTS (16)
#define DECR 5

int spots[10][SPOTS];
char line[XSIZE*XMAG*3];

int world[YSIZE][XSIZE][3][2];
#define W(x,y,z) (world[y][x][z][f])
#define O(x,y,z) (world[y][x][z][1-f])

frame() {
	static int f=0;
	int x,y,xx,yy,i,j,c[3];
	unsigned char *lp;

	f=1-f;
	yy=0;
	for(i=0;i<3;i++) for(j=0;j<SPOTS;j++) O(spots[3][j],spots[4][j],i)|=spots[i][j];
	for(y=0;y<YSIZE;y++) {
		lp=line;
		for(x=0;x<XSIZE;x++) {
			for(i=0;i<3;i++) {
				if(O(x,y,0)+O(x,y,1)+O(x,y,2)>32) W(x,y,i)=O(x,y,i)*240/256;
				else W(x,y,i)=O(x,y,i);
				if (W(x,y,i)<0) W(x,y,i)=0;
				j=W(x,y,i); if(j>255)j=255;
				c[i]=j;
			}
			for(xx=0;xx<XMAG;xx++) {
				*(lp++)=c[0];
				*(lp++)=c[1];
				*(lp++)=c[2];
			}
		}
		if (y<(YSIZE-NOSHOW)) 
			for(xx=0;xx<YMAG;xx++) 
				vga_drawscansegment(line,0,yy++,3*XSIZE*XMAG); 
		
	}
	for(j=0;j<SPOTS;j++) {
		int r,t;
		spots[7][j]+=RR(-MOVE,MOVE);
		spots[8][j]+=COS(spots[7][j]); if (spots[8][j]<0) spots[8][j]+=XSIZE*TABMAG; if (spots[8][j]>(XSIZE*TABMAG-1)) spots[8][j]-=XSIZE*TABMAG;
		spots[9][j]+=SIN(spots[7][j]); if (spots[9][j]<0) spots[9][j]+=YSIZE*TABMAG; if (spots[9][j]>(YSIZE*TABMAG-1)) spots[9][j]-=YSIZE*TABMAG;
		spots[3][j]=spots[8][j]/TABMAG;
		spots[4][j]=spots[9][j]/TABMAG;
		spots[5][j]+=RR(-CMOVE,CMOVE); if(spots[5][j]<0)spots[5][j]=0; if(spots[5][j]>(TABSIZE/4))spots[5][j]=TABSIZE/4;
		spots[6][j]+=RR(-CMOVE,CMOVE); if(spots[6][j]<0)spots[6][j]=0; if(spots[6][j]>(TABSIZE/4))spots[6][j]=TABSIZE/4;
		r=spots[5][j]; t=spots[6][j];
		spots[0][j]=(SIN(r)*COS(t))/(TABMAG*TABMAG/256);
		spots[1][j]=COS(r)*COS(t)/(TABMAG*TABMAG/256);
		spots[2][j]=SIN(t)/(TABMAG/256);
	}
}
	
main(int argc, char **argv[]) {
	int i,j,r,t;

	S();

	vga_setmode(G320x200x16M); 

	for(j=0;j<SPOTS;j++) {
		spots[3][j]=(spots[8][j]=R(TABMAG*XSIZE)+1)/TABMAG;
		spots[4][j]=(spots[9][j]=R(TABMAG*YSIZE)+1)/TABMAG;
		spots[5][j]=r=R(TABSIZE/4);	
		spots[6][j]=t=R(TABSIZE/4);
		spots[0][j]=(SIN(r)*COS(t))/(TABMAG*TABMAG/256);
		spots[1][j]=COS(r)*COS(t)/(TABMAG*TABMAG/256);
		spots[2][j]=SIN(t)/(TABMAG/256);
		spots[7][j]=R(TABSIZE);
	}

 	while(1) frame();
}
