Search code examples
c#openglvertex-buffer

Why do i get gradient colored lines when using vertexbuffer?


I'm making something like a CAD/CAM software using OpenGL.
at first I simply used glBegin and glEnd, it works fine but it gets slow when there are lot of vertices, so I did my search and found there is something called vertexbuffer.
so I made a simple program to test it it's written in c# and sharpgl

//create a new buffer
gl.BindBuffer(OpenGL.GL_ARRAY_BUFFER, vertexId);
gl.BufferData(OpenGL.GL_ARRAY_BUFFER, vertexSize + colorSize, new IntPtr(0),OpenGL.GL_STREAM_DRAW);
gl.VertexPointer(2, OpenGL.GL_FLOAT, 0, new IntPtr(0));
gl.ColorPointer(3, OpenGL.GL_UNSIGNED_BYTE, 0, new IntPtr(vertexSize));
//update vertex buffer
public int UpdateVertexAt(float[] segments,int offset)
    {
        int len = segments.Length * sizeof(float);
        unsafe
        {
            fixed(float * p = segments)
            {
                IntPtr ptr = new IntPtr(p);
                gl.BufferSubData(OpenGL.GL_ARRAY_BUFFER, offset, len, ptr);
            }
        }
        c += segments.Length / 2;
        return len;
    }
//update color
 public int UpdateColorAt(byte[] rgb, int offset)
    {
       // gl.BindBuffer(OpenGL.GL_ARRAY_BUFFER, colorId);
        unsafe
        {
            fixed (byte* p = rgb)
            {
                IntPtr ptr = new IntPtr(p);
                gl.BufferSubData(OpenGL.GL_ARRAY_BUFFER, offset, rgb.Length, ptr);
            }
        }
        return rgb.Length;
    }
//draw scene
  public void Flush()
    {
        gl.EnableClientState(OpenGL.GL_VERTEX_ARRAY);
        gl.EnableClientState(OpenGL.GL_COLOR_ARRAY);
        gl.DrawArrays(OpenGL.GL_LINES, 0, 2 * c);
        gl.DisableClientState(OpenGL.GL_COLOR_ARRAY);
        gl.DisableClientState(OpenGL.GL_VERTEX_ARRAY);
    }

the problem is I start drawing lines it looks werid and not in the right place, and when I draw the first line it dosent show but when I draw the sconed line and apperes like the

enter image description here

I checked the vertices and color using gl.GetBufferSubData and every thing looks right, but when use gl.ColorPointer(3, OpenGL.GL_UNSIGNED_BYTE, 0, new IntPtr(0)), the lines are drawn in place and every thing is just fine except the color, and I think it's because its reading the vertices as color

enter image description here

so what I'm doing wrong here ?


Solution

  • i found the problem, I was using 1 color for the start and the end point of the line, that what was causing the gradient color