GLSL shader example
Depth-of-Field Blur from a Depth Texture
The depth fixture varies from left to right. Focus selects the sharp band; depth difference controls blur radius. This introductory gather filter does not solve foreground occlusion leakage.
Live example
Edit the code and the preview updates as you type.
What to observe
Depth-of-Field Blur from a Depth Texture.
Mechanism
The depth fixture varies from left to right. Focus selects the sharp band; depth difference controls blur radius. This introductory gather filter does not solve foreground occlusion leakage.
The controlling code
float depth=texture2D(u_depth,uv).r,radius=abs(depth-u_parameter)*.045;vec3 sum=vec3(0.);float w=0.;for(int y=-3;y<=3;y++)for(int x=-3;x<=3;x++){vec2 o=vec2(float(x),float(y))/3.;if(dot(o,o)<=1.){sum+=texture2D(u_texture,uv+o*radius).rgb;w++;}}c=sum/w;
Experiment
Set u_parameter to 0.25 and then 0.75. Since the depth fixture grows from black on the left to white on the right, abs(depth-u_parameter)*.045 moves the sharp vertical band across the image.
Debugging and cost
The -3 to 3 loops test 49 offsets and sample the ones inside a disk, plus one depth lookup. Replace .045 with .09 to double the out-of-focus radius; samples still ignore neighboring depth, so this does not fix foreground/background leakage.