Skip to content

Instantly share code, notes, and snippets.

@partybusiness
Last active January 9, 2025 17:17
Show Gist options
  • Save partybusiness/ef6c6ce1e240fb30e462d9df74113692 to your computer and use it in GitHub Desktop.
Save partybusiness/ef6c6ce1e240fb30e462d9df74113692 to your computer and use it in GitHub Desktop.
Generates a checkboard pattern on a texture, which can be used as a generic texture for testing shaders and so on.
@tool
extends ImageTexture
class_name Checkers
# I wanted an example of a custom parameter-controlled texture
# There are other examples that override the _draw funcs but that approach doesn't work if
# assigning as a uniform sampler2D on a shader
@export var size:Vector2i = Vector2i(64,64):
get:
return size
set(p_value):
size = p_value
request_update(true)
@export var colour1:Color = Color.WHITE:
set(p_value):
colour1 = p_value
request_update()
@export var colour2:Color = Color.BLACK:
set(p_value):
colour2 = p_value
request_update()
@export var number_of_checks:int = 8:
set(p_value):
number_of_checks = p_value
request_update()
var image:Image
func request_update(size_changed:bool = false) -> void:
if size_changed:
gen_image()
fill_image()
image.generate_mipmaps()
if size_changed:
set_image(image)
else:
update(image)
func _init():
request_update(true)
func gen_image():
image = Image.create(size.x, size.y, true, Image.FORMAT_RGB8)
func fill_image():
image.fill(colour1)
for x in range(0, number_of_checks):
for y in range(0, number_of_checks):
if (x%2 == y%2):
continue
var corner1:Vector2i = Vector2i(x * size.x / number_of_checks, y * size.y / number_of_checks)
var corner2:Vector2i = Vector2i((x + 1) * size.x / number_of_checks, (y + 1) * size.y / number_of_checks)
# subtracting next corner works better when numbers don't divide evenly
var rect:Rect2i = Rect2i(corner1.x, corner1.y, corner2.x - corner1.x, corner2.y - corner1.y)
image.fill_rect(rect, colour2)
@partybusiness
Copy link
Author

The examples I saw extending Texture2D would override the _draw function, which works fine in the event that you assign the texture to a CanvasItem and don't try to sample the TEXTURE in the shader. But if you assign it to a shader parameter, I think it needs to be an ImageTexture like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment