#version 120
uniform sampler2D iChannel0;

uniform sampler2D oldStageBuffer;

uniform float gridSize;
uniform float panelFlipTime;
uniform float interPanelDelay;

uniform vec2 minGridPos;
uniform vec2 cameraPos;
uniform vec2 bufferSize;

uniform float transitionTimer;

const float PI = 3.14159265359;

#include "shaders/logic.glsl"

float withinTextureBounds(vec2 uv)
{
	return ge(uv.x,0.0)*ge(uv.y,0.0)*le(uv.x,1.0)*le(uv.y,1.0);
}

void main()
{
	vec2 worldPos = cameraPos + gl_FragCoord.xy;
	vec2 gridPos = floor(worldPos/gridSize) - minGridPos;

	float transition = clamp(transitionTimer/panelFlipTime - (gridPos.x + gridPos.y)*interPanelDelay, 0.0, 1.0);

	vec2 inGridUV = mod(worldPos/gridSize,1.0);
	inGridUV.x = (inGridUV.x - 0.5)/abs(cos(transition*PI)) + 0.5;
	//inGridUV = (inGridUV - 0.5)/abs(cos(transition*PI)) + 0.5;

	vec2 uv = ((floor(worldPos/gridSize) + inGridUV)*gridSize - cameraPos)/bufferSize;

	vec4 old = texture2D(oldStageBuffer, uv);
	vec4 new = texture2D(iChannel0, uv);

	gl_FragColor = mix(old, new, ge(transition,0.5))*withinTextureBounds(inGridUV);
	//gl_FragColor = mix(gl_FragColor, vec4(vec3(0.0), 0.25), min(transition,1.0 - transition)*2.0);
	gl_FragColor *= gl_Color;
}