关于鼠标位置的鱼眼变形 - 片段着色器

Fish-eye warping about mouse position - fragment shader

我正在尝试创建鱼眼效果,但仅限于鼠标位置周围的小半径范围内。我已经能够修改 this code to work about the mouse position (demo) 但我无法弄清楚缩放的来源。我期待输出像这样扭曲图像(为了这个问题忽略颜色反转):

相关代码:

// Check if within given radius of the mouse
vec2 diff = myUV - u_mouse - 0.5;
float distance = dot(diff, diff); // square of distance, saves a square-root

// Add fish-eye 
if(distance <= u_radius_squared) {
  vec2 xy = 2.0 * (myUV - u_mouse) - 1.0;
  float d = length(xy * maxFactor);
  float z = sqrt(1.0 - d * d);
  float r = atan(d, z) / PI;
  float phi = atan(xy.y, xy.x);
    
  myUV.x = d * r * cos(phi) + 0.5 + u_mouse.x;
  myUV.y = d * r * sin(phi) + 0.5 + u_mouse.y;
}

vec3 tex = texture2D(tMap, myUV).rgb;

gl_FragColor.rgb = tex;

这是我的第一个着色器,所以除了解决这个问题之外的其他改进也欢迎。

计算当前片段到鼠标的向量和向量的长度:

vec2 diff = myUV - u_mouse;
float distance = length(diff);

新的纹理坐标是鼠标位置和缩放后的方向向量之和:

myUV = u_mouse + normalize(diff) * u_radius * f(distance/u_radius);

例如:

uniform float u_radius;
uniform vec2 u_mouse;

void main()
{
    vec2 diff = myUV - u_mouse;
    float distance = length(diff);

    if (distance <= u_radius)
    {
        float scale = (1.0 - cos(distance/u_radius * PI * 0.5));
        myUV = u_mouse + normalize(diff) * u_radius * scale;
    }

    vec3 tex = texture2D(tMap, myUV).rgb;
    gl_FragColor = vec4(tex, 1.0);
}