Diagonalized Checkerboard Filter

I’m not really sure what to call this pattern, but I made it based on a reference from an anonymous internet fren. Requires a mask. Two masks at two different resolutions are included.

Note: I couldn’t figure out how to make it work with TextureRect’s stretch_mode on anything but `keep`, but I will update this if I ever do.

Shader code
shader_type canvas_item;

uniform sampler2D mask: filter_linear_mipmap, hint_default_white;
uniform float frequency = 4.0;

varying vec2 local_vertex;
void vertex() {
	local_vertex = VERTEX;
}

void fragment() {
	vec2 grid_cell_size = vec2(textureSize(mask, 0)) / frequency;
	
	vec2 grid_position = floor(local_vertex / grid_cell_size);
	// results in either 0.0 or 1.0
	float flip = floor(mod(grid_position.x + grid_position.y, 2.0));
	
	vec2 mask_uv = mod(local_vertex, grid_cell_size) / grid_cell_size;
	vec2 mask_uv_flipped = mod(local_vertex, grid_cell_size) / grid_cell_size;
	mask_uv_flipped.x = 1.0 - mask_uv_flipped.x;
	vec2 mask_uv_checkered = mix(mask_uv, mask_uv_flipped, flip);
	
	// create an additional diagonalized UV offset based on the checkerboard flip
	vec2 grid_cell_size_uv = grid_cell_size * TEXTURE_PIXEL_SIZE;
	vec2 grid_cell_local_uv = mod(UV, grid_cell_size_uv);
	vec2 grid_cell_local_uv_normalized = grid_cell_local_uv / grid_cell_size_uv;
	float grid_cell_top_left_ratio = floor(grid_cell_local_uv_normalized.x + grid_cell_local_uv_normalized.y);
	float grid_cell_top_right_ratio = floor(1.0 + grid_cell_local_uv_normalized.y - grid_cell_local_uv_normalized.x);
	vec2 grid_cell_offset_unflipped = mix(vec2(0.25, -0.25), vec2(-0.25, 0.25), grid_cell_top_right_ratio);
	vec2 grid_cell_offset_flipped =mix(vec2(-0.25, -0.25), vec2(0.25, 0.25), grid_cell_top_left_ratio);
	vec2 grid_cell_offset = mix( grid_cell_offset_unflipped, grid_cell_offset_flipped, flip ) * grid_cell_size_uv;
	
	vec2 uv_quantized = UV - grid_cell_local_uv + (grid_cell_size_uv/2.0) + grid_cell_offset;
	
	COLOR = texture(TEXTURE, uv_quantized) * texture(mask, mask_uv_checkered);
	COLOR.a = 1.0; // This doesn't work well with transparency, so let's just not.
}
Live Preview
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from XenithStar

Related shaders

guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments