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

问题描述

这个问题与这里的问题非常相关().

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种情况.其他包装/拆包都可以通过这两种方法进行处理.

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(zeroToOne, 256.0), zeroToOne / 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(zeroToOne, 256.0), mod(zeroToOne / 256.0, 256.0), zeroToOne / 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之间转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 16:14