如何在 GLSL 中绑定统一位置?

How do I bind uniform locations in GLSL?

我正在尝试将统一变量绑定到某个位置,但我目前不知道如何:

要绑定属性(例如vertex/normal数据),我使用以下代码:

Override
protected void bindAttributes() {
    super.bindAttribute(1, "position");
    super.bindAttribute(2, "textureCoords");
    super.bindAttribute(3, "normal");
}
protected void bindAttribute(int attribute, String variableName){
    GL20.glBindAttribLocation(programID, attribute, variableName);
}

我想对统一变量做同样的事情。

目前,我正在获取这样的自动分配位置:

public int location_transformationMatrix;
public int location_lightPosition;
public int location_lightColour;

@Override
public void getAllUniformLocations(){
    location_transformationMatrix = super.getUniformLocation("transformationMatrix");
    location_lightPosition = super.getUniformLocation("lightPosition");
    location_lightColour = super.getUniformLocation("lightColour");
}

但是,由于我随后绑定了属性,这充其量会导致光照和法线等数据丢失,最坏的情况是,对于大约 60% 的尝试这样做的人来说,游戏会崩溃播放它。

从 OpenGL 4.3 开始,可以使用布局限定符设置着色器制服:

layout(location = 2) uniform mat4 modelToWorldMatrix;
例如,

会将制服 modelToWorldMatrix 的位置 n 绑定到位置 2。有关详细信息,请查看 here

4.3 之前(或者更确切地说没有 ARB_explicit_uniform_location 扩展)没有办法修复制服位置。