Skip to content

Instantly share code, notes, and snippets.

@patriciogonzalezvivo
Created July 1, 2014 19:28
Show Gist options
  • Save patriciogonzalezvivo/20263fe85d52705e4530 to your computer and use it in GitHub Desktop.
Save patriciogonzalezvivo/20263fe85d52705e4530 to your computer and use it in GitHub Desktop.
GLSL Triplanar Texture Mapping

From http://gamedevelopment.tutsplus.com/articles/use-tri-planar-texture-mapping-for-better-terrain--gamedev-13821

Vertex Shader

varying vec4 vPos;
varying vec3 vNormal;

void main(){

	...
	vPos =  vec4( gl_Vertex.xyz, 1.0 );
	vNormal = normalize(gl_NormalMatrix * gl_Normal);
	...
}

Fragment Shader

uniform sampler2D tNormal;
varying vec3 vNormal;
varying vec3 vEye;

vec3 getTriPlanarBlend(vec3 _wNorm){
	// in wNorm is the world-space normal of the fragment
	vec3 blending = abs( _wNorm );
	blending = normalize(max(blending, 0.00001)); // Force weights to sum to 1.0
	float b = (blending.x + blending.y + blending.z);
	blending /= vec3(b, b, b);
	return blending;
}

void main(){
	vec3 blending = getTriPlanarBlend(vNormal);
	vec3 xaxis = texture2D( tNormal, vPos.yz * normalRepeat).rgb;
	vec3 yaxis = texture2D( tNormal, vPos.xz * normalRepeat).rgb;
	vec3 zaxis = texture2D( tNormal, vPos.xy * normalRepeat).rgb;
	vec3 normalTex = xaxis * blending.x + xaxis * blending.y + zaxis * blending.z;
	normalTex = normalTex * 2.0 - 1.0;
	normalTex.xy *= normalScale;
	normalTex = normalize( normalTex );

	vec3 T = vec3(0.,1.,0.);
  	vec3 BT = normalize( cross( vNormal, T ) * 1.0 );

  	mat3 tsb = mat3( normalize( T ), normalize( BT ), normalize( vNormal ) );
  	vec3 N = tsb * normalTex;
}

@richardba
Copy link

richardba commented Apr 9, 2019

@patriciogonzalezvivo where does normalRepeat and normalScale come from?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment