|
| 1 | +precision highp float; |
| 2 | +varying highp vec2 vVertTexCoord; |
| 3 | + |
| 4 | +uniform sampler2D uImg; |
| 5 | +uniform sampler2D uDepth; |
| 6 | +uniform vec2 uSize; |
| 7 | +uniform float uIntensity; |
| 8 | +uniform float maxBlur; |
| 9 | +uniform int uNumSamples; |
| 10 | +uniform float uTargetZ; |
| 11 | +uniform float uNear; |
| 12 | +uniform float uFar; |
| 13 | + |
| 14 | +#define PI 3.14159265359; |
| 15 | + |
| 16 | +const int MAX_NUM_SAMPLES = 50; |
| 17 | + |
| 18 | +float rand(vec2 co){ |
| 19 | + return fract(sin(dot(co.xy, vec2(12.9898,78.233))) * 43758.5453); |
| 20 | +} |
| 21 | + |
| 22 | +float depthToZ(float depth) { |
| 23 | + float depthNormalized = 2.0 * depth - 1.0; |
| 24 | + return 2.0 * uNear * uFar / (uFar + uNear - depthNormalized * (uFar - uNear)); |
| 25 | +} |
| 26 | + |
| 27 | +float calcBlur(float z, float pixelScale) { |
| 28 | + return clamp(abs(z - uTargetZ), 0.0, 0.3*pixelScale); |
| 29 | +} |
| 30 | + |
| 31 | +void main() { |
| 32 | + float pixelScale = max(uSize.x, uSize.y); |
| 33 | + float total = 1.0; |
| 34 | + float origZ = depthToZ(texture2D(uDepth, vVertTexCoord).x); |
| 35 | + vec4 color = texture2D(uImg, vVertTexCoord); |
| 36 | + float blurAmt = calcBlur(origZ, pixelScale); |
| 37 | + for (int i = 0; i < MAX_NUM_SAMPLES; i++) { |
| 38 | + if (i >= uNumSamples) break; |
| 39 | + float t = (float(i + 1) / float(uNumSamples)); |
| 40 | + float angle = (t*12.0) * 2. * PI; |
| 41 | + float radius = 1.0 - (t*t*t); // Sample more on the outer edge |
| 42 | + angle += 5.*rand(gl_FragCoord.xy); |
| 43 | + vec2 offset = (vec2(cos(angle),sin(angle)) * radius * uIntensity * blurAmt)/pixelScale; |
| 44 | + float z = depthToZ(texture2D(uDepth, vVertTexCoord + offset).x); |
| 45 | + float sampleBlur = calcBlur(z, pixelScale); |
| 46 | + |
| 47 | + float weight = float((z >= origZ) || (sampleBlur >= blurAmt*radius + 5.)); |
| 48 | + vec4 sample = texture2D(uImg, vVertTexCoord + offset); |
| 49 | + color += weight * sample; |
| 50 | + total += weight; |
| 51 | + } |
| 52 | + color /= total; |
| 53 | + gl_FragColor = color; |
| 54 | +} |
0 commit comments