flb

bokeh.frag

flb
Dec 3rd, 2019
852
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Simulate bokeh blur
  3.  
  4. The author disclaims copyright to this source code
  5.  
  6. Live preview available at: https://www.shadertoy.com/view/WdVSWd
  7. */
  8.  
  9. in vec2 UV;
  10. out vec4 Color;
  11.  
  12. uniform sampler2D Texture;
  13. uniform float Radius;
  14. uniform vec2 Size;
  15.  
  16. const float GoldenAngle = 2.39996323;
  17.  
  18. // bigger is better quality
  19. const float Iterations = 400.0;
  20.  
  21. const mat2 Rotation = mat2(
  22.     cos(GoldenAngle),
  23.     sin(GoldenAngle),
  24.    -sin(GoldenAngle),
  25.     cos(GoldenAngle)
  26. );
  27.  
  28. const float ContrastAmount = 150.0;
  29. const vec3 ContrastFactor = vec3(9.0);
  30. const float Smooth = 2.0;
  31.  
  32. ///////////
  33. /*
  34.     calculates circle of confusion diameter for each fixel from physical parameters and depth map
  35.  
  36.     this function is unused
  37.  
  38.     see http://ivizlab.sfu.ca/papers/cgf2012.pdf, page 10
  39. */
  40. float blurRadius(
  41.     float A, // aperture
  42.     float f, // focal length
  43.     float S1, // focal distance
  44.     float far, // far clipping plane
  45.     float maxCoc, // mac coc diameter
  46.    
  47.     vec2 uv,
  48.     sampler2D depthMap)
  49. {
  50.     vec4 currentPixel = texture(depthMap, uv);
  51.    
  52.     float S2 = currentPixel.r * far;
  53.    
  54.     //https://en.wikipedia.org/wiki/Circle_of_confusion
  55.     float coc = A * ( abs(S2 - S1) / S2 ) * ( f / (S1 - f) );
  56.    
  57.     float sensorHeight = 0.024; // 24mm
  58.    
  59.     float percentOfSensor = coc / sensorHeight;
  60.    
  61.     // blur factor
  62.     return clamp(percentOfSensor, 0.0f, maxCoc);
  63. }
  64. ///////////
  65.  
  66. vec3 bokeh(sampler2D tex, vec2 uv, float radius) {
  67.     vec3 num, // numerator
  68.          weight;
  69.    
  70.     float rec = 1.0; // reciprocal
  71.    
  72.     vec2 horizontalAngle = vec2(0.0, radius * 0.01 / sqrt(Iterations));
  73.    
  74.     for (float i; i < Iterations; i++) {
  75.         rec += 1.0 / rec;
  76.        
  77.         horizontalAngle = horizontalAngle * Rotation;
  78.        
  79.         vec2 offset = (rec - 1.0) * horizontalAngle;
  80.        
  81.         vec2 aspect = vec2(Size.y / Size.x, 1.0);
  82.        
  83.         vec2 sampleUV = uv + aspect * offset;
  84.        
  85.         vec3 col = texture(tex, sampleUV).rgb;
  86.        
  87.         // increase contrast and smooth
  88.         vec3 bokeh = Smooth + pow(col, ContrastFactor) * ContrastAmount;
  89.        
  90.         num += col * bokeh;
  91.         weight += bokeh;
  92.     }
  93.     return num / weight;
  94. }
  95.  
  96. void main() {
  97.     Color.rgb = bokeh(Texture, UV, Radius);
  98.     Color.a = 1.0;
  99. }
RAW Paste Data