#include <metal_stdlib>
using namespace metal;

kernel void compute_spatial_vortex(
    texture2d<float, access::sample> inTexture [[texture(0)]],
    texture2d<float, access::write> outTexture [[texture(1)]],
    constant float &time [[buffer(0)]],
    uint2 gid [[thread_position_in_grid]]
) {
    if (gid.x >= outTexture.get_width() || gid.y >= outTexture.get_height()) return;
    float2 uv = float2(gid) / float2(outTexture.get_width(), outTexture.get_height());
    float2 delta = uv - float2(0.5);
    float angle = atan2(delta.y, delta.x) + (1.0 - length(delta)) * sin(time);
    float r = length(delta);
    float2 twisted = float2(0.5) + float2(cos(angle), sin(angle)) * r;
    outTexture.write(float4(twisted.x, twisted.y, 1.0, 1.0), gid);
}
