Search code examples
game-physicsraytracing

What to do if color values go above 1?


I am working on a raytracer and when adding different colors like from lights, reflected and refracted light, I get values above 1 and then I need to clamp. But clamping is probably not correct? Maybe I should handle this in other way?


Solution

  • This is not an error, it's an effect called saturation, or maybe overexposure. It happens in film and digital cameras, and in your eye, as well. The issue is simply that you've got so much light energy reaching your photoreceptor (in the case of an eye, or CCD in a digital camera, or photosensitive compound in a film camera) that the receptor is saturated to it's maximum output value. In other words, you can keep dumping more energy into it, but the receptor won't be able to output any stronger signal, so it will look the same. So the simple solution is to simply saturate all color values at 1.0, which mimics what happens in a real photoreceptor.

    Of course, when this happens in your eye, your pupils constrict so not as much light gets in, and when a photographer has an overexposed shot, they might reduce the aperture, or the exposure time for the same reason. You can do the same in your renderer by simply dividing the color values at every pixel by a fixed amount. This is analogous to constricting the pupil or limiting the exposure time to reduce the amount of light energy that reaches each receptor. After doing so, you will still need to clamp any values that remain greater than 1 (or whatever your maximum color value is).

    Of course you can store very large numerical color values using double precision floating point, or arbitrarily large numerical values using BigInts, for instance. But sooner or later, you need to actually produce this image in "real life": via a printer, or on a monitor, or store it to a standard image format like PNG. Whatever mechanism you use, there will be a limited range of output values that can be produced, and you'll need to fit your colors into that range. You can use either technique I described for doing this: you can simply clamp anything outside the available range, or you can scale all the values by a fixed amount so that all the values fit into the range. In the former case, you will get clipping in the image, meaning you will loose detail anywhere the light is very bright. In the latter case, you will experience a loss of contrast where ever the color-values are already close together, because scaling them down will bring them even closer together. Generally, you will want to apply both techniques to limit the two different problems. You could attempt to analyze the statistics of the image and decide algorithmically how to adjust it, but I'm not really sure what that would look like. The alternative is to adjust it manually through trial and error (presumably with lower quality renderings so each trial doesn't take as long).