Implementing Triplanar Mapping in ThreeJs

I’m currently trying to implement Triplanar mapping in ThreeJs. Below are the modifications I made in the normal_fragment_maps .

#ifdef USE_NORMALMAP_OBJECTSPACE

  #ifdef USE_TRIPLANAR_MAPPING
    vec3 normalTexX = texture2D(normalMap, tx).xyz * weights.x * 2.0 - 1.0;
    vec3 normalTexY = texture2D(normalMap, ty).xyz * weights.y * 2.0 - 1.0;
    vec3 normalTexZ = texture2D(normalMap, tz).xyz * weights.z * 2.0 - 1.0;
    normal = normalize(normalTexX + normalTexY + normalTexZ);
  #elif
	  normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals
  #endif

	#ifdef FLIP_SIDED
		normal = - normal;
	#endif

	#ifdef DOUBLE_SIDED
		normal = normal * faceDirection;
	#endif

	normal = normalize( normalMatrix * normal );
  // gl_FragColor = vec4( packNormalToRGB( normal ), 1.0);
  // return;

#elif defined( USE_NORMALMAP_TANGENTSPACE )

  #ifdef USE_TRIPLANAR_MAPPING
    vec3 mapNX = texture2D(normalMap, tx).xyz * weights.x * 2.0 - 1.0;
    vec3 mapNY = texture2D(normalMap, ty).xyz * weights.y * 2.0 - 1.0;
    vec3 mapNZ = texture2D(normalMap, tz).xyz * weights.z * 2.0 - 1.0;
    vec3 mapN = normalize(mapNX + mapNY + mapNZ);
    mapN.xy *= normalScale;
    normal = normalize(tbn * mapN);
  #elif
    vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
    mapN.xy *= normalScale;
    normal = normalize( tbn * mapN );
  #endif

#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif

gl_FragColor = vec4( packNormalToRGB( normal ), 1.0);
return;

It seems that all models enter the USE_NORMALMAP_TANGENTSPACE code segment. However, some models display the correct textures while others do not. What could be causing this discrepancy?

Before using normal = normalize( tbn * mapN ) , everything seems to be working fine, with each model displaying textures similar to the distribution of the normal maps. However, after applying the TBN transformation, issues arise: the normal textures disappear on some models. I’m wondering what might be causing this? How should I modify the code to address this issue?

This is the normal map I use:


This is the correct normal:

This is the wrong normal:

I think I’ve found the reason for the issue. It seems that I need to modify the way tbn is calculated in normal_fragment_begin . The calculation of tbn involves vNormalMapUV , and models without UVs are using default values.

2 Likes