Skip to content

Instantly share code, notes, and snippets.

@williammanco
Last active January 21, 2020 13:15
Show Gist options
  • Select an option

  • Save williammanco/94af77cc442d796211fec6c743fd7a5b to your computer and use it in GitHub Desktop.

Select an option

Save williammanco/94af77cc442d796211fec6c743fd7a5b to your computer and use it in GitHub Desktop.
Calc normal from vertex
//https://observablehq.com/@k9/calculating-normals-for-distorted-vertices
varying vec3 vNormal;
uniform float offset;
float tangentFactor = 0.1;
${perlin()}
// http://lolengine.net/blog/2013/09/21/picking-orthogonal-vector-combing-coconuts
vec3 orthogonal(vec3 v) {
return normalize(abs(v.x) > abs(v.z) ? vec3(-v.y, v.x, 0.0)
: vec3(0.0, -v.z, v.y));
}
// Any function can go here to distort p
vec3 distorted(vec3 p) {
return p + vec3(
cnoise(p / 3.0 + offset),
cnoise(p / 4.0 + offset + 1.0),
cnoise(p / 5.0 + offset + 2.0)
);
}
void main() {
vec3 distortedPosition = distorted(position);
vec3 tangent1 = orthogonal(normal);
vec3 tangent2 = normalize(cross(normal, tangent1));
vec3 nearby1 = position + tangent1 * tangentFactor;
vec3 nearby2 = position + tangent2 * tangentFactor;
vec3 distorted1 = distorted(nearby1);
vec3 distorted2 = distorted(nearby2);
vec4 mvPosition = modelViewMatrix * vec4(distortedPosition, 1.0);
gl_Position = projectionMatrix * mvPosition;
vNormal = normalize(cross(distorted1 - distortedPosition, distorted2 - distortedPosition));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment