#version 300 es
precision highp float;

uniform sampler2D uPassTex;// 原始图像
uniform sampler2D normalTex;// 用于计算法线的图像

uniform vec2 uOffset;
uniform float uDepth;

in vec2 vUV;
in vec2 vNormalUV;
in vec4 vRectBounds;
in vec2 vFragCoord;
out vec4 fragColor;

// 添加安全的纹理采样
vec4 safeTexture(sampler2D tex, vec2 uv) {
    if (uv.x < 0.001 || uv.x > 0.999 || uv.y < 0.001 || uv.y > 0.999) {
       return texture(tex, vUV);
    }
    return texture(tex, uv);
}

// 采样函数
vec3 texSample(float x, float y) {
    vec2 uv = vNormalUV + vec2(x, y);
    return texture(normalTex, uv * 2.).rgb;
}

// 亮度计算
float luminance(vec3 c) {
    return dot(c, vec3(0.2126, 0.7152, 0.0722));
}

// 法线计算
vec3 calcNormal() {
    float R = abs(luminance(texSample(uOffset[0], 0.0)));
    float L = abs(luminance(texSample(-uOffset[0], 0.0)));
    float D = abs(luminance(texSample(0.0, uOffset[1])));
    float U = abs(luminance(texSample(0.0, -uOffset[1])));

    float X = (L - R) * 0.5;
    float Y = (U - D) * 0.5;

    return normalize(vec3(X, Y, 1.0 / (uDepth)));
}

void main() {
    vec3 normal = calcNormal();

    // 控制扭曲强度
    float distortionStrength = 0.2;

    // 计算扭曲偏移并限制范围
    vec2 distortion = normal.xy * distortionStrength;

    // 确保 UV 在 [0,1] 范围内
    vec2 distortedUV = clamp(vUV + distortion, 0.0, 1.0);

    fragColor = safeTexture(uPassTex, distortedUV);
}