Search code examples
three.jsshadermeshfragment-shader

MeshNormalMaterial color


In default MeshNormalMaterial example, the color of cube wall is changing because it uses this THREE.ShaderLib[ 'normal' ] shader. This shader sets gl_FragColor by this gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );. Can anyone explain me this formula? which vector of cube is normalized? Are there any other factors that have impact on color?

http://www.smartjava.org/ltjs/chapter-04/04-mesh-normal-material.html - example

Sorry for stupid question, I'm new in three.js.


Solution

  • The MeshNormalMaterial basically colors an object based on its normals. So in the equation you gave vNormal is the vertex normal of that fragment. Think of it as translating the (x,y,z) vector of a normal to an (r,g,b) color. The transformation between the two spaces is given by that formula. if you had

    gl_FragColor = vec4( vNormal, opacity );
    

    then the final fragment color (i.e. the r,g,b,a values) would only depend on the normal.

    In the equation you posted there is a constant term and half the normalized normal.