Libgdx 3D Texture Transparency
Asked Answered
B

3

8

I'm having a problem with a texture which has transparent areas. Basically it is a texture of a coin rendered onto a cube. I can't get the corners to appear transparent, they just show up as white/gray.

I made sure to enable G20.GL_Blend, so that can't be it.

enter image description here

This is the code I use in the render() method (I tried different combinations):

    Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
    Gdx.gl20.glEnable(GL20.GL_BLEND);
    Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    Gdx.gl20.glEnable(GL20.GL_TEXTURE_2D);
    Gdx.gl20.glBlendEquation(GL20.GL_BLEND);
    
    modelBatch.begin(cam);
    texture.bind();
    modelBatch.render(instance, environment);
    modelBatch.end();
        
    Gdx.gl20.glDisable(GL20.GL_TEXTURE_2D);
Bloke answered 1/10, 2013 at 9:17 Comment(0)
C
12

Add a blending attribute to the model:

http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=10016&p=45952#p45369

Edit.- Link dead. It is like this:

modelInstance.materials.get(0).set(
    new BlendingAttribute(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)
)
Cirone answered 9/10, 2013 at 20:7 Comment(1)
Link died. Answer now shortcomming imho.Bohs
N
2

You need to add a BlendingAttribute to your ModelInstance:

modelInstance.materials.get(0).set(
    new BlendingAttribute(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)
)

You can also add it in your ModelBuilder code (where you create a Model which can create ModelInstances):

new Material(
    TextureAttribute.createDiffuse(yourTransparentTexture), 
    new BlendingAttribute(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA))
)
Nemeth answered 24/8, 2020 at 11:34 Comment(0)
A
-1

ModelBatch.begin(...) will disable Blending by calling Gdx.gl.glDisable(GL20.GL_BLEND). So make sure to enable blending AFTER calling ModelBatch.begin().

modelBatch.begin(camera); // resets Blending to false
// enable Blending
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// draw mesh
mesh.render(shader, GL20.GL_TRIANGLES);
modelBatch.end();

Source: https://mcmap.net/q/1326182/-rendering-transparent-meshes-in-libgdx

This answer is getting downvotes and I don't understand why... Look inside ModelBatch.begin(...)

public void begin (final Camera cam) {
    if (camera != null) throw new GdxRuntimeException("Call end() first.");
    camera = cam;
    if (ownContext) context.begin();
}

Which calls RenderContext.begin()

public void begin () {
    Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
    depthFunc = 0;
    Gdx.gl.glDepthMask(true);
    depthMask = true;
    Gdx.gl.glDisable(GL20.GL_BLEND); // <--- SEE HERE
    blending = false;
    Gdx.gl.glDisable(GL20.GL_CULL_FACE);
    cullFace = blendSFactor = blendDFactor = 0;
    textureBinder.begin();
}
Alphitomancy answered 26/3, 2021 at 16:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.