Search code examples
segmentation-faultglslopengl-3dot-product

glsl dot function indirectly causing a segmentation fault in program


Heres my vertex shader code:

#version 330

layout(location = 0) in vec3 vertex_position;
layout(location = 0) in vec3 vertex_normal;

//model space
uniform vec3 toLight;

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

smooth out vec3 color;

void main()
{
  gl_Position = projection * view * model * vec4(vertex_position, 1.0f);
  
  vec3 normal = normalize(vertex_normal);
  
  float intensity = dot(normal, toLight);
  intensity = clamp(intensity, 0, 1);
  
  color = vec3(intensity);
}

In this code I am trying to calculate lighting using the tutorial at Learning Modern 3D Graphics Programming site. Which is a great book by the way, however the code here is basically identical to the listed code with a couple of names changed, however through the some experimentation, I have discovered something very peculiar. The segmentation fault occurs on the

color = vec3(intensity);

line, I know that because removing that line causes the program to run normally, (except without lighting of course)

However when I replace the line

float intensity = dot(normal, toLight);

with:

float intensity = 3.14159;

It clamps to 1.0f and everything works fine, the cube is white, same happens if I put a negative number: the number is clamped to zero and the cube is black...

So this is strange, here's the facts:

  • The segmentation fault disappears when removing the line that sets the output vector to the color requested.
  • The segmentation fault also disappears when removing the calculation of the dot product
  • When the intensity is a constant float, everything works fine.
  • setting the color to anything not involving the intensity works fine.
  • EDIT: found some interesting info, when setting a variable other than the color variable using the intensity variable works fine, for example vec3 temp = vec3(intensity); doesn't cause a segfault, however setting color to something that is not related to the intensity variable works fine also color = vec3(1.0f); although, if I were to set color to temp it would crash too, this is very strange.

Any suggestions are greatly appreciated. Thanks

Also, I would include my opengl, c++ code, but I don't think it's necessary, correct me if I'm wrong.


Solution

  • Oh, god! I made a big mistake, right here:

    layout(location = 0) in vec3 vertex_position;
    layout(location = 0) in vec3 vertex_normal;
    

    notice how vertex_position and vertex_normal have the same location, I didn't either. Setting the vertex_normal location to 1 fixed everything, sorry I wasted most of your time, but thanks to all of you for suggestions and to Tim who got me to realize that a segfault was occurring with the normal, leading me to the top of the source, thanks all of you just the same... =D