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?

  • 2
    \$\begingroup\$ There is an old article in the first GPU Gems book about shadow mapping (you can read it here: http.developer.nvidia.com/GPUGems/gpugems_ch12.html). 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. \$\endgroup\$
    – Benlitz
    Aug 11, 2012 at 13:30
  • 1
    \$\begingroup\$ Another resource that might be helpful is the article "Compact Normal Storage for Small G-Buffers" by Aras P from Unity ( aras-p.info/texts/CompactNormalStorage.html ). This article is limited to normals only. \$\endgroup\$ Aug 11, 2012 at 15:49
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – alariq
    Nov 14, 2013 at 20:05
  • \$\begingroup\$ @alariq yes the float extension is widely supported now. \$\endgroup\$
    – Will
    Nov 15, 2013 at 10:50
  • \$\begingroup\$ @Will If the float extension solved your problem, then post it as an answer and accept it. \$\endgroup\$
    – Polar
    Dec 12, 2013 at 17:59

1 Answer 1


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

  • \$\begingroup\$ Can you add the code snippets to your answer? If the site you mentioned goes down, the link will serve no good. \$\endgroup\$ Dec 12, 2018 at 17:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .