// ps_2_0 HLSL
sampler2D BASETEXTURE : register(s0);

float4 C0 : register(c0); // Holds material flags $c0_x, $c0_y, $c0_z, and $c0_w
float4 C1 : register(c1); // Holds material flags $c0_x, $c0_y, $c0_z, and $c0_w

float smoothstep(float edge0, float edge1, float x)
{
    float t = saturate((x - edge0) / (edge1 - edge0));
    return t * t * (3.0 - 2.0 * t);
}

struct PS_INPUT {
	float2 uv : TEXCOORD0;	// Texture coordinates
};

float4 main(PS_INPUT fragCoord) : COLOR
{
	float4 iResolution = float4(C0.x, C0.y, 0, 0); // xy = tamaño pantalla
	float4 iMouse = float4(C0.z, C0.w, 0, 0);      // xy = mouse coords

    float2 uv = fragCoord.uv / iResolution.xy;
    float2 mouse = iMouse.xy;
    //if (length(mouse) < 1.0)
        //mouse = iResolution.xy * 0.5;

    float2 m2 = uv - mouse / iResolution.xy;

    float roundedBox = pow(abs(m2.x * iResolution.x / iResolution.y), C1.x) +
                       pow(abs(m2.y), C1.y);

    float rb1 = saturate((1.0 - roundedBox * 10000.0) * 8.0);
    float rb2 = saturate((0.95 - roundedBox * 9500.0) * 16.0) -
                saturate(pow(0.9 - roundedBox * 9500.0, 1.0) * 16.0);
    float rb3 = saturate((1.5 - roundedBox * 11000.0) * 2.0) -
                saturate(pow(1.0 - roundedBox * 11000.0, 1.0) * 2.0);

    float4 fragColor = float4(0, 0, 0, 0);

    float transition = smoothstep(0.0, 1.0, rb1 + rb2);

    if (transition > 0.0)
    {
        float2 lens = (uv - 0.5) * 0.9 * (roundedBox * 5000.0 + 0.9) + 0.5;

        float total = 0.0;
        [unroll]
        for (int xi = -1; xi <= 1; xi++)
        {
            [unroll]
            for (int yi = -1; yi <= 1; yi++)
            {
                float2 offset = float2(xi, yi) * 0.5 / iResolution.xy;
                fragColor += tex2D(BASETEXTURE, offset + lens);
                total += 1.0;
            }
        }
        fragColor /= total;

        // Lighting
        float gradient = saturate((saturate(m2.y / 0.2) + 0.1) / 2.0) +
                         saturate((saturate(-m2.y / 0.2) * rb3 + 0.1) / 2.0);

        float4 lighting = min(
            float4(1.0, 1.0, 1.0, 1.0),
            max(
                float4(0.0, 0.0, 0.0, 0.0),
                fragColor + float4(rb1, rb1, rb1, rb1) * gradient +
                            float4(rb2, rb2, rb2, rb2) * 0.3
            )
        );

        // Antialiasing (lerp en vez de mix)
        fragColor = lerp(tex2D(BASETEXTURE, uv), lighting, transition);
    }
    else
    {
        fragColor = tex2D(BASETEXTURE, uv);
    }

    return float4(fragColor.xyz, 1);
}
