/* $VER: WBStars_plot.c 2.0 (18 Dec 1996)
*/

#include <exec/types.h>
#include <exec/memory.h>
#include <intuition/intuition.h>
#include <proto/exec.h>
#include <clib/alib_protos.h>

#include "WBStars_plot.h"

struct Flake
{
	struct Flake	*next;
	struct Flake	*last;
	int	x;
	int	y;
	int	sticky;
	char	drawn;
	int	dir;
};

void	NewFlake( void );
void	ClearFlake(struct Flake *f);

struct Flake	*Flakes		= NULL;
int 		Flake_cnt	= 0;

void	InitObjects()
{
	/* nothing to do here */
}

void	NewFlake()
{
	struct Flake	*f;

	if( ((Max_Objects<0)||(Flake_cnt<Max_Objects)) && (f=(struct Flake*)AllocMem(sizeof(struct Flake),0)) )
	{
		f->next		= Flakes;
		if( Flakes!=NULL ) Flakes->last	= f;
		f->last		= NULL;
		f->x		= RangeRand(width);
		f->y		= 0;
		f->sticky	= 0;
		f->drawn	= FALSE;
		Flakes		= f;
		Flake_cnt++;
	}
}

void	ClearFlake(struct Flake *f)
{
	if( f->next!=NULL ) f->next->last=f->last;
	if( f->last!=NULL )
	{
		f->last->next=f->next;
	}
	else
	{
		Flakes=f->next;
	}
	FreeMem( f, sizeof(struct Flake) );
	Flake_cnt--;
}

void	ClearObjects()
{
	struct	Flake	*f;
	char	dummy;

	while( Flakes!=NULL )
	{
		dummy = ClearPixelTest(Flakes->x,Flakes->y);

		f=Flakes->next;
		FreeMem( Flakes, sizeof(struct Flake) );
		Flakes=f;
	}
	Flake_cnt=0;
}

void	PlotObjects()
{
	struct Flake	*f;
	struct Flake	*next;
	int		newx;
	int		newy;
	int		addx;
	char	dummy;

	NewFlake();

	for(f=Flakes; f!=NULL; f=next)
	{
		next		= f->next;
		if( (!f->sticky) || (Max_Stick>=0) )
		{
			newy		= f->y +1;

			if( f->dir==0 )
			{
				addx	= RangeRand(3) -1;
			}
			else
			{
				addx	= RangeRand(2)*SIGN(f->dir);
			}
			newx		= f->x +addx;

			LockPlotArea();

			if( (newy>=height) || (newx<0) || (newx>=width) )
			{
				if(f->drawn) dummy=ClearPixelTest(f->x,f->y);
				ClearFlake(f);
			}
			else
			{
				if( (!f->drawn) || Test1Pixel(f->x,f->y) )
				{
					if( SetPixelTest(newx,newy) )
					{
						if(f->drawn) ClearPixel(f->x,f->y);
						f->x		= newx;
						f->y		= newy;
						f->drawn	= TRUE;
						f->sticky	= 0;
						f->dir		= addx;
					}
					else
					{
						if( SetPixelTest(f->x,newy) )
						{
							if(f->drawn) ClearPixel(f->x,f->y);
							f->y		= newy;
							f->drawn	= TRUE;
							f->sticky	= 0;
							f->dir		= 0;
						}
						else
						{
							if( ((f->sticky++)>Max_Stick) && (Max_Stick>=0) )
							{
								dummy=ClearPixelTest(f->x,f->y);
								ClearFlake(f);
							}						
						}
					}
				}
				else
				{
					dummy=ClearPixelTest(f->x,f->y);
					ClearFlake(f);
				}
			}
		}
		UnlockPlotArea();
	}
}
