danielspaniol
danielspaniol

Reputation: 2328

OpenGL - Depth test doesn't work

I am leanring OpenGL and at the moment I learn how to add the 3rd dimension. I want to make a Cube but only one of its sides is not transparent:

Current front side is transparent

Blue side is not transparent

My draw-function looks like this:

void draw()
{
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH);

    glUseProgram(program);

    // The attributes are like they have to be, nothing wrong here
    glBindBuffer(GL_ARRAY_BUFFER, vboCube);
    glEnableVertexAttribArray(attributePosition);
    glVertexAttribPointer(
        attributePosition,
        3,
        GL_FLOAT,
        GL_FALSE,
        sizeof(attributes),
        (GLvoid *)offsetof(attributes, position)
    );
    glEnableVertexAttribArray(attributeColor);
    glVertexAttribPointer(
        attributeColor,
        3,
        GL_FLOAT,
        GL_FALSE,
        sizeof(attributes),
        (GLvoid *)offsetof(attributes, color)
    );

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboCube);
    int size;
    glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);

    glDrawElements(GL_TRIANGLES, size / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glDisableVertexAttribArray(attributePosition);
    glDisableVertexAttribArray(attributeColor);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

and my tick-function (which is called 40 times per second) looks like this:

void tick()
{
    glm::mat4 model = glm::translate(glm::mat4(1), glm::vec3(0, 0, -4));
    glm::mat4 view = glm::lookAt(glm::vec3(0, -2, 0), glm::vec3(0, 0, -4), glm::vec3(0, 1, 0));
    glm::mat4 projection = glm::perspective(45.0f, WIDTH / (float) HEIGHT, 0.1f, 10.0f);
    glm::mat4 daRealMvp = projection * view * model; // 9gaggers will get this

    // adding some rotation so i can see why the cube looks strange
    float angle = glfwGetTime();
    daRealMvp = daRealMvp * glm::rotate(glm::mat4(1), angle, glm::vec3(0, 1, 0));

    glUniformMatrix4fv(uniformMvp, 1, GL_FALSE, glm::value_ptr(daRealMvp));
}

If I remove glEnable(GL_DEPTH); (or move it to another line) or change glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); to glClear(GL_COLOR_BUFFER_BIT); nothing changes, so I thought there is a problem with clearing the depth-buffer, but I don't know what it is.

So, what can I do to get a nice cube? :)

EDIT1:

funny thing is, the blue face (which is not transparent) isnt the one on the front (where all vertices have positive Z), its the the one on the right (where all vertices have a positive X).

Upvotes: 0

Views: 814

Answers (1)

Mehdi
Mehdi

Reputation: 578

you should use

glEnable(GL_DEPTH_TEST);

instead of

glEnable(GL_DEPTH); 

at the third line.

Upvotes: 4

Related Questions