Dither opacity with GLES2 Support

Dithering can be used as an alternative to transparency. Ideal for mobile devices to improve performance.

Inspired by Toadile https://www.youtube.com/watch?v=9V3WcE2Zups

 

 

Shader code
/*
	Dither Opacity Shader with GLES2  by Firerabbit
	
	MIT License
*/

shader_type spatial;

uniform sampler2D _albedo : hint_albedo;
uniform float _alpha_clip : hint_range(0,1) = 0.01;

const mat4 dither = mat4(
	vec4(0.0625, 0.5625, 0.1875,  0.6875),
	vec4(0.8125, 0.3125, 0.9375,  0.4375),
	vec4(0.25, 0.75, 0.125, 0.625),
	vec4(1.0, 0.5, 0.875,  0.375));
	
float getValue(int x, int y) {

	float res = 0.0;
	vec4 temp;
	// GLES 2
	if (x == 0) {temp = dither[0];} 
	else if (x == 1) temp = dither[1];
	else if (x == 2) temp = dither[2];
	else if (x == 3) temp = dither[3];
	
	
	if (y == 0) {res = temp[0];} 
	else if (y == 1) res = temp[1];
	else if (y == 2) res = temp[2];
	else if (y == 3) res = temp[3];
		
	return res;
	
}

void fragment() {
	vec4 color = texture(_albedo, UV);
	
	float limit = getValue(int(FRAGCOORD.x) % 4, int(FRAGCOORD.y) % 4);
	
	if (color.a < limit || color.a < _alpha_clip) {
		discard;
	}
	ALBEDO = color.rgb;
}
Tags
alpha, dither, dithering, opacity
The shader code and all code snippets in this post are under MIT license and can be used freely. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from Firerabbit

Mesh Blending with Alpha

Generalized Kuwahara

Terrain Mesh Blending with Dithering

Related shaders

Opacity Pulse

Post Effect Outline Shader for GLES2

Image opacity

Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Hei
Hei
2 years ago

Thank you for the nice shader! Just FYI, the switch statement isn’t necessary. You can use the index to get the correct vec4 channel:

float getValue(int x, int y) {
	return dither[x][y];
}