Trying to implement depth testing for 2d isometric game. I have this sample, and it doesn’t seem that depth values are written to the depth buffer.
The effect I’m trying to achieve is when second.png is drawn on top of first.png, only red is displayed on screen.
But what I get is that second.png is drawn normally and green part is visible.
private SpriteBatch mBatch;
private Texture mSprite1;
private Texture mSprite2;
@Override
public void create() {
mBatch = new SpriteBatch();
mBatch.setShader(new ShaderProgram(Gdx.files.internal("test.vsh"), Gdx.files.internal("test.fsh")));
mSprite1 = new Texture("first.png");
mSprite2 = new Texture("second.png");
Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl20.glDepthFunc(GL20.GL_LESS);
Gdx.gl20.glDepthMask(true);
}
float mx = 0.0f;
float my = 0.0f;
private void tick() {
float speed = 100.0f * Gdx.graphics.getDeltaTime();
if (Gdx.input.isKeyPressed(Keys.A))
mx -= speed;
if (Gdx.input.isKeyPressed(Keys.D))
mx += speed;
if (Gdx.input.isKeyPressed(Keys.W))
my += speed;
if (Gdx.input.isKeyPressed(Keys.S))
my -= speed;
}
@Override
public void render() {
tick();
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
mBatch.begin();
float scale = 4.0f;
float x = Gdx.graphics.getWidth() / 2;
float y = Gdx.graphics.getHeight() / 2;
mBatch.draw(mSprite1, x - mSprite1.getWidth() / 2 * scale, y - mSprite1.getHeight() / 2 * scale,
mSprite1.getWidth() * scale, mSprite1.getHeight() * scale);
mBatch.flush();
mBatch.draw(mSprite2, mx + x - mSprite2.getWidth() / 2 * scale, my + y - mSprite2.getHeight() / 2 * scale,
mSprite2.getWidth() * scale, mSprite2.getHeight() * scale);
mBatch.end();
int width = Gdx.graphics.getWidth();
int height = Gdx.graphics.getHeight();
FloatBuffer buffer = BufferUtils.newFloatBuffer(width * height);
Gdx.gl20.glReadPixels(0, 0, width, height, GL20.GL_DEPTH_COMPONENT, GL20.GL_FLOAT,
buffer);
for (int i = 0; i < width * height; i++) {
float pixel = buffer.get(i);
if (pixel != 1.0f) {
throw new IllegalStateException("OMG IT WORKS!!");
}
}
if (Gdx.gl20.glGetError()!=0) {
throw new Error("OPENGL ERROR: " + Gdx.gl20.glGetError());
}
}
vertex shader
#ifdef GL_ES
precision mediump float;
#endif
attribute vec3 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;
uniform mat4 u_projTrans;
varying vec4 v_color;
varying vec2 v_texCoord;
void main()
{
gl_Position = u_projTrans * vec4(a_position, 1);
v_color = a_color * 2.0;
v_texCoord = a_texCoord0;
}
fragment shader
#ifdef GL_ES
precision mediump float;
#endif
uniform sampler2D u_texture;
varying vec4 v_color;
varying vec2 v_texCoord;
void main()
{
vec4 texel = v_color * texture2D(u_texture, v_texCoord);
if (texel.r > 0)
{
gl_FragDepth = 0.0;
}
else
{
gl_FragDepth = 0.5;
}
gl_FragColor = texel;
}
first.png
second.png