Convert TextureRect to Texture2D?

Godot Version

4.6.2

Question

I have a TextureRect with this code that has it display regions from an AtlasTexture

extends TextureRect

@export var atlas_texture: Texture2D
@export var x_index:int = 0
@export var y_index:int = 0
@export var icon_size:int = 50

var atlas: AtlasTexture

func _ready():
atlas = AtlasTexture.new()
atlas.atlas = atlas_texture
texture = atlas
update_region()

func _on_button_pressed() → void:
x_index += 1
update_region()

func update_region():
var x = x_index * icon_size
var y = y_index * icon_size
atlas.region = Rect2(x, y, icon_size, icon_size)

and I need to have the displayed region converted into some format that I can use as the mask parameter for this shader, such as Texture2D. Some other way of slicing up the atlas would also work. The shader takes atlastextures, but it uses the whole atlas even with parameters set, and thst’s not usable for me.

shader_type canvas_item;

uniform sampler2D mask;

void fragment( )
{
	vec4 mask_color = texture(mask, UV).rgba;
	vec4 sprite_color = texture(TEXTURE, UV).rgba;
	
	if (mask_color.a == 0.0)
	{
		sprite_color.a = 0.0;
	}
	COLOR = sprite_color;
}

Render the texture rect into a subviewport and plug subviewport’s texture into the shader.

I tried that already, but when I try to input it into the shader, I get a warning saying “Can’t create a ViewportTexture on resources saved as a file. Resource needs to belong to a scene.”

1 Like

Assign it at runtime.

1 Like

I tried for a while, and can’t quite figure out how to do this on my own. Any suggestions for how I would go about doing that? I’m new to Godot, so if you’re willing, more details would be better lol

In your initialization code assign the viewport texture reference to shader’s mask uniform:

your_material.set_shader_parameter("mask", your_subviewport_node.get_texture())