// Polar.fx
//
// Based on
// VVVV PolarCoordinates.fx by mtallen

struct VS_OUTPUT
{
  float4 Position: POSITION;
  float3 Tex0:     TEXCOORD0;
};

sampler Sampler = sampler_state
{
  MipFilter = LINEAR;
  MinFilter = LINEAR;
  MagFilter = LINEAR;
};


float V_Alpha : ALPHA;
float slider  : VAR1; // 1.0
float repeat  : VAR2; // 1.0
float scale   : VAR3; // 1.0
float offsetx : VAR4; // 0.0
float offsety : VAR5; // 0.0

float2 cartesian(float2 coords)
{
  float2 nuevas;
  nuevas[0] = coords[0] - (0.5 + offsetx);
  nuevas[1] = 1 - coords[1];
  nuevas[1] = coords[1] - (0.5 + offsety);
  return nuevas;
}
float2 cartToPolar(float2 coords)
{
  float mag = (length(coords)*2)*scale;
  // clamp it
  // comment out the next line if you just want the edges to repeat
  if (!repeat)
  {
    mag = saturate(mag);
  }
  // angle = arc tangent of y/x
  float angle = (atan2(coords[1], coords[0]))*slider;
  angle /= 6.28319;
  
  coords[0] = frac(angle);
  coords[1] = frac(mag);
  return coords;
}

float4 PS(VS_OUTPUT In) : COLOR0
{
  /*
   * for the conversion to polar coordinates we will offset the incoming
   * pixels coordinates to be in a cartesian plane with 0.0, 0.0 as the center
   * of the image and the upper left corner being -0.5, 0.5. From here we will
   * use those coordinates as a vector, getting the magnitude and the angle
   * using sweet sweet linear algebra. we clamp the radius to the size of the
   * image (1.0), and we use that and the angle in radians for our new color!
   */
     
  float2 coords;
  float4 col;
    
  // convert to cartesian
  // do the algebra to get the angle and magnitude
  coords = cartToPolar(cartesian(In.Tex0));
  col    = tex2D(Sampler,coords);
  col.a  = V_Alpha;
  return col;
}

technique Polar
{
  pass PassPolar
  {
    PixelShader = compile ps_2_0 PS();
  }
}
