Incorrect values written in stencil buffer

I am trying to pick objects on mouse click. For this I have followed this tutorial, and tried to use the stencil buffer for this purpose.

Inside “game” loop I am trying to draw 10 (5 pairs) 'pick’able triangles as follows:


...

glClearColor(red, green, blue, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

glClearStencil(0); // this is the default value

/* Enable stencil operations */
glEnable(GL_STENCIL_TEST);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);

/*Some other drawing not involving stencil buffer*/

int index = 0;
for (GLshort i = 0; i < 5; i++)
{
    //this returns 2 model matrices
    auto modelMatrices = trianglePairs[i].getModelMatrices(); 

    for (GLshort j = 0; j < 2; j++)
    {
        glStencilFunc(GL_ALWAYS, index, -1);
        glUniformMatrix4fv(glGetUniformLocation(ourShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(modelMatrices[j]));
        glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, BUFFER_OFFSET(2));
        index++;
    }
    /*Some other drawing not involving stencil buffer*/
}

...

However, when I am trying to read back the stencil values, I am getting wrong values. I am reading back the values as (this is also a part of the above-mentioned tutorial):


GLuint index;
glReadPixels(xpos, Height - ypos - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);

Whenever, I click the first triangle of the pair I am getting values as i+1, whereas the correct value should have been i, and for the second triangle of the pair, I am getting 0 as index.

Please let me know what am I missing here?