【问题标题】:How to make visible uniform variable in both shaders?如何在两个着色器中制作可见的统一变量?
【发布时间】:2016-10-10 17:23:45
【问题描述】:

我在顶点着色器“uIsTeapot”中有变量。

uniform float uIsTeapot;

顶点着色器可以很好地使用它,但片段着色器看不到它。如果我使用

if (uIsTeapot == 0.0) 

然后发生错误

"uIsTeapot": undeclared identifier

但我在顶点着色器中定义了它。如果我将两个着色器中的 uIsTeapot 定义为统一,那么程序会说“无法初始化着色器”,因为程序没有通过验证

if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
        alert("Could not initialise shaders");
}

编辑: 我将 mediump 添加到变量中,现在程序编译没有错误,但结果是屏幕上的一个对象,但我绘制了两个对象。

顶点着色器

attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;

attribute vec4 aVertexColor;

uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat3 uNMatrix;

uniform vec3 uAmbientColor;
uniform vec3 uPointLightingLocation;
uniform vec3 uPointLightingColor;

uniform mediump float uIsTeapot;
//varying float vIsTeapot;

varying vec2 vTextureCoord;
varying vec3 vLightWeighting;

varying vec4 vColor;

void main(void) {

    if (uIsTeapot == 1.0) {
        vec4 mvPosition = uMVMatrix * vec4(aVertexPosition, 1.0);
        gl_Position = uPMatrix * mvPosition;

        vec3 lightDirection = normalize(uPointLightingLocation - mvPosition.xyz);
        vec3 transformedNormal = uNMatrix * aVertexNormal;
        float directionalLightWeighting = max(dot(transformedNormal, lightDirection), 0.0);
        directionalLightWeighting = 100.0;
        vLightWeighting = uAmbientColor + uPointLightingColor * directionalLightWeighting;
        vTextureCoord = aTextureCoord;
    }
    if (uIsTeapot == 0.0) {
        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
        vColor = aVertexColor;
    } }

片段着色器

precision mediump float;

varying vec2 vTextureCoord;
varying vec3 vLightWeighting;

varying vec4 vColor;

uniform sampler2D uSampler;

uniform mediump float uIsTeapot;
//varying float vIsTeapot;

void main(void) {

    if (uIsTeapot == 1.0) {
        vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
        gl_FragColor = vec4(textureColor.rgb * vLightWeighting, textureColor.a);
    } else {
        gl_FragColor = vColor;
    }


}

【问题讨论】:

标签: opengl-es webgl shader fragment-shader vertex-shader


【解决方案1】:

您需要在两个着色器中以相同的精度声明它。

什么意思:

然后程序不能正常工作。

【讨论】:

  • “initShaders”部分出错
  • 我添加了一些有问题的信息
【解决方案2】:

你能发布你的顶点着色器和片段着色器吗?我怀疑您依赖的是默认精度,很可能您在顶点着色器中使用 highp,在片段着色器中使用 mediump

尝试使用:

uniform mediump float uIsTeapot;

...在顶点着色器和片段着色器中。

【讨论】:

  • 谢谢,initShaders 中的错误消失了,但屏幕上只有一个对象,尽管我绘制了两个对象。你知道为什么只有一个对象吗?
  • @Log 如果这是正确的答案,也许你可以接受 :)
  • @zhangxaochen 5年后不记得了)
猜你喜欢
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
相关资源
最近更新 更多