在OpenGL着色器中的main之外进行计算是否合理? [英] Is it ever reasonable to do computations outside of main in an OpenGL shader?

查看:184
本文介绍了在OpenGL着色器中的main之外进行计算是否合理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些顶点着色器代码,如下所示(这是一些简化的示例):

I have some vertex shader code somewhat like the following (this is a bit of simplified example):

attribute vec2 aPosition;
attribute vec4 aColor;

varying lowp vec4 vColor;

uniform  vec4 uViewport;
mat4 viewportScale = mat4(2.0 / uViewport.z, 0, 0, 0,    0, -2.0 / uViewport.w, 0,0,    0, 0,1,0,    -1,+1,0,1);

void main() {
  vec2 pos = aPosition;
  gl_Position = viewportScale * vec4(pos, 0, 1);
  vColor = vec4(aColor.rgb*aColor.a, aColor.a);
}

尤其是,viewportScale矩阵是根据主函数外部的uViewport统一 计算出来的.从浏览器(WebGL)使用它,似乎在我测试过的每台机器上都可以正常工作……特别是,当我更改uViewport变量时,viewportScale矩阵会正确更新.这样做与在main函数内部进行相同的计算之间有什么区别吗?我找不到与此相关的任何示例或讨论.

In particular, the viewportScale matrix is calculated from the uViewport uniform outside of the main function. Using this from a browser (WebGL), it seems to work fine on every machine I've tested on... in particular, the viewportScale matrix is correctly updated when I change the uViewport variable. Is there any difference between doing this, and doing the same calculation inside of the main function? I can't find any examples or discussion related to this.

我遇到了相关问题,使我对此问题有些偏执-至少,我想了解发生了什么.

I ran into a related problem that has made me a bit paranoid about this issue -- at the very least, I'd like to understand what's going on.

推荐答案

这不是GLSL ES 1.00(与ES 2.0一起使用的GLSL版本)中的合法着色器. WebGL共享相同的GLSL定义,但WebGL规范中指定了一些例外.我在WebGL规范中找不到例外,因此我认为着色器在ES 2.0和WebGL中都是非法的.

This is not a legal shader in GLSL ES 1.00, which is the GLSL version that is used with ES 2.0. WebGL shares the same GLSL definition, with some exceptions specified in the WebGL spec. I can't find an exception for this in the WebGL spec, so I believe that the shader is illegal in both ES 2.0 and WebGL.

根据GLSL ES 1.00规范的第29页上的"4.3存储限定符"部分(添加了重点):

From the GLSL ES 1.00 spec, section "4.3 Storage Qualifiers" on page 29 (emphasis added):

不具有存储限定符或仅具有const限定符的全局声明可以包括初始化器,在这种情况下,它们将在执行main()的第一行之前进行初始化.此类初始化器必须是常量表达式.

第49页的"5.10常量表达式"一节定义了常量表达式是什么.它包括:

Section "5.10 Constant Expressions" on page 49 defines what a constant expression is. It includes:

在常量表达式中可能使用以下内容:

  • 制服,属性和变化形式.
  • Uniforms, attributes and varyings.

根据您的情况,表达式包含一个统一的表达式,这使其成为非恒定表达式.因此,它不能用作全局变量的初始化器.

The expression in your case includes a uniform, which makes it a non-constant expression. It can therefore not be used as the initializer of a global variable.

这篇关于在OpenGL着色器中的main之外进行计算是否合理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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