shader_type canvas_item;

uniform float wind_speed = 1.0;
uniform float wind_strength = 10.0;
uniform sampler2D noise_tex : repeat_enable;
uniform vec2 frame_size = vec2(16.0, 32.0);
uniform vec2 sheet_size = vec2(64.0, 32.0);
uniform vec4 modulate : source_color = vec4(1.);

void vertex() {
	float rnd_offset = INSTANCE_CUSTOM.r;
	float tex_idx = INSTANCE_CUSTOM.g;
	float state = INSTANCE_CUSTOM.b;

	if (state < 0.5) { 
		vec2 world_pos = (MODEL_MATRIX * vec4(VERTEX, 0.0, 1.0)).xy;
		float noise = texture(noise_tex, world_pos * 0.005 + vec2(TIME * wind_speed * 0.1)).r;

		if (VERTEX.y < 0.0) {
			VERTEX.x += sin(TIME * wind_speed) * (wind_strength * noise) + rnd_offset;
		}
	}

	if (state > 0.5) {
		VERTEX.y *= 0.2;
		VERTEX.y += 5.0;
	}

	float columns = sheet_size.x / frame_size.x;
	float col_idx = mod(tex_idx, columns);

	UV.x = (UV.x / columns) + (col_idx / columns);
}

void fragment() {
	vec2 uv = vec2(UV.x, 1. - UV.y); 

	vec4 col = texture(TEXTURE, uv);
	COLOR = col * modulate;
}