// Spiral.
// Written by Nils Liaaen Corneliusen 2019.
// https://www.ignorantus.com
// License: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication license

#include <math.h>
#include <assert.h>

#include "bmp.h"
#include "vec.h"


// It's based on "Look me in the eyes" by Fabrice Neyret: https://www.shadertoy.com/view/ldBGDc
// It has a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
// But I just borrowed these four lines, which is trivial math:

static float spiralit(v2 m, float t) {
	float r = v2_length(m);
	float a = atan2f(m.y, m.x);
	float v = sinf(100.0f*(sqrtf(r)-0.02f*a-0.3f*t));
	return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v;

}

void spiral_draw( bmp_argb *dst, v3 col, int frame, bool blend )
{
	for( int y = 0; y < dst->h; y++ ) {

		uint32_t *dstrow = (uint32_t *)(dst->argb+y*dst->stride);
	
		for( int x = 0; x < dst->w; x++ ) {

			float v = spiralit(v2_sub( v2_set( .9, .5 ), v2_set( x/(float)dst->h, y/(float)dst->h )), frame/60.0f );

			v3 pix;

			if( blend ) {

				uint32_t srcpixel8 = *dstrow;
				float srcr = ((srcpixel8>>16)&0xff)/255.0f;
				float srcg = ((srcpixel8>> 8)&0xff)/255.0f;
				float srcb = ((srcpixel8>> 0)&0xff)/255.0f;
				v3 srcpixel = v3_set( srcr, srcg, srcb );

				pix = v3_mix( srcpixel, col, v );
			
			} else {

				pix = v3_mul1( col, v );
			
			}


			int r = (int)(pix.x * 255.0f);
			int g = (int)(pix.y * 255.0f);
			int b = (int)(pix.z * 255.0f);
			uint32_t pixel = (r<<16)|(g<<8)|(b<<0);

			*dstrow++ = pixel;

		}
	
	}
}

#if 0
void spiral_texture( bmp_argb *dst, bmp_argb *tx, v3 col, int frame )
{
	assert( dst->w == tx->w );
	assert( dst->h == tx->h );
	assert( dst->stride == tx->stride );

	for( int y = 0; y < dst->h; y++ ) {

		uint32_t *srcrow = (uint32_t *)(tx->argb+y*tx->stride);
		uint32_t *dstrow = (uint32_t *)(dst->argb+y*dst->stride);
	
		for( int x = 0; x < dst->w; x++ ) {

			float v = spiralit(v2_sub( v2_set( .9, .5 ), v2_set( x/(float)dst->h, y/(float)dst->h )), frame/60.0f );

			uint32_t srcpixel8 = *srcrow++;
			float srcr = ((srcpixel8>>16)&0xff)/255.0f;
			float srcg = ((srcpixel8>> 8)&0xff)/255.0f;
			float srcb = ((srcpixel8>> 0)&0xff)/255.0f;
			v3 srcpixel = v3_set( srcr, srcg, srcb );

			v3 dstpixel = v3_mix( srcpixel, col, v );

			int r = (int)(dstpixel.x * 255.0f);
			int g = (int)(dstpixel.y * 255.0f);
			int b = (int)(dstpixel.z * 255.0f);
			uint32_t dstpixel8 = (r<<16)|(g<<8)|(b<<0);

			*dstrow++ = dstpixel8;

		}
	
	}
}
#endif
