OpenGL ES 2.0 transparency using alpha testing in a shader

I am trying to make a transparent object in OpenGL ES 2.0. I configure GL with options:

GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glDepthFunc(GLES20.GL_LESS); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glClearDepthf(1.0f); 

Here is the code for the shaders:

 private final String mVertexShader = "uniform mat4 uMVPMatrix;\n" + "attribute vec4 aPosition;\n" + "attribute vec2 aTextureCoord;\n" + "varying vec2 vTextureCoord;\n" + "void main() {\n" + " gl_Position = uMVPMatrix * aPosition;\n" + " vTextureCoord = aTextureCoord;\n" + "}\n"; private final String mFragmentShader = "precision mediump float;\n" + "varying vec2 vTextureCoord;\n" + "uniform sampler2D sTexture;\n" + "void main() {\n" + " vec4 base = texture2D(sTexture, vTextureCoord);\n" + " if(base.a < 0.5){ discard; }\n" + " gl_FragColor = base;\n" + "}\n"; 

Resulting rendering images: http://imgur.com/hNqm0 http://imgur.com/dmS2O . Please tell me what I'm doing wrong, it works fine in OpenGL ES Rendermonkey mode.

If i use

  GLES20.glDisable(GLES20.GL_BLEND); 

to initialize OpenGL, I get the correct transparency, but without trianging. Maybe some sorting will help in this case?

+4
source share
4 answers

Ok, so I found the reason for this failure.

Although the depth check was turned off and the fragment shader discarded certain pixels making them transparent, the triangles were still closed due to writing to the depth buffer.

I had to disable writing to the depth buffer using this code:

 GLES20.glDepthMask(false); 

Obviously, writing to the depth buffer was also disabled in the Rendermonkey, resulting in the correct image.

Thanks for your answers below, but I do not need to use alpha blending - I need to use alpha testing, and this does not require triangles sorting.

+4
source

Alpha mix supported by OpenGL. You do not need a special code in the shader. Try the following:

  GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc (GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); 
+5
source

OpenGL does not order your triangles. But since you just do alpha testing and turn off blending, this should not be a problem for you.

+2
source

I think you should put "gl_FragColor = base;" in 'else' like

 private final String mFragmentShader = "precision mediump float;\n" + "varying vec2 vTextureCoord;\n" + "uniform sampler2D sTexture;\n" + "void main() {\n" + " vec4 base = texture2D(sTexture, vTextureCoord);\n" + " if(base.a < 0.1){ discard; }\n" + " else { gl_FragColor = base; }\n" + "}\n"; 

this

+2
source

All Articles