如何在 float 和 vec4、vec3、vec2 之间转换? [英] How do I convert between float and vec4,vec3,vec2?

查看:54
本文介绍了如何在 float 和 vec4、vec3、vec2 之间转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题和这里的问题非常相关(如何将 vec4 rgba 值转换为浮点数?).

This question is very related to the question here(How do I convert a vec4 rgba value to a float?).

已经有一些与此问题相关的文章或问题,但我想知道大多数文章都没有确定哪种类型的浮动值.只要我能想出,下面有一些浮点值打包/解包公式.

There is some of articles or questions related to this question already, but I wonder most of articles are not identifying which type of floating value. As long as I can come up with, there is some of floating value packing/unpacking formula below.

  • 无符号归一化浮点数
  • 有符号归一化浮点数
  • 有符号范围浮点(我能找到范围限制的浮点值)
  • 无符号范围浮点数
  • 无符号浮点数
  • 有符号浮点数

但是,这些实际上只是 2 个案例.其他打包/拆包都可以通过这2种方式处理.

However, these are just 2 case actually. The other packing/unpacking can be processed by these 2 method.

  • 无符号范围浮点数(我可以通过简单的位移来打包/解包)
  • 有符号浮点数

我还想将带符号的浮点值打包和解包到 vec3 或 vec2 中.

I want to pack and unpack signed floating values into vec3 or vec2 also.

对于我的情况,浮点值并不能保证被归一化,所以我不能使用简单的位移方式.

For my case, the floating value is not ensured to be normalized, so I can not use the simple bitshifting way.

推荐答案

如果您知道要存储的值的最大范围,例如 +5 到 -5,那么最简单的方法就是选择一些将该范围转换为一个从 0 到 1 的值.将其扩展为您拥有的位数,然后将其分成几部分.

If you know the max range of values you want to store, say +5 to -5, than the easiest way is just to pick some convert that range to a value from 0 to 1. Expand that to the number of bits you have and then break it into parts.

vec2 packFloatInto8BitVec2(float v, float min, float max) {
   float zeroToOne = (v - min) / (max - min);
   float zeroTo16Bit = zeroToOne * 256.0 * 255.0;
   return vec2(mod(zeroTo16Bit, 256.0), zeroTo16Bit / 256.0);
}

要放回去,你做相反的事情.组装零件,除以返回到 zeroToOne 值,然后按范围扩展.

To put it back you do the opposite. Assemble the parts, divide to get back to a zeroToOne value, then expand by the range.

float unpack8BitVec2IntoFloat(vec2 v, float min, float max) {
   float zeroTo16Bit = v.x + v.y * 256.0;
   float zeroToOne = zeroTo16Bit / 256.0 / 255.0;
   return zeroToOne * (max - min) + min;
}

对于 vec3,只需扩展它

For vec3 just expand it

vec3 packFloatInto8BitVec3(float v, float min, float max) {
   float zeroToOne = (v - min) / (max - min);
   float zeroTo24Bit = zeroToOne * 256.0 * 256.0 * 255.0;
   return vec3(mod(zeroTo24Bit, 256.0), mod(zeroTo24Bit / 256.0, 256.0), zeroTo24Bit / 256.0 / 256.0);
}

float unpack8BitVec3IntoFloat(vec3 v, float min, float max) {
   float zeroTo24Bit = v.x + v.y * 256.0 + v.z * 256.0 * 256.0;
   float zeroToOne = zeroTo24Bit / 256.0 / 256.0 / 256.0;
   return zeroToOne * (max - min) + min;
}

这篇关于如何在 float 和 vec4、vec3、vec2 之间转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆