GLSL Fresnel effect makes half of my sphere white

163 Views Asked by At

Here in app using r3f, in my sphere object I use the fresnel effect in my vertex shader, but the problem is that when the sphere is rotated the other side is pure white like in the example bellow ↓ The bug

Here is my code:

Vertex.glsl: (cnoise funciton taken from here)

uniform float uTime;

varying vec3 vPosition;
varying vec3 vNormal;
varying vec2 vUv;
varying float vDisplacement;

// cnoise function...

void main() {
  vPosition = position;
  vNormal = normal;
  vUv = uv;

  float customSpeed = uTime;
  customSpeed = customSpeed * 1.15;

  vec3 animatedNormal = normal;
  animatedNormal = animatedNormal * 2.;
  animatedNormal.x += customSpeed / 2.5;
  animatedNormal.y += customSpeed / 3.;
  animatedNormal.z += customSpeed / 4.;

  vDisplacement = cnoise2(vec4(animatedNormal, 1.), vec4(10.)) / 7.;

  vec3 newPosition = position + normal * vDisplacement;
  vec4 modelViewMatrixPosition = modelViewMatrix * vec4(newPosition, 1.0);
  vec4 projectedPosition = projectionMatrix * modelViewMatrixPosition;
  gl_Position = projectedPosition;
}

Fragment.glsl:

uniform sampler2D uSky;

varying float vDisplacement;

varying highp vec3 vPosition;
varying highp vec3 vNormal;

#define PI 3.14159265359

void main() {
  float phi = acos(vNormal.y);

  float angle = atan(vNormal.x, vNormal.z);

  vec2 fakeUv = vec2((angle + PI) / (2. * PI), phi / PI);

  float fresnel = dot(normalize(cameraPosition - vPosition), normalize(vNormal));
  vec4 texture = texture2D(uSky, fakeUv / 3. + vDisplacement);

  gl_FragColor = vec4(mix(vec3(1.), texture.rgb, fresnel * 1.2), 1.0);
  // gl_FragColor = texture; // if we only use this it works fine

}

Sphere.tsx:

// the jsx for the sphere
      <mesh ref={ref}>
        <icosahedronGeometry args={[2, 200]} />
        <shaderMaterial
          ref={shaderMaterialRef}
          vertexShader={vertex}
          fragmentShader={fragment}
        />
      </mesh>

// how I am rotating it
      useFrame(() => {
          ref.current.rotation.y = 30;
      }, [])

What could be going wrong here?

0

There are 0 best solutions below