Browse Source

added cofactor function to shaderlib.sh

It is useful to transform normals.
attilaz 6 years ago
parent
commit
652cbac63d
1 changed files with 18 additions and 0 deletions
  1. 18 0
      examples/common/shaderlib.sh

+ 18 - 0
examples/common/shaderlib.sh

@@ -392,4 +392,22 @@ vec2 texture2DBc5(sampler2D _sampler, vec2 _uv)
 #endif
 #endif
 }
 }
 
 
+mat3 cofactor( mat4 _m )
+{
+	// Reference:
+	// Cofactor of matrix. Use to transform normals. The code assumes the last column of _m is [0,0,0,1].
+	// https://www.shadertoy.com/view/3s33zj
+	// https://github.com/graphitemaster/normals_revisited
+    return mat3( 
+     _m[1][1]*_m[2][2]-_m[1][2]*_m[2][1],
+     _m[1][2]*_m[2][0]-_m[1][0]*_m[2][2],
+     _m[1][0]*_m[2][1]-_m[1][1]*_m[2][0],
+     _m[0][2]*_m[2][1]-_m[0][1]*_m[2][2],
+	 _m[0][0]*_m[2][2]-_m[0][2]*_m[2][0],
+     _m[0][1]*_m[2][0]-_m[0][0]*_m[2][1],
+     _m[0][1]*_m[1][2]-_m[0][2]*_m[1][1],
+     _m[0][2]*_m[1][0]-_m[0][0]*_m[1][2],
+     _m[0][0]*_m[1][1]-_m[0][1]*_m[1][0] );
+}
+
 #endif // __SHADERLIB_SH__
 #endif // __SHADERLIB_SH__