Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to compose conventional triangle-based models and particles with a ray-traced scene at a reasonable frame-rate.

webGL does not let you write the gl_FragDepth in the fragment shader. You cannot have multiple render targets, but you can render to an RGBA texture and then use that texture as input to another draw-op. So I can render my ray-traced scene and store the depth as input to the next stage. This is obviously far from ideal, but workable.

I'd love to be wrong about this, and this is gathered from trial and error rather than any definitive source; please correct any flawed assumptions

How can you pack/unpack a float and, ideally, some flag bits and such, into an RGBA texture efficiently in a GLSL fragment shader?

share|improve this question
There is an old article in the first GPU Gems book about shadow mapping (you can read it here: It explains how to pack floats in an RGBA texture with two different ways. Look at section 12.3.3 for writing, then 12.3.6 for reading. – Benlitz Aug 11 '12 at 13:30
Another resource that might be helpful is the article "Compact Normal Storage for Small G-Buffers" by Aras P from Unity ( ). This article is limited to normals only. – Mortennobel Aug 11 '12 at 15:49
You may create R32F texture and just write your depth values there. without any packing unpacking. then during your second "conventional triangle-based" pass use this texture as a depth buffer (attached as depth to FBO). Feel free to ask more if this is not clear. – alariq Nov 14 '13 at 20:05
@alariq yes the float extension is widely supported now. – Will Nov 15 '13 at 10:50
@Will If the float extension solved your problem, then post it as an answer and accept it. – Polar Dec 12 '13 at 17:59

Here are pack and unpack functions that will work on WebGL and OpenGL ES 2.0, this is only for values in the 0...1 range so you should take care your depth calculation is in the correct space.

Encoding Floats to RGBA

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.