Packing float into vec4 - how does this code work?

∥☆過路亽.° 提交于 2019-11-27 20:08:44

It's not storing a GLSL float in a GLSL vec4. What it's doing is storing a value in a vec4 which, when written to an RGBA8 framebuffer (32-bit value) can be read as a vec4 and then reconstituted into the same float that was given previously.

If you did what you suggest, just writing the floating-point value to the red channel of the framebuffer, you'd only get 8 bits of accuracy. With this method, you get all 32-bits working for you.

In addition to the answer above, you might be interested in the floating point texture extension described here:

http://www.khronos.org/registry/webgl/extensions/OES_texture_float/

Note that there are hardware/software setups out there where this extension doesn't exist/run, but if it do it sure is a good extension. My experience is that it's fast as well. If you use this, you can use the remaining three channels to store other information, such as color from a projected texture.

If you're interested into the nitty-gritty details of how these routines work I suggest you to read my blog post. I'm adding some details here on how that code works and to address some possible use cases.

As you probably figured out, that code is encoding a normalized float value to a vec4. OpenGL ES 2.0 or WebGL (at the time of writing), might make use of those pack/unpack routines to provide 32 bit precision floating points via RGBA8 textures (more on this in the spec).

Even with the extension posted by Mikael (OES_texture_float) it might be necessary (for debugging purposes for instance) to dump full 32 bit precision normalized floating points and as described in the spec readPixels is currently limited by the following

Only two combinations of format and type are accepted. The first is format RGBA and type UNSIGNED_BYTE. The second is an implementation-chosen format.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!