Saturday 31 August 2013

Divide by zero

Sometimes you will run into "divide by zero" error. To avoid this, you can:

float ss = s/txscale;
float tt = t/txscale;

//return a value either 0.00001 or greater)
float scaler = max(1/txscale, 0.00001);

float ss = s * scaler;
float tt = s * scaler;

As you develop your shaders, you will sometimes need to use a certain value within your shaders, but that value would make no sense at all as a shader parameter. One such example is when you are scaling a texture. Remember that texture spaces (s, t) are usually within the 0 to 1 range. To scale the texture, you could take a shader input txscaleand divide by the s or t value.

The problem with this approach is that you will run into a “divide by zero” error when the texture coordinate is 0 (you can’t divide a value by 0). The following code will more than likely generate rendering errors:
float ss = s/txscale;
float tt = t/txscale;


To get around this problem, we will invert our approach and add the logic to avoid division by zero. To do this, we will multiply the sand tvalues by 1/txscale. What this does is scale down the texture coordinates, resulting in the texture scaling up.

To prevent division by zero, we will use the max()shadeop to restrict the value to drop below a very small number. Here is the modified code.
float scaler = max(1/txscale,0.000001);
float ss = s * scaler;
float tt = t * scaler;

No comments:

Post a Comment