
#ifndef MAPPING_TRIPLANAR_H
#define MAPPING_TRIPLANAR_H

vec4 mapping_triplanar(sampler2D smpl, vec3 p, vec3 n, vec3 scale)
{
	vec3 coords = p;
	vec3 blending = abs(n);
	blending = normalize(max(blending, 0.00001)); // Force weights to sum to 1.0
	float b = (blending.x + blending.y + blending.z);
	blending /= vec3(b);

	vec4 xaxis = texture(smpl, coords.yz * scale.yz);
	vec4 yaxis = texture(smpl, coords.xz * scale.xz);
	vec4 zaxis = texture(smpl, coords.xy * scale.xy);
	vec4 tex = xaxis * blending.x + yaxis * blending.y + zaxis * blending.z;
	return tex;
}

vec3 mapping_triplanar_normal(sampler2D smpl, vec3 p, vec3 n, vec3 scale)
{
	vec3 coords = p;
	vec3 blending = abs(n);
	blending = normalize(max(blending, 0.00001)); // Force weights to sum to 1.0
	float b = (blending.x + blending.y + blending.z);
	blending /= vec3(b);

	vec3 axis_sign = sign(n);

	vec3 xaxis = texture(smpl, coords.zy * scale.zy).rgb * 2.0 - 1.0;
	vec3 yaxis = texture(smpl, coords.xz * scale.xz).rgb * 2.0 - 1.0;
	vec3 zaxis = texture(smpl, coords.xy * scale.xy).rgb * 2.0 - 1.0;
	
	xaxis.z *= axis_sign.x;
	yaxis.z *= axis_sign.y;
	zaxis.z *= axis_sign.z;

	vec3 tex = normalize(xaxis.zyx * blending.x + yaxis.xzy * blending.y + zaxis.xyz * blending.z);
	return tex;
}

#endif