

#include "/lib/raytracing.glsl"

float avgOf(vec3 a)             { return (a.x + a.y + a.z) * rcp(3.0); }
float maxOf(vec3 a)         { return max(a.x, max(a.y, a.z)); }
const float sqrt2 = sqrt(2);

vec3 getEmissionCol(float emission, vec3 albedo, float curve, int id) {
	if(isTorch(id)) {
		return torchLight*EMISSIVE_BRIGHTNESS*0.5;
	} else if(isSoulLight(id)) {
		return soulLight*EMISSIVE_BRIGHTNESS*0.5;
	} else {
		// albedo  = max(albedo, 1e-8);
		// float albedoLum = mix(avgOf(albedo), maxOf(albedo), 0.71);
		// 	albedoLum   = clamp01(albedoLum * sqrt2);

		// float emitterLum = clamp01(mix(pow2(albedoLum), sqrt(maxOf(albedo)), albedoLum) * sqrt2);

		// albedo  = mix(pow2(normalize(albedo)), normalize(albedo), sqrt(emitterLum)) * emitterLum;

		// return albedo * EMISSIVE_BRIGHTNESS * 2.0;
		float norm_factor = mix(max(LuminanceAP1(albedo), 1e-4), 1.0, 0.3);
		return pow(albedo*rcp(norm_factor), vec3(curve))*0.5*EMISSIVE_BRIGHTNESS * emission;
	}
}

vec3 directLight(vec3 p, vec3 n) {
	#if (!defined(NETHER) && !defined(ENDER))

	//Convert positions to view space
	p = VoxelSpaceToSceneSpace(p);
	p -= gbufferModelViewInverse[3].xyz;
	p = worldToView(p);

	n = worldToView(n);

	vec3 sunDir = normalize(lightDirView);

	p += 0.001 * n;

	vec3 sunShadow = shadowFast1Coloured(p, n);
	
	return sunShadow;
	#else
	return vec3(0.0);
	#endif
}

vec3 directLightPCSS(vec3 p, vec3 n, vec2 dither, out vec3 visibility, bool isPlant) {

	#if (!defined(NETHER) && !defined(ENDER))

	//Convert positions to view space
	p = VoxelSpaceToSceneSpace(p);
	p -= gbufferModelViewInverse[3].xyz;
	p = worldToView(p);

	n = worldToView(n);

	vec3 sunDir = normalize(lightDirView);

	// float cosTheta = dot(sunDir, n);
	p += 0.001 * n;
	visibility = shadow(shadowtex1, p, n, PCSS_SAMPLES, dither, isPlant);
	
	return visibility;
	#else
	visibility = vec3(0.0);
	return vec3(0.0);
	#endif
}


