
#version 130

uniform sampler2D texture;

uniform vec4 sideColour = vec4(1, 1, 1, 1);
uniform bool sideColourSwap = true;

uniform vec2 textureSize = vec2(0, 0);
uniform vec2 imageSize = vec2(0, 0);
uniform vec2 imagePos = vec2(0, 0); // image position on texture

uniform bool hasMaskTexture = false;
uniform sampler2D maskTexture;

uniform vec2 screenSize = vec2(512, 512);
uniform float renderScale = 1;
uniform vec2 mapScroll = vec2(0,0);
uniform float time = 0;

uniform bool grimeEnabled = true;
uniform bool shineEnabled = true;
uniform float angle = 0;

uniform int objectID = 0;

#include "Shared/Perlin.frag"


void main()
{
	bool sideColourSwapped = false;

	if(sideColourSwap)
	{
		// swap magic pink pixels for side colour
		vec4 pixel = texture2D(texture, gl_TexCoord[0].xy) * gl_Color;

		if(pixel.r >= 0.5 && pixel.g >= 0.5 && pixel.b >= 0.5)
		{
			gl_FragColor = sideColour * pixel;
			sideColourSwapped = true;
		}
		else
		{
			gl_FragColor = pixel;
		}
	}
	else
	{
		vec4 pixel = texture2D(texture, gl_TexCoord[0].xy) * gl_Color;
		gl_FragColor = pixel;
	}

	// grime
	if(grimeEnabled && gl_FragColor.a > 0)
	{
		vec2 screenPos = gl_FragCoord.xy;
		screenPos.y = screenSize.y - screenPos.y;

		vec2 uvPerlin = (gl_TexCoord[1].xy * textureSize) - imagePos;	
		uvPerlin /= 22;

		uint seed = uint(objectID + 20000);
		float sample = perlin2D(uvPerlin, 2, 3, seed);
		vec4 noisePixel = vec4(sample, sample, sample, 1);

		gl_FragColor = mix(gl_FragColor, noisePixel, 0.16);
	}

	// shine
	if(shineEnabled && gl_FragColor.a > 0)
	{
		if(hasMaskTexture)
		{
			vec2 screenPos = gl_FragCoord.xy;
			screenPos.y = screenSize.y - screenPos.y;			

			vec2 uvPerlin;

			vec2 imageCoord = (textureSize * gl_TexCoord[1].xy) - imagePos;

			float posMulti = 20;

			vec2 imageNormalisedPos = imageCoord / imageSize;

			float radius = 10; //10;//0.1 * imageSize.x;
			uvPerlin.x = 100000 + (imageNormalisedPos.x * posMulti) + (cos(radians(angle)) * radius);
			uvPerlin.y = 100000 + (imageNormalisedPos.y * posMulti) - (sin(radians(angle)) * radius);

			uvPerlin *= 0.005;

			uvPerlin += (time * 0.005);

			int freq = 25;

			uint seed = 4232312u;
			float sample = perlin2D(uvPerlin, freq, 2, seed);
			
			vec4 noisePixel = vec4(sample, sample, sample, 1);

			// mask texture red channel is brightness
			vec4 bright = texture2D(maskTexture, gl_TexCoord[1].xy).rrra;
			if(bright.a > 0 && bright.r > 0 && sample > 0)
			{
				bright *= 0.65;

				float a = gl_FragColor.a;
				gl_FragColor = gl_FragColor + (noisePixel * bright);
				gl_FragColor.a = a;
				
			}
		}
	}

}
