I’m trying hard to figure out shaders, and I’ve been reading this tutorial, which seems pretty good and easy to understand. I’ve followed the code in it as closely as I can, and while I do see a triangle, it’s all a solid red, rather than the range of colors I specified in my color array. Here’s my actual code:
In the init section:
float[] vertices = {
-0.8f, -0.8f, 0.0f, 1.0f,
0.0f, 0.8f, 0.0f, 1.0f,
0.8f, -0.8f, 0.0f, 1.0f
};
float[] colors = {
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f
};
gl.GenVertexArrays(1, vaoId);
gl.BindVertexArray(vaoId[0]);
gl.GenBuffers(1, vertexBufferId);
gl.BindBuffer(OpenGL.GL_ARRAY_BUFFER, vertexBufferId[0]);
unsafe
{
fixed (float* verts = vertices)
{
var ptr = new IntPtr(verts);
gl.BufferData(OpenGL.GL_ARRAY_BUFFER, vertices.Length * sizeof(float), ptr, OpenGL.GL_STATIC_DRAW);
}
}
gl.VertexAttribPointer(0, 3, OpenGL.GL_FLOAT, false, 0, new IntPtr(0));
gl.EnableVertexAttribArray(0);
gl.GenBuffers(1, colorBufferId);
gl.BindBuffer(OpenGL.GL_ARRAY_BUFFER, colorBufferId[0]);
unsafe
{
fixed (float* colr = colors)
{
var ptr = new IntPtr(colr);
gl.BufferData(OpenGL.GL_ARRAY_BUFFER, colors.Length * sizeof(float), ptr, OpenGL.GL_STATIC_DRAW);
}
}
gl.VertexAttribPointer(1, 3, OpenGL.GL_FLOAT, false, 0, new IntPtr(0));
gl.EnableVertexAttribArray(1);
vertexShaderId = gl.CreateShader(OpenGL.GL_VERTEX_SHADER);
fragmentShaderId = gl.CreateShader(OpenGL.GL_FRAGMENT_SHADER);
string[] vertString = File.ReadAllLines("vertShader.vert");
string[] fragString = File.ReadAllLines("fragShader.frag");
unsafe
{
gl.ShaderSource(vertexShaderId, 1, vertString, null);
gl.ShaderSource(fragmentShaderId, 1, fragString, null);
}
gl.CompileShader(vertexShaderId);
gl.CompileShader(fragmentShaderId);
programId = gl.CreateProgram();
gl.AttachShader(programId, vertexShaderId);
gl.AttachShader(programId, fragmentShaderId);
gl.LinkProgram(programId);
gl.UseProgram(programId);
gl.ClearColor(0, 0, 0, 0);
And in the Draw section:
gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);
// Load the identity matrix.
gl.LoadIdentity();
gl.BindBuffer(OpenGL.GL_ARRAY_BUFFER, vertexBufferId[0]);
gl.BindBuffer(OpenGL.GL_ARRAY_BUFFER, colorBufferId[0]);
gl.DrawArrays(OpenGL.GL_TRIANGLES, 0, 3);
This is vertShader.vert:
#version 400
layout(location=0) in vec4 in_Position;
layout(location=1) in vec4 in_Color;
out vec4 ex_Color;
void main(void)
{
gl_Position = in_Position;
ex_Color = in_Color;
}
and fragShader.frag:
#version 400
in vec4 ex_Color;
out vec4 out_Color;
void main(void)
{
out_Color = ex_Color;
}
I apologize for the C#-ness of the code (I’m using SharpGL as a wrapper), but it’s still understandable. As far as I can tell I’m passing everything correctly, but I’ve never done this before and I wouldn’t know if I’m making some elemental error. What’s wrong with my setup?