| 7 |
| uniform float refract_index; |
| 8 | uniform float refract_intensity; |
| 9 | uniform float refract_angle; |
| 10 | uniform float4 foreground_color_premultiplied; |
| 11 |
| 12 | half sdfRect(half2 p, half4 r) { |
| 13 | r.xy = (p.x > 0.0) ? r.xy : r.zw; |
| 14 | r.x = (p.y > 0.0) ? r.x : r.y; |
| 15 | half2 q = abs(p) - size + r.x; |
| 16 | return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r.x; |
| 17 | } |
| 18 |
| 19 | half4 srcOver(half4 src, half4 dst) { |
| 20 | half3 outRGB = (src.rgb + dst.rgb * (1.0 - src.a)); |
| 21 | float outA = src.a + (1.0 - src.a) * dst.a; |
| 22 | return half4(outRGB, outA); |
| 23 | } |
| 24 |
| 25 | half4 main(in float2 fragCoord) { |
| 26 | half2 p = fragCoord - center; |
| 27 | half sdRaw = sdfRect(p, radius); |
| 28 | half2 uv = fragCoord; |
| 29 | // past the edge the lens goes on as at the edge: the outline clips it, but a downsampled glass is upscaled over it |
| 30 | half sd = min(sdRaw, 0.0); |
| 31 | half sdX = sdfRect(p + half2(1.0, 0.0), radius); |
| 32 | half sdY = sdfRect(p + half2(0.0, 1.0), radius); |
| 33 |
| 34 | half n_cos = max(thickness + sd, 0.0) / thickness; |
| 35 | half n_cos2 = n_cos * n_cos; |
| 36 | half n_sin = sqrt(1.0 - n_cos2); |
| 37 | half2 normal_xy = half2((sdX - sdRaw) * n_cos, (sdY - sdRaw) * n_cos); |
| 38 | half ca = cos(refract_angle), sa = sin(refract_angle); |
| 39 | normal_xy = half2(normal_xy.x * ca - normal_xy.y * sa, normal_xy.x * sa + normal_xy.y * ca); |
| 40 | half3 normal = normalize(half3(normal_xy, n_sin)); |
| 41 |
| 42 | half3 refract_vec = refract(half3(0.0, 0.0, -1.0), normal, 1.0 / refract_index); |
| 43 | half h = sd < -thickness ? thickness : sqrt(sd * (-2.0 * thickness - sd)); |
| 44 | half refract_length = (h + 8.0 * thickness) / -refract_vec.z; |
| 45 |
| 46 | uv += refract_vec.xy * refract_length * refract_intensity; |
| 47 | // on a small shape the edge samples past the far side: stay within the shape, whatever the grid of a downsampled node |
| 48 | uv = clamp(uv, center - size + 0.5, center + size - 0.5); |
| 49 |
| 50 | return srcOver(half4(foreground_color_premultiplied), img.eval(uv)); |
| 51 | } |
| 52 |