#include <psychlops.h>
using namespace Psychlops;

void psychlops_main() {
	Canvas cnvs(1024,768,Canvas::window);
	cnvs.watchFPS();
	cnvs.showFPS();
	Mouse::show();
	Color::setGammaValue(1.0,1.0,1.0);

	Figures::ShaderImage img;
/*	img.setFunction(
		"uniform float frequency;"
		"void main(void){"
		"float sigma_ = 2.0/frequency;"
		"float freq_ = frequency;"
		"float r = length(vec2(xp()-RECT_WIDTH/2.0, yp()-RECT_HEIGHT/2.0));"
		"float level = 0.5+0.5*cos(r*freq_) * GaussianM0(r, sigma_);"
		"gl_FragColor = vec4(level, 0.0,0.0,1.0);"
		"}"
	);*/
/*
	img.setFunction(
		"uniform float frequency;"
		"vec4 GaussianConvolute(in float frequency_) {"
		"float sigma_ = 2.0/frequency_;"
		"int lim = int(sigma_*3.0);"
		"vec4 color = vec4(0.0,0.0,0.0,0.0);"
		"float factor = 0.0, cur=0.0, r=0.0;"
		"for(int y=-lim; y<=lim; y++) { for(int x=-lim; x<=lim; x++) {"
		"     r = length(vec2(x,y));"
		"     cur = cos(r*frequency_) * GaussianM0(r, sigma_);"
		"     factor += cur;"
		"     color += cur*getPix(x,y);"
		"} }"
		"color /= factor;"
		"return color;"
		"}"
		"void main(void){"
//		"float _y = abs(xi()-0.5)*frequency;"
		"gl_FragColor = GaussianConvolute(frequency);"
		"}"
	);*/
/*	img.setFunction(
		"uniform float sigma;"
		"vec4 GaussianConvolute(in float sigma_) {"
		"int lim = int(sigma_*3.0);"
		"vec4 color = vec4(0.0,0.0,0.0,0.0);"
		"float factor = 0.0, cur=0.0;"
		"for(int y=-lim; y<=lim; y++) { for(int x=-lim; x<=lim; x++) {"
		"     cur = GaussianM0(length(ivec2(x,y)), sigma_);"
		"     factor += cur;"
		"     color += cur*getPix(x,y);"
		"} }"
		"return color / factor;"
		"}"
		"void main(void){"
		"float _y = abs(xi()-0.5)*sigma;"
		"gl_FragColor = GaussianConvolute(_y);"
		"}"
	);
*/	img.cache(
		"void main(void){"
		"float dh = gl_TexCoord[4][0], sigma = gl_TexCoord[4][1], MX = gl_TexCoord[4][2], MY = gl_TexCoord[4][3];"
		"vec4 hsv = RGBtoHSV(getPix());"
		"hsv[0] = mod(hsv[0]+dh, 360.0);"
		"hsv[1] = hsv[1]*GaussianM0(distance(vec2(MX, MY), vec2(xp(), yp())), sigma);"
		"pix(HSVtoRGB(hsv));"
		"}"
	);
	Image orig_img("01.png");
	orig_img.cache();


	double val = 0, sigma = 100.0;
	Widgets::Dial dial1, dial2;
	dial1.link(val,   360).set(50).centering().shift(-50,0);
	dial2.link(sigma, 100).set(50).centering().shift( 50,0);


	while(!Keyboard::esc.pushed()) {
		cnvs.clear(Color::gray);
//		orig_img.centering(300,300);
		orig_img.centering();
		img.argv(val, sigma, cnvs.mouse().x-orig_img.getLeft(), cnvs.mouse().y-orig_img.getTop());
		img.draw(orig_img);
//		orig_img.centering(700,550).draw();
		dial1.draw();
		dial2.draw();
		cnvs.flip();
	}
}

