Dot product of tow vec3 vectors does not work

This is the fragment shader in which the dot product always returns zero.

#version 300 es

precision highp float;

out vec4 FragColor;

struct VS_OUT {
    vec3 FragPos;
    vec3 Normal;
    vec2 TexCoords;
};

in VS_OUT fs_in;
uniform sampler2D TexSample1;
uniform sampler2D TexSample2;  
uniform vec3 lightPos;
uniform vec4 lightColor;
uniform vec3 viewPos;
bool blinn = true;

highp float dotProduct(highp vec3 item1, highp vec3 item2);

void main()
{           
    vec3 color = mix(texture(TexSample1, fs_in.TexCoords), texture(TexSample2, fs_in.TexCoords), 0.3).xyz;
    // Ambient
    vec3 ambient = 0.2 * color;
    // Diffuse
    vec3 lightDir = normalize(lightPos - fs_in.FragPos);
    vec3 normal = normalize(fs_in.Normal);
    float diff = dotProduct(lightDir, normal);
    vec3 diffuse = color * diff;
    // Specular
    vec3 viewDir = normalize(viewPos - fs_in.FragPos);
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = 0.0;
    if(blinn)
    {
        vec3 halfwayDir = normalize(lightDir + viewDir);  
        spec = pow(dotProduct(normal, halfwayDir), 32.0);
    }
    else
    {
        vec3 reflectDir = reflect(-lightDir, normal);
        spec = pow(max(dot(viewDir, reflectDir), 0.0), 32.0);
    }
    vec4 coloring = lightColor;
    vec3 specular = vec3(0.2) * spec; // assuming bright white light color
    //FragColor = vec4(ambient + diffuse + specular, 1.0) * coloring;
    FragColor = vec4(color, 1.0);
}

highp float dotProduct(vec3 item1, vec3 item2)
{
    highp float tmpitem1 = item1.x * item2.x;
    highp float tmpitem2 = item1.y * item2.y;
    highp float tmpitem3 = item1.z * item2.z;
    highp float tempval =  tmpitem1 + tmpitem2 + tmpitem3;
    
    return clamp(tempval, 0.0, 1.0);
}

This is the vertex shader:

#version 300 es

precision highp float;

struct VS_OUT {
    vec3 FragPos;
    vec3 Normal;
    vec2 TexCoords;
};

layout (location = 0) in vec3 aPos;   // the position variable
layout (location = 1) in vec3 aNorm;
layout (location = 2) in vec2 aTex;

out VS_OUT fs_in;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

vec4 posVal;
void main()
{
    fs_in.Normal = (model * vec4(aNorm, 1.0)).xyz;
    fs_in.TexCoords = aTex;
    posVal = projection * view * model * vec4(aPos, 1.0);
    gl_Position = posVal;
    fs_in.FragPos = (model * vec4(aPos, 1.0)).xyz;
}

Are you referring to the dot product computed by the built-in dot function or your own dotProduct function? The latter clamps the result to [0,1], so if the dot product is negative it will return zero.

Also:

For a direction, the W component should be zero; you don’t want it to be affected by any translation. So:

fs_in.Normal = (model * vec4(aNorm, 0.0)).xyz;

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.