#include <math.h>
#include "project_volumes.h"
#include "project_textures.h"
#include "fx_colors.h"

int fxp_fsin1[32768],fxp_fsin2[32768],fxp_fsin3[32768];
unsigned int fxp_argb[256];

bool FxPlasmaInit = false;
bool FxPlasmaColorsInit = false;

void InitFxPlasmaColors()
{
	if (FxPlasmaColorsInit) return;

    SetPalette(fxp_argb, GetColor(0,0,0,0), GetColor(255,127,0,191), 0, 63);
    SetPalette(fxp_argb, GetColor(255,127,0,192), GetColor(127,255,255,255), 64, 127);
    SetPalette(fxp_argb, GetColor(127,255,255,255), GetColor(0,127,255,192), 128, 191);
    SetPalette(fxp_argb, GetColor(0,127,255,191), GetColor(0,0,0,0), 192, 255);

	GenPalletteTexture(256, fxp_argb, 64);

	FxPlasmaColorsInit = true;
}

void InitFxPlasma(Cvolume *vol)
{
    float l = (float)vol->GetWidth() / 128.0f;
    for (int i=0; i<32768; i++)
	{
		fxp_fsin1[i]=(int)(sin(i/(l*15.0))*96.0+96.0);
		fxp_fsin2[i]=(int)(sin(i/(l*20.0))*112.0+112.0);
		fxp_fsin3[i]=(int)(sin(i/(l*35.0))*128.0+128.0);
	}

	InitFxPlasmaColors();

	FxPlasmaInit = true;
}

void FxRunPlasma(Cvolume *vol, int ticks)
{
	if (!FxPlasmaInit) InitFxPlasma(vol);

    int k = ticks >> 5;

	int vsize = vol->GetWidth();
	unsigned char *voxels = vol->GetDataPointer();

    int i = 0;
    for (int z=0; z<vsize; z++)
    {
        for (int y=0; y<vsize; y++)
        {
            for (int x=0; x<vsize; x++)
            {
                unsigned char c = fxp_fsin1[x] + fxp_fsin2[y] + fxp_fsin3[z] + fxp_fsin1[x+y+k] + fxp_fsin2[x+z+k+k] + fxp_fsin3[y+z+k+k+k];
                voxels[i++] = c;
            }
        }
    }
}
