/* $VER: WBStars_plot.c 2.0b4 (28 May 1997)
*/

#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;
	char	color;
};

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;

	while( Flakes!=NULL )
	{
		ClearPixel(Flakes->x,Flakes->y,Flakes->color);

		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		v_flut;
	char		color;

	NewFlake();

	for(f=Flakes; f!=NULL; f=next)
	{
		next= f->next;
		if( (!(f->sticky) || (Max_Stick>=0)) &! (f->sticky%Check_Stick) )
		{
			if( (RangeRand((V_Flutter)+100)<100) || f->sticky )
			{
				newy	= f->y +1;
				v_flut	= FALSE;
			}
			else
			{
				newy	= f->y;
				v_flut	= TRUE;
			}

			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) ClearPixel(f->x,f->y,f->color);
				ClearFlake(f);
			}
			else
			{
				if( (color=SetPixel(newx,newy,Force))!=-1 )
				{
					if(f->drawn) ClearPixel(f->x,f->y,f->color);
					f->x		= newx;
					f->y		= newy;
					f->sticky	= 0;
					f->drawn	= TRUE;
					f->dir		= addx;
					f->color	= color;
				}
				else
				{
					if( !v_flut )
					{
						f->dir		= 0;
						if( (color=SetPixel(f->x,newy,Force))!=-1 )
						{
							if(f->drawn) ClearPixel(f->x,f->y,f->color);
							f->y		= newy;
							f->sticky	= 0;
							f->drawn	= TRUE;
							f->color	= color;
						}
						else
						{
							if( !f->drawn )
							{
								ClearFlake(f);
							}
							else
							{
								if( Remember || Test1Pixel(f->x,f->y) )
								{
									if( ((f->sticky++)>Max_Stick) && (Max_Stick>=0) )
									{
										ClearPixel(f->x,f->y,f->color);
										ClearFlake(f);
									}
								}
								else
								{
									ClearFlake(f);
								}
							}
						}
					}
				}
			}
			UnlockPlotArea();
		}
		else
		{
			f->sticky++;
		}
	}
}
