I was wondering if anybody knew if there is a way to use an alpha mask on a 3D object?

I was experimenting around with the MaterialShader Language and I wanted to know if there is a way to apply an alpha mask to allow blending of two textures. I did see the "tex(texture,UV).rgba" but its not working the way I thought it should work. The Idea is to make an alpha mask so then it can be used to blend different materials say I wanted to blend a road texture with the cavern texture.

Here is the code that isn't working:

``````FRAGMENT CODE:

uniform texture diffuse;
uniform texture diffuse2;
uniform texture blend;

color cavern = tex(diffuse,UV).rgba;
color alpha = tex(blend,UV).rgba;

``````
in Engine
retagged

+1 vote

Do you ignore alpha values of your respective textures ?

Also, as you are blending/mixing two values with an alpha factor, you can't ponderate both values with it, one of it would use (255. - alpha.a) instead for example (if alpha.a = 0, one texture is fully used and the other unused, right ?).

So it would be

``````DIFFUSE_ALPHA = vec4(cavern.r,cavern.g,cavern.b,alpha.a)+vec4(road.r,road.g,road.b,(255. - alpha.a));
``````

But formula would still be wrong, for example you are your resulting vector v has v.r = cavern.r + road.r that is likely to go out of bound.

So you would do something like :

``````DIFFUSE_ALPHA = vec4(cavern.r*alpha.a/255. + road.r*(255. - alpha.a)/255., cavern.g*alpha.a/255. + road.g*(255. - alpha.a)/255., cavern.b*alpha.a/255. + road.b*(255. - alpha.a)/255., cavern.a*alpha.a/255. + road.a*(255. - alpha.a)/255.);
``````

or... much simpler :

``````DIFFUSE_ALPHA = cavern.r*alpha.a/255. + road*(255. - alpha.a)/255.
``````

Maybe you'd like to try something like this, with built-in linear interpolate function :

``````DIFFUSE_ALPHA = mix(cavern, road, alpha.a/255.);
``````

or

``````DIFFUSE_ALPHA = mix(cavern, road, alpha.r/255.);
``````

-> just draw black and white on your alpha texture.

Or even :

``````DIFFUSE_ALPHA = mix(cavern, road, alpha);
``````

with proper alpha texture.

I hope it helped (I am not even using Godot yet :P), otherwise please provide result example from your favorite picture editor.

by (338 points)
selected

Thanks for the response, I'll let you know which one works and post an example.