Need help with masking a texture using alpha or gray-scale

Hello,

I am new to MonoGame and have been doing some digging with no such luck for a solid solution or reasonable example. I want to to make a texture partially transparent to completely transparent using a gradient mask. It seems that a stencil buffer will not work for this, and a shader will be needed, but I have not been able to find a good example. Here is an image of what I am trying to achieve. Any help or references would be great!

As an fyi I am developing only for the monogame directx platform.

There’s another thread on here about alpha masking. You can also find lots of help online related to alpha masking shaders. Here’s an example on StackOverflow, although it’s in GLSL, but you can get the general idea. I’m not sure what level of familiarity you have with shaders, but feel free to ask for more explicit examples. The main idea is that in your pixel shader, you sample from both textures, and multiply the output alpha by the grayscale or alpha of the mask.

EDIT: If you want to apply an alpha mask that is a function of position, rather than sampling from a texture, you can do the same thing, but evaluate your function in the vertex or pixel shader rather than sampling the alpha mask texture.

You can simply achieve this with a custom blend state if your gradient is a texture with alpha values as in your b/w image (black being alpha 1 and white 0). Here’s a gist with a sample Game1: https://gist.github.com/Jjagg/db34a25897e20dbdb0f16cb5bcb75493
If you want to understand this better, I recommend reading up on premultiplied alpha (if you haven’t yet): https://blogs.msdn.microsoft.com/shawnhar/2009/11/06/premultiplied-alpha/

1 Like

Thank you @Jjagg for your very detailed sample, and the referenced article. I was able to follow and understand what was going on and then apply it to my own circumstance. I was wondering if there were any performance considerations to keep in mind with this approach. It would also seem that if I need to mask multiple textures I could do two sprite batches to a render target the size of the viewport. First drawing the textures and then drawing the masks using the blend state.

Also if I am understanding that the render target is just a buffer on the graphics card, if the completed render target does not change between frames, I could just redraw the render target to the back buffer, yes?

Thank you again for imparting knowledge!

1 Like