使用 ANGLE 时防止在着色器程序中展开循环

Prevent loop unrolling in shader program when using ANGLE

在我的 WEBGL 着色器中,我使用了未知长度的循环(在编译时)。

    do {
        sample = texture(uTex, posXY).a;
        accumulated += aSample * uAMultiplier;
    } while (accumulated < 0.8);

这在 OpenGL 浏览器上按预期工作,但默认情况下 windows chrome/ff 使用角度展开循环,这在这种情况下是不可能的,会导致编译错误。

Error: Error compiling generate
Error: Cannot link program
Info log:
C:\fakepath(110,28-106): error X4014: cannot have gradient operations inside loops with divergent flow control

C:\fakepath(59,12-96): warning X3570: gradient instruction used in a loop with varying iteration, forcing loop to unroll
C:\fakepath(118,1-82): error X3511: unable to unroll loop, loop does not appear to terminate in a timely manner (1024 iterations)

是否有解决方案来防止展开或以其他方式绕过必须循环?

您可以尝试声明一个带出口的静态循环。例如

float accumulated = 0.0;
#define ITERATION_LIMIT 100;
for (int i = 0; i < ITERATION_LIMIT; ++i) {
  sample = texture(uTex, posXY).a;
  accumulated += aSample * uAMultiplier;
  if (accumulated >= 0.8) {
    break;
  }
}

当然最好选择一个合理的限制数