/*  Plasma
 *  Copyright (C) Joakim Kolsjö and Anders Asplund 2003/2004
 *	This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
 */

#include "gfx_plasma.h"
#include <iostream>
#include <cmath>

using namespace std;

namespace gfx
{	
	void Plasma::init(xio::Manager *i, xio::surface *tsurf)
	{
		xio = i;
		target = tsurf;
		
		map_red = new xio::u8[target->w * target->h];
		map_green = new xio::u8[target->w * target->h];
		map_blue = new xio::u8[target->w * target->h];
		// Red
		for(int y=0; y < target->h; ++y)
		{
			for(int x=0; x < target->w; ++x)
			{
				map_red[y * target->w + x] = (int)(79 + 78.0f * sin((
					1.5f * (target->w - x) / target->w *
					3.0f * y / target->h ))); 
			}
		}

		// Green
		for(int y = 0; y < target->h; ++y)
		{
			for(int x = 0; x < target->w; ++x)
			{
				map_green[y * target->w + x] =
					54 + (int)(53.0 * cos( (float)x /
					(25.0f + 10.0f * cos((float)y / 97.0f)) ) *
					sin((float)y / (36.0f + 12.0f * sin((float)x/67.0f))));

			}
		}	

		// Blue
		for(int y = 0; y < target->h; ++y)
		{
			for(int x=0; x < target->w; ++x)
			{
				map_blue[y * target->w + x] = 
					(int)(20 + 19.0f * sin((sqrt((double)(y*y + x*x))) / 200.0f)); 
			}
		}
		
		pr = new xio::u8[256];
		pg = new xio::u8[256];
		pb = new xio::u8[256];
	}
	
	void Plasma::draw(long time, int dx, int dy, float alpha)
	{	
    	for(int i = 0; i < 256; i++)
		{
			pr[i] = (xio::u8)(128 + 128.0f * cos((i * M_PI / 64.0 + time/740.0f)));
			pg[i] = (xio::u8)(128 + 128.0f * sin((i * M_PI / 64.0 + time/630.0f)));
			pb[i] = (xio::u8)(128 - 128.0f * cos((i * M_PI / 64.0 + time/810.0f)));
    	}	
		
		// Draw plasma
		for(int y = 0; y < target->h-1; y++)
		{
			for(int x = 0; x < target->w-1; x++)
			{
				xio->video->setPixel(target, x, y,
					pr[map_red[y * target->w + x]],
					pg[map_green[y * target->w + x]],
					pb[map_blue[y * target->w + x ]]);
			}
		}
	}
}
