How to deal with NaN or inf in OpenGL ES 2.0 shade

2019-07-04 16:40发布

问题:

This is based on the question: Best way to detect NaN's in OpenGL shaders

Standard GLSL defines isnan() and isinf() functions for detection. OpenGL ES 2.0 shading language doesn't. How can I deal with NaNs and Infs nevertheless?

回答1:

You can check for NaN via a condition that will only be true for NaN:

bool isNan(float val)
{
  return (val <= 0.0 || 0.0 <= val) ? false : true;
}

isinf is a bit more difficult. There is no mechanism to convert the float into its integer representation and play with the bits. So you'll have to compare it against a suitably large number.



回答2:

Same problem for WebGL. Answer of Nicol Bolas works good for most GPUs but does not for some nVidias. This version works good for all GPUs I had an opportunity to try:

bool isNan( float val )
{
  return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;
  // important: some nVidias failed to cope with version below.
  // Probably wrong optimization.
  /*return ( val <= 0.0 || 0.0 <= val ) ? false : true;*/
}


回答3:

Untested, so not sure this will work (due to optimizations), but it should work, both for Inf and -Inf.

  bool isinf(float val) {
    return (val != 0.0 && val * 2.0 == val) ? true : false;
  }