Webgl - How to make Specular Light not change size

89 views Asked by At

I am trying to implement specular lighting (thats coming from the front) but the light is always changing size in an unnatural way. How do I fix this? I hardcoded viewerPos to test. I'm using a halfway vector "shortcut" so I have to calculate less things as explained here: https://webglfundamentals.org/webgl/lessons/webgl-3d-lighting-point.html

Video with my lighting implemented: https://streamable.com/j95bz7

// Vertex shader program

  const vsSource = `
    attribute vec4 aVertexPosition;
    attribute vec3 aVertexNormal;
    attribute vec2 aTextureCoord;

    uniform mat4 uNormalMatrix;
    uniform mat4 uModelViewMatrix;
    uniform mat4 uProjectionMatrix;
    uniform highp vec3 uViewPos;

    varying highp vec2 vTextureCoord;
    varying highp vec4 vNormal;
    varying highp mat4 vModelViewMatrix;
    varying highp vec3 vPos;

    void main(void) {
      gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
      vTextureCoord = aTextureCoord;        //Textura
      vModelViewMatrix = uModelViewMatrix;    
      vPos = (uModelViewMatrix * aVertexPosition).xyz;

      vNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);

    }
  `;

  // Fragment shader program

  const fsSource = `
    varying highp vec2 vTextureCoord;
    varying highp vec4 vNormal;
    varying highp mat4 vModelViewMatrix;
    varying highp vec3 vPos;


    uniform sampler2D uSampler;

    void main(void) {
      // Apply lighting effect
      
      highp vec4 texelColor = texture2D(uSampler, vTextureCoord);

      //Luz Ambiente
      highp vec3 ambientLight = 0.3 * vec3(1.0, 1.0, 1.0);

      //Luz Difusa
      highp vec3 directionalLightColor = vec3(1, 1, 1);
      highp vec3 directionalVector = vec3(0.0, 0.0, 1.0);
      highp float directional = max(dot(vNormal.xyz, normalize(directionalVector)), 0.0);

      //Luz Especular
      highp vec3 viewerPos = vec3(0, 0, -6); //NOTA: PASSAR PARA SHADERS, NAO DAR HARDCODE
      highp vec3 surfaceToLightDirection = (-1.0 * directionalVector);
      highp vec3 surfaceToViewDirection = (vPos - viewerPos);
      highp vec3 halfVector = normalize(surfaceToLightDirection + surfaceToViewDirection);
      highp float specular = max(dot(vNormal.xyz, halfVector), 0.0);



      highp vec3 vLighting = ambientLight;// + (directionalLightColor * directional);

      gl_FragColor = vec4(texelColor.rgb * vLighting + (specular * 0.5), texelColor.a);
    }
  `;
0

There are 0 answers