英文:
glsl vertex shader glGetUniformLocation return null
问题
大家好,我正在学习 WebGL,但无法获取特殊变量的位置。
以下是代码
顶点着色器
uniform vec2 u_translation;
attribute vec2 a_position;
uniform vec2 u_resolution;
void main() {
vec2 position = a_position + u_translation;
vec2 zeroToOne = a_position / u_resolution;
vec2 zeroToTwo = zeroToOne * 2.0;
vec2 clipSpace = zeroToTwo - 1.0;
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
}
片元着色器
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
var translationLocation = gl.getUniformLocation(program, "u_translation");
var positionLocation = gl.getAttribLocation(program, "a_position");
var resolutionLocation = gl.getUniformLocation(program, "u_resolution");
var colorLocation = gl.getUniformLocation(program, "u_color");
// translationLocation 为 null,但其他变量可以获取到
[查看图片描述](https://i.stack.imgur.com/6J6sc.png)
有人知道发生了什么吗?我认为我在着色器中使用了 'u_translation'
英文:
hello everyone i'm learning webgl and i can't get the location of the special variable
here is the code
vertex-shader
uniform vec2 u_translation;
attribute vec2 a_position;
uniform vec2 u_resolution;
void main() {
vec2 position = a_position + u_translation;
vec2 zeroToOne = a_position / u_resolution;
vec2 zeroToTwo = zeroToOne * 2.0;
vec2 clipSpace = zeroToTwo - 1.0;
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
}
fragment-shader
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
var translationLocation = gl.getUniformLocation(program, "u_translation");
var positionLocation = gl.getAttribLocation(program, "a_position");
var resolutionLocation = gl.getUniformLocation(program, "u_resolution");
var colorLocation = gl.getUniformLocation(program, "u_color");
// translationLocation is null but i can get the others
does any one know what happend? i think i used the 'u_translation' in the shader
答案1
得分: 0
本地变量 `position` 在着色器中未被使用,因此不需要 `u_translation` 并且被优化掉。因此它不会成为一个活动的程序资源,也不会得到统一位置。可能以下行错误:
>```glsl
>vec2 zeroToOne = a_position / u_resolution;
>```
但应该是:
```glsl
vec2 zeroToOne = position / u_resolution;
现在本地变量 position
在着色器程序中被使用,因此 u_translation
成为一个活动的程序资源。
<details>
<summary>英文:</summary>
The local variable `position` is not used anywhere in the shader and thus `u_translation` is not needed and optimized out. So it does not become an active program resource and does not get a uniform location. Likely the following line is wrong
>```glsl
>vec2 zeroToOne = a_position / u_resolution;
>```
but should be
```glsl
vec2 zeroToOne = position / u_resolution;
Now the local variable position
is used in the shader program and thus u_translation
becomes an active program resource.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论