matthew-r
12/11/2017 - 4:00 AM

procedurally generating normals for a displaced surface

from Mike Walczyk:

someone just posted this snippet in the cinder slack channel - a way of procedurally generating normals for a displaced surface, directly inside of the vertex shader

mat3 getTangentBasis( in vec3 tangent_y )
{
    vec3 UpVector = vec3(0,1,0);
    vec3 tangent_x = normalize( cross( UpVector, tangent_y ) );
    vec3 tangent_z = cross( tangent_y, tangent_x );
    return mat3( tangent_x, tangent_y, tangent_z );
}

vec3 applyDeformation( in vec3 pos, in vec3 norm )
{
// .. displace vertex
}

vec3 computeVertexNormal( in vec3 pos, in vec3 norm )
{
    float offset = 0.1;
    mat3 basis = getTangentBasis( norm );
    vec3 xv = offset * basis[0];
    vec3 zv = offset * basis[2];
  
    vec3 x0 = applyDeformation( pos.xyz - xv, norm ).xyz;
    vec3 x1 = applyDeformation( pos.xyz + xv, norm ).xyz;
    vec3 z0 = applyDeformation( pos.xyz - zv, norm ).xyz;
    vec3 z1 = applyDeformation( pos.xyz + zv, norm ).xyz;
    return cross( x1 - x0, z1 - z0 );
}