How to setup a color index array?

In the following code , I’m trying to draw the 3 Cartesian axis with 3 colors (red,blue,green) , the lines are drawing correctly , but the colors is incorrect . So how should I setup the color index array ? Many thanks!

auto draw_axis = [] {
    struct {
      float ary[3];
    } axis[] = {
      0.0f,  0.0f, 0.0f,
      5.0f,  0.0f, 0.0f,
      0.0f,  5.0f, 0.0f,
      0.0f,  0.0f, 5.0f,
    }, colors[] = {
      1.0f,0.0f,0.0f,
      0.0f,0.0f,1.0f,
      0.0f,1.0f,0.0f,
    };
    unsigned char indices_vtx[] = {0,1,0,2,0,3};
    unsigned char indices_clr[] = {0,0,1,1,2,2};   // not sure if this is correct
    glVertexPointer(3,GL_FLOAT,sizeof(float)*3,(void*)axis);
    glColorPointer(3,GL_FLOAT,sizeof(float)*3,(void*)colors);
    glIndexPointer(GL_UNSIGNED_BYTE,0,(void*)indices_clr);  // not sure if this is correct
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_INDEX_ARRAY);
    glLineWidth(2);
    glDrawElements(GL_LINES,sizeof(indices_vtx),GL_UNSIGNED_BYTE,(void*)indices_vtx);
  };

You need six vertices, two for each axis. The axes’ start vertices share the same position (0,0,0) but they don’t share the same colour, so you need three distinct vertices.

1 Like

thank you. I see, the key difference is 4 vertices vs 6 vertices.

This confusion comes from OpenGL 1.1 terminology, where sometimes it might seem that “vertex” is used interchangably with “position”.

In OpenGL 1.1 immediate mode, glVertex does not just specify the position, it also completes the vertex and associates the current values of texcoords, colors, and other attributes with the vertex.

However, a lot of code from that time seems to miss this distinction and you frequently see the term “vertex” used in old code where “position” is what is really meant.

Indices correctly specifies an index for a vertex, but it’s for a completed vertex including it’s position and any other attributes, not for position only.

What this also means is that you can’t(*) index attributes separately from each other.

(*) well, you can if you write your own vertex pulling in a shader, but that goes well beyond the level you’re working at here.

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