shader_type canvas_item;

const float PI = 3.14159;

uniform float bits = 1.;
uniform float pixel_offset = 0.5;

uniform float total_distance = 50.;

uniform float wave1 :hint_range(0.0, 1.0, 1.) = 1.;
uniform float wave2 :hint_range(0.0, 1.0, 1.) = 1.;
uniform float wave3 :hint_range(0.0, 1.0, 1.) = 1.;

uniform vec4 wave1_color : hint_color = vec4(0.0,1.0,0.0,1.);
uniform vec4 wave2_color : hint_color = vec4(0.0,1.0,0.0,1.);
uniform vec4 wave3_color : hint_color = vec4(1.,1.,1.,1.);

uniform float wave_frequency: hint_range(0.0, 10.) = 0.2;
uniform float wave_amplitude: hint_range(0., 1.) = 0.3;
uniform float wave_offset: hint_range(-1., 1.) = 0.5;

uniform float traveling : hint_range(0.,1.,  1.) = 1.;
uniform float travel_speed : hint_range(-100., 100.) = 0.618;

uniform float oscilating : hint_range(0.,1.,  1.) = 1.;
uniform float oscilation_speed : hint_range(-100., 100.) = 0.618;

float plot(vec2 st, float pct) {
	return smoothstep(pct - 0.03, pct, st.y) -
			smoothstep(pct, pct + 0.03, st.y);
}

void fragment() {
	// Adapt the size of pixel regions to the size of the texture 
	float x_bits = bits / TEXTURE_PIXEL_SIZE.x;
	float y_bits = bits / TEXTURE_PIXEL_SIZE.y;
	// Segment the UV into pixels
	float pixelized_x = floor(UV.x * x_bits)/x_bits + pixel_offset/x_bits;
	float pixelized_y = floor(UV.y * y_bits)/y_bits + pixel_offset/y_bits;
	vec2 pixel_coord = vec2(pixelized_x, pixelized_y);
	
	float freq = wave_frequency / TEXTURE_PIXEL_SIZE.x;
	
	float travel_summand = (TIME * traveling * travel_speed);
	float oscilation_factor = (sin(TIME) * oscilating * oscilation_speed);
	
	float y1 = sin(pixel_coord.x * freq + travel_summand) * (wave_amplitude/2. + wave_amplitude/2. * oscilation_factor) + wave_offset;
	float y2 = -1. * sin(pixel_coord.x * freq + travel_summand) * (wave_amplitude/2. + wave_amplitude/2. * oscilation_factor) + wave_offset;
	float y3 = 0. + wave_offset;
	float point1 = (plot(pixel_coord, y1));
	float point2 = (plot(pixel_coord, y2));
	float point3 = (plot(pixel_coord, y3));
	vec4 c = point1 * wave1 * wave1_color + point2 * wave2 * wave2_color + point3 * wave3 * wave3_color;
	
	vec2 texture_coord = UV.xy / (TEXTURE_PIXEL_SIZE.xy);
	float dist = max(sign(total_distance - texture_coord.x), 0.);
	
	COLOR = c * dist;
}