PDA

View Full Version : Z-buffer issue with two walls



Bronislaw666
06-20-2017, 06:29 AM
Hi there,

I've got a problem regarding the z-buffer. It doesn't seem to work properly and I don't know what's wrong. I've tested many things, but nothing works.

There are two walls. A front white one and a green back one.
If I move the white wall along the z-axis in negative direction (in real-time), it is still visible for the whole time, even when it has moved far behind the green wall.
What's the solution for this problem? Many thanks in advance for any hints!


#include <SFML/Graphics.hpp>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
#include <SFML/OpenGL.hpp>

void myGluPerspective(double fovy, double aspect, double zNear, double zFar)
{
double f = 1.0 / tan(fovy * M_PI / 360); // convert degrees to radians and divide by 2
double xform[16] =
{
f / aspect, 0, 0, 0,
0, f, 0, 0,
0, 0, (zFar + zNear)/(zFar - zNear), -1,
0, 0, 2*zFar*zNear/(zFar - zNear), 0
};
glMultMatrixd(xform);
}

float testvar = 0;

int main()
{
sf::ContextSettings Settings;
Settings.depthBits = 24;
Settings.stencilBits = 8;
Settings.antialiasingLevel = 2;
sf::Window window(sf::VideoMode(800, 600, 32), "SFML OpenGL", sf::Style::Close, Settings);

window.setFramerateLimit(40);

glClearDepth(1.f);
glClearColor(0.8f, 0.8f, 0.8f, 0);

glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();

myGluPerspective(60,800.0f/600.0f,0,180);

glTranslatef(0,0,-3);

while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
}
}

window.setActive();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);

testvar = testvar - 0.01f;
//glRotatef(1,0,0.1f,0);

glBegin(GL_QUADS);

glColor3f(1.0f,1.0f,1.0f); // white front wall
glVertex3f(-1,-1,testvar);
glVertex3f(1,-1,testvar);
glVertex3f(1,1,testvar);
glVertex3f(-1,1,testvar);

glColor3f(0.0f,1.0f,0.0f); // green back wall
glVertex3f(-1,-1,-1);
glVertex3f(1,-1,-1);
glVertex3f(1,1,-1);
glVertex3f(-1,1,-1);

glEnd();

window.display();
}
return 0;
}

Bronislaw666
06-22-2017, 04:23 AM
Problem solved: The z-axis directions are reversed.
zFar = zNear and zNear = zFar.

mhagain
06-22-2017, 09:24 AM
Your problem is actually that your zNear is 0.
myGluPerspective(60,800.0f/600.0f,0,180);This is always illegal in any API for a perspective projection because it ultimately causes division-by-zero errors. Set it to a low - but not too low - value instead. 0.5 or 1 would be good, 0.000001 would definitely not be good.