/*
 * Paraguay fades by rimina
 */

THREE.ParaguayFades = {

	uniforms: {
		"tDiffuse": { type: "t", value: null },
		"brightness": { type: "f", value: 0 },
		"negate": { type: "i", value: 0 },
		"grayscale": { type: "i", value: 0 },
		"fade": { type: "f", value: 0 },
		"fadeColor": { type: "v3", value: new THREE.Vector3(0, 0, 0) },
		"uHb": { type: "f", value: 0.0 },
	},

	vertexShader: [

		"varying vec2 vUv;",
		"void main() {",
		"vUv = uv;",
		"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
		"}"

	].join("\n"),

	fragmentShader: [

		"uniform sampler2D tDiffuse;",
		"uniform float brightness;",
		"uniform float fade;",
		"uniform vec3 fadeColor;",
		"uniform int negate;",
		"uniform int grayscale;",
		"uniform float uHb;",

		"varying vec2 vUv;",

		//chromatic abbreviation
		"vec3 ca(vec2 u){",
		"vec3 c=vec3(0);",
		"float rf=1., gf=1., bf=1.;",
		"float canim = 50.0*smoothstep(7.0,9.0,uHb);",
		"for(int i = 0; i < 25+int(canim); ++i){",
		"c.r+=texture(tDiffuse, 0.5+0.5*(u*rf)).r;",
		"c.g+=texture(tDiffuse, 0.5+0.5*(u*gf)).g;",
		"c.b+=texture(tDiffuse, 0.5+0.5*(u*bf)).b;",
		"rf*=.9988/(1.0+0.0002*canim);",
		"gf*=.9982/(1.0+0.0002*canim);",
		"bf*=.996/(1.0+0.0002*canim);",
		"}",
		"return c/(25.0+canim*0.25);",
		"}",

		"void main() {",
		"vec4 c = texture2D( tDiffuse, vUv );",

		"c += vec4(ca(-1.+2.*vUv), 1.0);",

		//Brightness
		"c.rgb += brightness;",
		"c.rgb = clamp(c.rgb, vec3(0.), vec3(1.));",

		//fade
		"c.rgb = mix(c.rgb, fadeColor, smoothstep(0.0, 1.0, fade));",

		//negate
		"if(negate == 1){",
		"c.rgb = vec3(1.)-c.rgb;",
		"}",

		//grayscale
		"if(grayscale ==  1){",
		"c.rgb = vec3( c.r * 0.3 + c.g * 0.59 + c.b * 0.11 );",

		"}",

		"gl_FragColor = c;",
		"}"

	].join("\n")

};
