I'm trying to add two textures to a 3d cube. I achieved my goal, but on the way I lost the background color.
I want to show the original color of the images and also the background color. I use a mix, but it displays the background completely dark.
This is how it looks my fragmentShaderCode:
private final String fragmentShaderCode =
"precision mediump float;"
"uniform sampler2D u_Texture0;"
"uniform sampler2D u_Texture1;"
"uniform vec4 aColor;"
"varying vec2 v_TexCoordinate0;"
"varying vec2 v_TexCoordinate1;"
"void main() {"
" vec4 base = texture2D(u_Texture0, v_TexCoordinate0);"
" vec4 overlay = texture2D(u_Texture1, v_TexCoordinate1);"
" mediump float ra = (overlay.a) * overlay.r (1.0 - overlay.a) * base.r;"
" mediump float ga = (overlay.a) * overlay.g (1.0 - overlay.a) * base.g;"
" mediump float ba = (overlay.a) * overlay.b (1.0 - overlay.a) * base.b;"
" gl_FragColor = vec4(mix(aColor.rgb, vec4(ra, ga, ba, 1.0).rgb , vec4(ra, ga, ba, 1.0).a), 1.0);"
"}";
CodePudding user response:
The alpha channel of vec4(ra, ga, ba, 1.0)
is 1.0. Therefore the result of vec4(ra, ga, ba, 1.0).a
is always 1.0.
You need to use the texture's alpha channels. e.g.: max(base.a, overlay.a)
:
vec3 textureColor = vec3(ra, ga, ba);
float textureAlpha = max(base.a, overlay.a);
gl_FragColor = vec4(mix(aColor.rgb, textureColor, textureAlpha), 1.0);
Simplify the code by mixing the texture colors with the mix
function:
void main() {
vec4 base = texture2D(u_Texture0, v_TexCoordinate0);
vec4 overlay = texture2D(u_Texture1, v_TexCoordinate1);
vec3 textureColor = mix(base.rgb, overlay.rgb, overlay.a);
float textureAlpha = max(base.a, overlay.a);
gl_FragColor = vec4(mix(aColor.rgb, textureColor, textureAlpha), 1.0);
}