//////////////////////////////////////////////////////////////////////////////
//    ##      #####   ######   ######     ##     ####     #######  ##  ##   //
//   ####    ##   ##  # ## #    ##  ##   ####     ##       ##   #  ##  ##   //
//  ##  ##   #          ##      ##  ##  ##  ##    ##       ## #     ####    //
//  ##  ##    #####     ##      #####   ##  ##    ##       ####      ##     //
//  ######        ##    ##      ## ##   ######    ##   #   ## #     ####    //
//  ##  ##   ##   ##    ##      ##  ##  ##  ##    ##  ##   ##   #  ##  ##   //
//  ##  ##    #####    ####    #### ##  ##  ##   #######  #######  ##  ##   //
//--------------------------------------------------------------------------//
//--------------------------------------------------------------------------//
//      #####   ##   ##    ##     #####    #######  ######    #####         //
//     ##   ##  ##   ##   ####     ## ##    ##   #   ##  ##  ##   ##        //
//     #        ##   ##  ##  ##    ##  ##   ## #     ##  ##  #              //
//      #####   #######  ##  ##    ##  ##   ####     #####    #####         //
//          ##  ##   ##  ######    ##  ##   ## #     ## ##        ##        //
//          ##  ##   ##  ######    ##  ##   ## #     ## ##        ##        //
//     ##   ##  ##   ##  ##  ##    ## ##    ##   #   ##  ##  ##   ##        //
//      #####   ##   ##  ##  ##   #####    #######  #### ##   #####         //
/////(BSL Shaders Edit)//////////////////////////////////////By LexBoosT//////

//Settings//
#include "/lib/settings.glsl"

//Varyings//
varying vec2 texCoord, lmCoord;

varying vec3 normal;
varying vec3 sunVec, upVec, eastVec;
varying vec4 color;

#if MC_VERSION >= 11700
varying float fullLightmap;
#endif

#ifdef ADVANCED_MATERIALS
varying vec3 viewVector;

varying float dist;

varying vec3 binormal, tangent;

varying vec4 vTexCoord, vTexCoordAM;
#endif

//Fragment Shader///////////////////////////////////////////////////////////////////////////////////
#ifdef FSH

//Uniforms//
uniform int blockEntityId;
uniform int frameCounter;
uniform int isEyeInWater;
uniform int worldTime;
uniform int heldItemId;
uniform int heldItemId2;
uniform int moonPhase;
#define UNIFORM_MOONPHASE

#ifdef DYNAMIC_HAND_LIGHT
	uniform int heldBlockLightValue;
	uniform int heldBlockLightValue2;
#endif

uniform float frameTimeCounter;
uniform float nightVision;
uniform float rainStrengthS;
uniform float screenBrightness;
uniform float shadowFade;
uniform float timeAngle, timeBrightness;
uniform float viewWidth, viewHeight;

uniform vec3 cameraPosition;

uniform ivec2 eyeBrightnessSmooth;

uniform mat4 gbufferProjectionInverse;
uniform mat4 gbufferModelViewInverse;
uniform mat4 shadowProjection;
uniform mat4 shadowModelView;

uniform sampler2D texture;

#if defined (OVERWORLD) && defined WATER_CAUSTICS
uniform sampler2D noisetex;
#endif

#ifdef ADVANCED_MATERIALS
uniform ivec2 atlasSize;
uniform sampler2D specular;
uniform sampler2D normals;
#endif

uniform vec3 fogColor;

//Common Variables//

float eBS = eyeBrightnessSmooth.y / 255.0;
float sunVisibility  = clamp(dot( sunVec,upVec) + 0.0625, 0.0, 0.125) * 8.0;
float moonVisibility = clamp(dot( -sunVec,upVec) + 0.0625, 0.0, 0.125) * 8.0;
float screenBrightness2 = clamp(screenBrightness, 0.0, 1.0);

#ifdef ADVANCED_MATERIALS
vec2 dcdx = dFdx(texCoord);
vec2 dcdy = dFdy(texCoord);
#endif

	#ifdef OVERWORLD
	vec3 lightVec = sunVec * ((timeAngle < 0.5325 || timeAngle > 0.9675) ? 1.0 : -1.0);
	#else
	vec3 lightVec = sunVec;
	#endif

//Common Functions//
float GetLuminance(vec3 color){
	return dot(color,vec3(0.299, 0.587, 0.114));
}

float InterleavedGradientNoise(){
	float n = 52.9829189 * fract(0.06711056 * gl_FragCoord.x + 0.00583715 * gl_FragCoord.y);
	return fract(n + frameCounter / 8.0);
}

//Includes//
#include "/lib/color/blocklightColor.glsl"
#include "/lib/color/dimensionColor.glsl"
#include "/lib/color/specularColor.glsl"
#include "/lib/util/dither.glsl"
#include "/lib/util/spaceConversion.glsl"

#if defined (OVERWORLD) && defined WATER_CAUSTICS
#include "/lib/color/waterColor.glsl"
#endif

#include "/lib/lighting/forwardLighting.glsl"
#include "/lib/surface/ggx.glsl"

#if AA > 0
#include "/lib/util/jitter.glsl"
#endif


#ifdef ADVANCED_MATERIALS
#include "/lib/util/encode.glsl"
#include "/lib/reflections/complexFresnel.glsl"
#include "/lib/surface/materialGbuffers.glsl"
#include "/lib/surface/parallax.glsl"
#endif

#ifdef NORMAL_SKIP
#undef PARALLAX
#undef SELF_SHADOW
#endif

#ifdef SHOW_DARK_ZONES
#include "/lib/lighting/showdarkzones.glsl"
#endif

//Program//
void main(){
	vec4 albedo = texture2D(texture, texCoord) * color;
	vec3 newNormal = normal;
	float smoothness = 0.0;

		#ifdef ADVANCED_MATERIALS
		vec2 newCoord = vTexCoord.st * vTexCoordAM.pq + vTexCoordAM.st;
		float surfaceDepth = 1.0;
		float parallaxFade = clamp((dist - PARALLAX_DISTANCE) / 32.0, 0.0, 1.0);
		
		#if MC_VERSION >= 11300
		float skipAdvMat = float(blockEntityId == 10401);
		#else
		float skipAdvMat = float(blockEntityId == 63 || blockEntityId == 68);
		#endif


			#ifdef PARALLAX
			if (skipAdvMat < 0.5){
				newCoord = GetParallaxCoord(parallaxFade, surfaceDepth);
				albedo = texture2DGradARB(texture, newCoord, dcdx, dcdy) * color;
			}
			#endif
		
		float skyOcclusion = 0.0;
		vec3 fresnel3 = vec3(0.0);
		
		#endif
		
		if (albedo.a > 0.00001){
			vec2 lightmap = clamp(lmCoord, vec2(0.0), vec2(1.0));
			
			float metalness      = 0.0;
			float emission       = float(blockEntityId == 10205);
			float subsurface     = float(blockEntityId == 10109) * 0.5;
			vec3 baseReflectance = vec3(0.04);

			emission *= dot(albedo.rgb, albedo.rgb) * 0.333;

			vec3 screenPos = vec3(gl_FragCoord.xy / vec2(viewWidth, viewHeight), gl_FragCoord.z);
			#if AA > 0
			vec3 viewPos = ToNDC(vec3(TAAJitter(screenPos.xy, -0.5), screenPos.z));
			#else
			vec3 viewPos = ToNDC(screenPos);
			#endif
			vec3 worldPos = ToWorld(viewPos);
			
			float lViewPos = length(viewPos.xyz);

			#ifdef ADVANCED_MATERIALS
			float f0 = 0.0, porosity = 0.5, ao = 1.0;
			vec3 normalMap = vec3(0.0, 0.0, 1.0);
			
			GetMaterials(smoothness, metalness, f0, emission, subsurface, porosity, ao, normalMap, newCoord, dcdx, dcdy);

			#ifdef NORMAL_SKIP
			normalMap = vec3(0.0, 0.0, 1.0);
			#endif
			
			mat3 tbnMatrix = mat3(tangent.x, binormal.x, normal.x,
								  tangent.y, binormal.y, normal.y,
								  tangent.z, binormal.z, normal.z);
			
			if (normalMap.x > -0.999 && normalMap.y > -0.999)
			newNormal = clamp(normalize(normalMap.xyz * tbnMatrix), vec3(-1.0), vec3(1.0));
			#endif
			
			
			float NoL = clamp(dot(newNormal, lightVec), 0.0, 1.0);
			float NoU = clamp(dot(newNormal, upVec), -1.0, 1.0);
			float NoE = clamp(dot(newNormal, eastVec), -1.0, 1.0);
			float vanillaDiffuse = (0.25 * NoU + 0.75) + (0.667 - abs(NoE)) * (1.0 - abs(NoU)) * 0.15;
				  vanillaDiffuse*= vanillaDiffuse;

			#ifdef NEW_END_PORTAL
				if (blockEntityId == 10888) {
					if (albedo.b < 0.1) {
					vec4[16] colors = vec4[](
					vec4(0.5922, 0.3569, 0.9725, 1.0),
					vec4(0.8392, 0.3059, 1.0, 0.616),
					vec4(0.7451, 0.0941, 0.9451, 0.432),
					vec4(0.898, 0.0157, 0.9804, 0.651),
					vec4(0.149, 0.0157, 0.4549, 1.0),
					vec4(0.2353, 0.0431, 0.9412, 1.0),
					vec4(0.3961, 0.0353, 0.6392, 0.527),
					vec4(0.8784, 0.0275, 0.9922, 0.377),
					vec4(0.7216, 0.5294, 0.9765, 0.363),
					vec4(0.5804, 0.4392, 0.8431, 0.384),
					vec4(0.53406537, 0.55311275, 1.5943265 ,1),
					vec4(0.5765, 0.2431, 0.851, 0.452),
					vec4(0.5902973 , 0.4286982 , 0.64408666,1),
					vec4(0.5882, 0.1176, 0.8039, 0.479),
					vec4(0.7843, 0.4078, 0.9608, 0.418),
					vec4(0.8784, 0.0275, 0.9922, 0.349));
					albedo.rgb = colors[15].rgb*0.001;

				for (int i = 1; i < 16; i++) {
					float colormult = 1.0/(16-i+20.0);
					albedo.rgb *= 0.69 * (1.0 + float(i > 1));
					float rotation = (i - 0.1 * i + 0.71 * i - 11 * i + 21) * 0.01 + i * 0.01;
					float Cos = cos(radians(rotation));
					float Sin = sin(radians(rotation));
					vec2 offset = vec2(0.0, 1.0/(3600.0/24.0)) * pow(16.0 - i, 2.0) * 0.004;

					vec3 wpos = normalize((gbufferModelViewInverse * vec4(viewPos * (i + 1), 1.0)).xyz);
							if (abs(dot(normal, upVec)) > 0.9) {
								wpos.xz /= wpos.y;
								wpos.xz *= 0.08 * sign(- worldPos.y);
								wpos.xz *= abs(worldPos.y) + i;
								wpos.xz -= cameraPosition.xz * 0.10;
							} else {
								vec3 absPos = abs(worldPos);
								if (abs(dot(normal, eastVec)) > 0.9) {
									wpos.xz = wpos.yz / wpos.x;
									wpos.xz *= 0.08 * sign(- worldPos.x);
									wpos.xz *= abs(worldPos.x) + i;
									wpos.xz -= cameraPosition.yz * 0.10;
								} else {
									wpos.xz = wpos.yx / wpos.z;
									wpos.xz *= 0.08 * sign(- worldPos.z);
									wpos.xz *= abs(worldPos.z) + i;
									wpos.xz -= cameraPosition.yx * 0.10;
								}
							}
							vec2 pos = wpos.xz;

							vec2 wind = fract((frameTimeCounter + 984.0) * (i + 8) * 0.125 * offset);
							vec2 coord = mat2(Cos, Sin, -Sin, Cos) * pos + wind;
							if (mod(float(i), 4) < 1.5) coord = coord.yx + vec2(-1.0, 1.0) * wind.y;
							
							vec4 sample = texture2D(texture, coord) * colors[i-1] * colormult;
							albedo += sample * length(sample.rgb) * 34.0;
							emission =0.05;
				}
			} else {
				albedo.rgb *= 12.0;
				emission = 0.05;
					}
				vanillaDiffuse = 1.0;
			}
			
			#endif

			albedo.rgb = pow(albedo.rgb, vec3(2.2));
			
			#ifdef WHITE_WORLD
			albedo.rgb = vec3(0.5);
			#endif
			#ifdef BLACK_WORLD
			albedo.rgb = vec3(0.0);
			#endif

			float parallaxShadow = 1.0;

			#ifdef ADVANCED_MATERIALS
			vec3 rawAlbedo = albedo.rgb * 0.999 + 0.001;
			albedo.rgb *= ao;
			
			#ifdef REFLECTION_SPECULAR
				albedo.rgb *= 1.0 - metalness * smoothness * 0.65;
			#endif
			
			float doParallax = 0.0;
			#ifdef SELF_SHADOW
			#ifdef OVERWORLD
			doParallax = float(lightmap.y > 0.0 && NoL > 0.0);
			#endif
			#ifdef END
			doParallax = float(NoL > 0.0);
			#endif
			
			if (doParallax > 0.5){
				parallaxShadow = GetParallaxShadow(surfaceDepth, parallaxFade, newCoord, lightVec, tbnMatrix);
			}
			#endif
			#endif

			bool dolighting = true;
			#ifdef ADVANCED_MATERIALS
			#if MC_VERSION >= 11700
			if (skipAdvMat > 0.5 && fullLightmap > 0.5) {
				dolighting = false;
				#ifdef OVERWORLD
				albedo.rgb *= LIGHTSIGN_INTENSITY_OVERWORLD;
				#endif
				#ifdef NETHER
				albedo.rgb *= LIGHTSIGN_INTENSITY_NETHER;
				#endif
				#ifdef ENDER
				albedo.rgb *= LIGHTSIGN_INTENSITY_ENDER;
				#endif
			}
			#endif
			#endif

			vec3 shadow = vec3(0.0);

			if(dolighting) GetLighting(albedo.rgb, shadow, viewPos, lViewPos, worldPos, lightmap, color.a, NoL, vanillaDiffuse,
			parallaxShadow, emission, 0.0, 0.0, 1.0);
			
			#ifdef ADVANCED_MATERIALS
			skyOcclusion = lightmap.y * lightmap.y * (3.0 - 2.0 * lightmap.y);
			
			baseReflectance = mix(vec3(f0), rawAlbedo, metalness);
			float fresnel = pow(clamp(1.0 + dot(newNormal, normalize(viewPos.xyz)), 0.0, 1.0), 5.0);
			
			fresnel3 = mix(baseReflectance, vec3(1.0), fresnel);
			#if MATERIAL_FORMAT == 1
			if (f0 >= 0.9 && f0 < 1.0) {
				baseReflectance = GetMetalCol(f0);
				fresnel3 = ComplexFresnel(pow(fresnel, 0.2), f0);
				#ifdef ALBEDO_METAL
				fresnel3 *= rawAlbedo;
				#endif
			}
			#endif
			
			float aoSquared = ao * ao ;
			shadow *= aoSquared; fresnel3 *= aoSquared;
			albedo.rgb = albedo.rgb * (1.0 - fresnel3 * smoothness * smoothness * (1.0 - metalness));

			#if (defined OVERWORLD || defined END) && (defined ADVANCED_MATERIALS || defined SPECULAR_HIGHLIGHT_ROUGH)
			vec3 specularColor = GetSpecularColor(lightmap.y, metalness, baseReflectance);
			
			albedo.rgb += GetSpecularHighlight(newNormal, viewPos, lightVec, smoothness, baseReflectance,
										   specularColor, shadow * vanillaDiffuse, color.a);
			#endif
			
			#if defined ADVANCED_MATERIALS && defined REFLECTION_SPECULAR && defined REFLECTION_ROUGH
			normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, smoothness);
			newNormal = clamp(normalize(normalMap * tbnMatrix), vec3(-1.0), vec3(1.0));
			#endif
			#endif
			
			if(blockEntityId == 10250) albedo.a = sqrt(albedo.a);

			#ifdef SHOW_DARK_ZONES
			if (vanillaDiffuse > 0.99) {
				albedo.rgb=showDarkZones(albedo.rgb);
			}
			#endif
			
			
		} else discard;
		
		
		/* DRAWBUFFERS:0 */
		gl_FragData[0] = albedo;
		
		#if defined ADVANCED_MATERIALS && defined REFLECTION_SPECULAR
		/* DRAWBUFFERS:0367 */
		gl_FragData[1] = vec4(smoothness, skyOcclusion, 0.0, 1.0);
		gl_FragData[2] = vec4(EncodeNormal(newNormal), float(gl_FragCoord.z < 1.0), 1.0);
		gl_FragData[3] = vec4(fresnel3, 1.0);
		#endif
	}
	
	#endif
	
	//Vertex Shader/////////////////////////////////////////////////////////////////////////////////////
	#ifdef VSH
	
	//Uniforms//
	uniform int worldTime;
	
	uniform float frameTimeCounter;
	uniform float timeAngle;
	
	uniform vec3 cameraPosition;
	
	uniform mat4 gbufferModelView,gbufferModelViewInverse;
	
	#if AA > 0
	uniform int frameCounter;
	
	uniform float viewWidth,viewHeight;
	#endif
	
	//Attributes//
	
	#ifdef ADVANCED_MATERIALS
	attribute vec4 mc_midTexCoord;
	attribute vec4 at_tangent;
	#endif
	
	//Common Variables//

	//Includes//
	#if AA > 0
	#include "/lib/util/jitter.glsl"
	#endif
	
	//Program//
	void main(){
		texCoord=(gl_TextureMatrix[0]*gl_MultiTexCoord0).xy;
		
		lmCoord=(gl_TextureMatrix[1]*gl_MultiTexCoord1).xy;

		#if MC_VERSION >= 11700
		fullLightmap = 0.0;
		if (lmCoord.x > 0.96) fullLightmap = 1.0;
		#endif

		lmCoord = clamp((lmCoord - 0.03125) * 1.06667, vec2(0.0), vec2(0.9333, 1.0));
		
		normal=normalize(gl_NormalMatrix*gl_Normal);
		
		#ifdef ADVANCED_MATERIALS
		binormal=normalize(gl_NormalMatrix*cross(at_tangent.xyz,gl_Normal.xyz)*at_tangent.w);
		tangent=normalize(gl_NormalMatrix*at_tangent.xyz);
		
		mat3 tbnMatrix=mat3(tangent.x,binormal.x,normal.x,
							tangent.y,binormal.y,normal.y,
							tangent.z,binormal.z,normal.z);
		
		viewVector=tbnMatrix*(gl_ModelViewMatrix*gl_Vertex).xyz;

		dist=length(gl_ModelViewMatrix*gl_Vertex);
		
		vec2 midCoord=(gl_TextureMatrix[0]*mc_midTexCoord).st;
		vec2 texMinMidCoord=texCoord-midCoord;
		
		vTexCoordAM.pq=abs(texMinMidCoord)*2;
		vTexCoordAM.st=min(texCoord,midCoord-texMinMidCoord);
		
		vTexCoord.xy=sign(texMinMidCoord) * 0.5 + 0.5;
		#endif
		
		color=gl_Color;
		
		const vec2 sunRotationData=vec2(cos(sunPathRotation*.01745329251994),-sin(sunPathRotation*.01745329251994));
		float ang=fract(timeAngle-.25);
		ang=(ang+(cos(ang*3.14159265358979)*-.5+.5-ang)/3.)*6.28318530717959;
		sunVec=normalize((gbufferModelView*vec4(vec3(-sin(ang),cos(ang)*sunRotationData)*2000.,1.)).xyz);
		
		upVec=normalize(gbufferModelView[1].xyz);

		#ifdef NEW_END_PORTAL
		eastVec = normalize(gbufferModelView[0].xyz);
		#endif

		gl_Position = ftransform();
		
		#if AA > 0
		gl_Position.xy=TAAJitter(gl_Position.xy,gl_Position.w);
		#endif
	}
	
	#endif