#version 300 es
precision highp float;

uniform sampler2D uPassTex;
uniform sampler2D normalTex;
uniform float uRate;

in vec2 vUV;
in vec2 vNormalUV;
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);
}

vec4 safeTextureRev(sampler2D tex, vec2 uv) {
    if (uv.x < 0.001 || uv.x > 0.999 || uv.y < 0.001 || uv.y > 0.999) {
        return texture(tex, vec2(vUV.x, 1.0 - vUV.y));
    }
    return texture(tex, vec2(uv.x, 1.0 - uv.y));
}

void main() {
    vec3 normal = texture(normalTex, vNormalUV).rgb * 2.0 - 1.0;
    normal = normalize(normal);

    float distortionStrength = 0.2 * uRate;// 使用 uRate 控制扭曲强度
    vec2 distortion = normal.xy * distortionStrength;
    vec2 distortedUV = clamp(vUV + distortion, 0.0, 1.0);

    fragColor = safeTexture(uPassTex, distortedUV);
}