Problem with shader

Completely untested ofc, but I think you’ll get the idea, and hopefully, it actually helps :smiley:

Shadow (* marks the changes):

void main(void) {
  float distance = 1.0;
  //angle do not changed for one ray, changed only r(lenght)
// Calc this in vertex shader!
* float theta = (var_texcoord0.s*2.0 -1.0) * PI + mult_pi; 
  const float add = 1.0/resolution;
// Pre calc the step
* vec2 step = add * vec2(pos.x/pos.z,pos.y/pos.w);
  const float nsteps = resolution;
// uniform candidate
* vec2 pre_something = vec2(resolution/2.0/pos.z, resolution/2.0/pos.w);
  vec2 pre_coord = vec2(sin(theta)*pre_something.x,cos(theta)*pre_something.y);
  
  //coord which we will sample from occlude map
  vec2 coord = pre_coord;
  for (int i=0; i < nsteps; i++) {
    vec4 data = texture2D(TEX0, coord);
    //if we've hit an opaque fragment (occluder), then get new distance
    if (data.a > THRESHOLD) {
*       distance = i / resolution;
        break;
    }
// step
*   coord -= step;
  }
// reciprocal: up_scale.x = 1 / up_scale.x
* gl_FragColor = vec4(vec3(distance*up_scale.x), 1.0);
}

As for the blur, it’s advisable to move calculations to the vertex shader,
and let the sampler interpolate the (linear) values (texture coordinates) for you.
Personally, I use a separable blur (currently box), so I need to render twice, one for horizontal blur,
and one for vertical.
Plus when summing the samples, in my own example, I use lowp vec4 color = vec4(0.0);, since it’s a blur anyway :slight_smile:

Take aways:

  • Precompute as uniforms if possible
  • Precompute linear values in vertex shader,
    and you’ll get the interpolated value in the fragment shader
  • Move constants variables out of loops
  • Use multiplication instead of divs (gain varies on different GPU drivers)

Some further reading for those interested (quick googling):

Humus, an ex-colleague of ours, has written a good GDC presentation about optimizing shaders:
http://www.humus.name/index.php?page=Articles&ID=6

General GLSL advice:
https://www.khronos.org/opengl/wiki/GLSL_Optimizations

Some Apple notes:
https://developer.apple.com/library/content/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/BestPracticesforShaders/BestPracticesforShaders.html

Here’s my box blur

Let us know how it goes! :smiley:

6 Likes