#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.setFunction(
		"uniform float dh, sigma, MX, MY;"
		"void main(void){"
		"vec4 hsv = RGBtoHSV(getPix());"
		"hsv[0] = mod(hsv[0]+dh, 360.0);"
		//"hsv[1] = hsv[1]*GaussianM0(length(vec2(xfp()-MX, yfp()-MY)), sigma);"
		//"hsv[2] = 0.5+(hsv[2]-0.5)*GaussianM0(length(vec2(xfp()-MX, yfp()-MY)), sigma);"
		"gl_FragColor = HSVtoRGB(hsv);"
		"}"
	);
	img.orig_vars.push_back("dh");
	img.orig_vars.push_back("sigma");
	img.orig_vars.push_back("MX");
	img.orig_vars.push_back("MY");
	Image orig_img("01.png");
	orig_img.cache();
	img.cache();



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


	while(!Keyboard::esc.pushed()) {
		img.var(img.orig_vars[2], cnvs.mouse().x-orig_img.getDatum().x);
		img.var(img.orig_vars[3], cnvs.mouse().y-orig_img.getDatum().y);
		if(dial1.changed()) img.var(img.orig_vars[0], val);
		if(dial2.changed()) img.var(img.orig_vars[1], sigma);
		cnvs.clear(Color::gray);
//		orig_img.centering(300,300);
		orig_img.centering();
		img.draw(orig_img);
//		orig_img.centering(700,550).draw();
		dial1.draw();
		dial2.draw();
		cnvs.flip();
	}
}

