如何在 GLSL (WebGL) 中将 int 转换为 float?

How to cast int to float in GLSL (WebGL)?

我的代码是(在 void main 里面):

float res;

for(int i=0; i<15; i++) {

    res = float(i)/15.0;

    //...

}

不幸的是,我在 float(i)/15.0

处遇到语法错误

如果我只写i/15.0,那么错误就是:

wrong operand types  no operation '/' exists that takes a left-hand operand of type 'mediump int' and a right operand of type 'const float' (or there is no acceptable conversion)

如果我只是尝试 i/15 那么结果是一个整数,但我想要一个浮点数。

如何将 int 转换为 float

It seems that you're not allowed to cast in GLSL. Therefore, "you have to use a constructor".

试试这个:

// http://www.shaderific.com/glsl-types/
// "Implicit type conversions are not supported.
// Type conversions can be done using constructors..."
float i_float = float(i);
res = i_float / 15.0;

PS:如果你看一下at the documentation,它说”...任何一种整数类型都可以转换成浮点数,和整数并且浮点数可以转换为双精度数。“ ...我觉得你的代码不被 GLSL 编译器接受很奇怪。(参见 Reto Koradi 的评论)