Question

I'm currently try to build a test scene with shaders. This is my code.

vertexArray = GL.GenVertexArray();
GL.BindVertexArray(vertexArray);

float[] Vertices = new float[] {
    -1.0f, -1.0f, 0.0f,
    1.0f, -1.0f, 0.0f,
    0.0f,  1.0f, 0.0f,
};

float[] Colors = new float[] {
    1.0f, 1.0f, 0.0f, 1.0f,
    1.0f, 1.0f, 0.0f, 1.0f,
   0.0f,  1.0f, 0.0f, 1.0f
};

vertexBuffer = GL.GenBuffer();
colorBuffer = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBuffer);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(sizeof(float) * Vertices.Length), Vertices, BufferUsageHint.StaticDraw);

GL.BindBuffer(BufferTarget.ArrayBuffer, colorBuffer);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(sizeof(float) * Colors.Length), Colors, BufferUsageHint.StaticDraw);

//Loading shaders...

My render loop:

GL.UseProgram(shaderProgram);

GL.EnableVertexAttribArray(0);
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBuffer);
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, 0);
GL.BindBuffer(BufferTarget.ArrayBuffer, colorBuffer);
GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 0, 0);

GL.DrawArrays(PrimitiveType.Triangles, 0, 3);

GL.DisableVertexAttribArray(0);

GL.UseProgram(0);

I use this vertex shader:

#version 330 core
layout(location = 0) in vec3 position;
layout(location = 1) in vec4 color;

out vec4 vColor;

void main()
{
  gl_Position = vec4(position, 1.0);
  vColor = color;
}

And this fragment shader:

#version 330 core
in vec4 vColor;
out vec4 fColor;

void main(void)
{
  fColor = vColor;
}

When i run it, i get the triangle, but it is black. I want the colors, like i have it in my Colors array. When i change the vColor in the fragment shader to vec4(1,0,0,1), i get a red triange. So it must be a problem between the both shader, maybe the vertex shader don't pass the color to the fragment shader...

What am i doing wrong? How can i pass the colors correctly?

Was it helpful?

Solution

I see two problems. First, you're never enabling the attribute for the color. Add a call to enable attribute 1, equivalent to what you did for attribute 0:

GL.EnableVertexAttribArray(1);

Your colors have 4 components, but you're passing 3 as the second argument to VertexAttribPointer when setting up the colors attribute. Change it to:

GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, 0, 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top