How do I convert a vec4 rgba value to a float?

后端 未结 5 1750
遇见更好的自我
遇见更好的自我 2020-12-03 15:29

I packed some float data in a texture as an unsigned_byte, my only option in webgl. Now I would like unpack it in the vertex shader. When I sample a pixel I get a vec4 whi

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 16:07

    You won't be able to just interpret the 4 unsigned bytes as the bits of a float value (which I assume you want) in a shader (at least not in GLES or WebGL, I think). What you can do is not store the float's bit representation in the 4 ubytes, but the bits of the mantissa (or the fixed point representation). For this you need to know the approximate range of the floats (I'll assume [0,1] here for simplicity, otherwise you have to scale differently, of course):

    r = clamp(int(2^8 * f), 0, 255);
    g = clamp(int(2^16 * f), 0, 255);
    b = clamp(int(2^24 * f), 0, 255);     //only have 24 bits of precision anyway
    

    Of course you can also work directly with the mantissa bits. And then in the shader you can just reconstruct it that way, using the fact that the components of the vec4 are all in [0,1]:

    f = (v.r) + (v.g / 2^8) + (v.b / 2^16);
    

    Although I'm not sure if this will result in the exact same value, the powers of two should help a bit there.

提交回复
热议问题