/**
 * @author zz85 / https://github.com/zz85 | https://www.lab4games.net/zz85/blog
 * modified by rimina / Paraguay
 *
 * Edge Detection Shader using Sobel filter
 * Based on http://rastergrid.com/blog/2011/01/frei-chen-edge-detector
 *
 * aspect: vec2 of (1/width, 1/height)
 */

THREE.EdgeShader2 = {

	uniforms: {
		"tDiffuse": { type: "t", value: null },
		"resolution":    { type: "v2", value: new THREE.Vector2(1280,720) },
        "additive": {type: "i", value: 0}
	},

	vertexShader: [

		"varying vec2 vUv;",

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

		"}"

	].join( "\n" ),

	fragmentShader: [

		"uniform sampler2D tDiffuse;",
		"uniform vec2 resolution;",
        "uniform int additive;",
        "varying vec2 vUv;",

        "void main(void){",
            "vec2 texel = vec2(1.0 / resolution.x, 1.0 / resolution.y);",

            "mat3 g0 = mat3( 1.0, 2.0, 1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -1.0 );",
            "mat3 g1 = mat3( 1.0, 0.0, -1.0, 2.0, 0.0, -2.0, 1.0, 0.0, -1.0 );",
            "mat3 G[2];",
            "G[0] = g0;",
            "G[1] = g1;",
            //Unrolled version because D3D conversion with ANGLE refuses to compile
            //the loop version because of bad l value... -rimina
            "mat3 I = mat3(",
                "length(texture2D(tDiffuse, vUv + texel * vec2(-1.0,-1.0)).rgb),",
                "length(texture2D(tDiffuse, vUv + texel * vec2(-1.0,0.0)).rgb),",
                "length(texture2D(tDiffuse, vUv + texel * vec2(-1.0,1.0)).rgb),",

                "length(texture2D(tDiffuse, vUv + texel * vec2(0.0,-1.0)).rgb),",
                "length(texture2D(tDiffuse, vUv + texel * vec2(0.0,0.0)).rgb),",
                "length(texture2D(tDiffuse, vUv + texel * vec2(0.0,1.0)).rgb),",

                "length(texture2D(tDiffuse, vUv + texel * vec2(1.0,-1.0)).rgb),",
                "length(texture2D(tDiffuse, vUv + texel * vec2(1.0,0.0)).rgb),",
                "length(texture2D(tDiffuse, vUv + texel * vec2(1.0,1.0)).rgb)",
            ");",

            "float cnv[2];",
            /* calculate the convolution values for all the masks */
            "for (int i=0; i<2; i++) {",
                "float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);",
                "cnv[i] = dp3 * dp3;",
            "}",

            "gl_FragColor = vec4(0.5 * sqrt(cnv[0]*cnv[0]+cnv[1]*cnv[1]));",
            //Some tweaks for the demo -rimina
            "gl_FragColor.rgb *= (texture2D(tDiffuse, vUv).rgb * vec3(2.0, 2.2, 2.6));",
            "if(additive == 1){",
                "gl_FragColor.rgb += (texture2D(tDiffuse, vUv).rgb * vec3(0.2, 0.3, 0.4));",
            "}",

        "}",

	].join( "\n" )

};
