shader中判断浮点型数值相等:round、floor

简介: shader中判断浮点型数值相等:round、floor

传递的顶点数据中vertices.z=1.0

网络异常,图片无法展示
|

使用gDebugger查看vbo中的数据z也是1.0

网络异常,图片无法展示
|

所有的顶点z都是一致的,当position.z=0、position.z=2时都正常,唯独position.z=1时异常

  • vertexes.shader
attribute vec2 a_position;
varying vec4 v_position;
void main(){
    v_position = a_position;
}
复制代码
  • fragment.shader
varying vec4 v_position;
void main(){
    float textureID = v_position.z;
     if(0.0 == textureID){
         // 正常
     }else if(1.0 == textureID){
         // 唯独这个1.0无法正常响应
     }ese if(2.0 == textureID){
         // 正常
     }
}
复制代码

为了防止是精度问题,特地转int,发现仍旧如此:

发现转int(z)后竟然等于0,可能这时的z是一个非常接近1的浮点数,比如:0.999999

varying vec4 v_position;
void main(){
    int textureID = int(v_position.z);
     if(0 == textureID){
         // 正常
     }else if(1 == textureID){
         // 唯独这个1.0无法正常响应
     }ese if(2 == textureID){
         // 正常
     }
}
复制代码

答案

使用round转int

varying vec4 v_position;
void main(){
    int textureID = round(v_position.z);
     if(0 == textureID){
         // 正常
     }else if(1 == textureID){
         // 唯独这个1.0无法正常响应
     }ese if(2 == textureID){
         // 正常
     }
}
复制代码

在某些环境中,round is undefined,可以使用floor(x+0.5)代替

shader函数

函数 说明
floor 返回小于等于x的最大整数
ceil 返回大于或等于输入值的最小整数。
degrees 弧度到角度的转换
fmod 返回a / b的浮点余数。
round 返回最接近于输入值的整数。
saturate 把输入值限制到[0, 1]之间。

注意事项

在round的官方文档中会看到关于类型的说明

genType round( genType x)
复制代码
  • genType对应的输入/输出参数可以是float,vec2,vec3或vec4。
  • genIType对应的输入/输出参数可以是int,ivec2,ivec3或ivec4。

举个例子:

int a = round(1.0); // 错误:Incompatible types in initialization (and no available implicit conversion)
float a = round(1.0); // 正确
复制代码


目录
相关文章
|
9月前
round() 函数:对一个数进行四舍五入
round() 函数:对一个数进行四舍五入
134 0
|
9月前
|
人工智能
PTA-找出整型数组中最大值的函数
找出整型数组中最大值的函数
179 0
|
JavaScript 前端开发 算法
JavaScript中toFixed、Math.round和四舍五入、银行家舍入法之间的关系
JavaScript 的 toFixed 方法使用定点表示法来格式化一个数值,数字.toFixed(要保留几位小数),参数为小数点后数字的个数,介于 0 到 20(包括)之间,默认 0,返回值为使用定点表示法表示给定数字的字符串,该数值在必要时进行四舍五入,不足位数时会直接用 0 来填充小数部分
450 0
51nod 1277 字符串中的最大值 (后缀数组求height[i])
51nod 1277 字符串中的最大值 (后缀数组求height[i])
73 0
|
C++
C++ 多种取整函数的使用和区别: ceil() floor() round() trunc() rint() nearbyint()
C++ 多种取整函数的使用和区别: ceil() floor() round() trunc() rint() nearbyint()
300 0
|
JavaScript
JS:数学计算Math相关四舍五入、向上取整、向下取整、取余、保留小数
JS:数学计算Math相关四舍五入、向上取整、向下取整、取余、保留小数
115 0
|
Python
Python浮点数转整数int、round、ceil、floor
Python浮点数转整数int、round、ceil、floor
384 0

热门文章

最新文章