着色器着色

时间:2012-06-02 12:07:34

标签: ios opengl-es opengl-es-2.0

我在XCode OpenGL ES模板上创建了一个项目。

有没有办法为每个对象自定义着色器颜色?

Shader.vsh:

attribute vec4 position;
attribute vec3 normal;

varying lowp vec4 colorVarying;

uniform mat4 modelViewProjectionMatrix;
uniform mat3 normalMatrix;

void main()
{
    vec3 eyeNormal = normalize(normalMatrix * normal);
    vec3 lightPosition = vec3(1.0, 1.0, 1.0);
    vec4 diffuseColor = vec4(1, 0.4, 1.0, 1.0);

    float nDotVP = max(0.0, dot(eyeNormal, normalize(lightPosition)));

    colorVarying = diffuseColor * nDotVP;

    gl_Position = modelViewProjectionMatrix * position;
}

Shader.fsh:

varying lowp vec4 colorVarying;

void main()
{
    gl_FragColor = colorVarying;
}

我是否需要在Shader.vsh中创建一个额外属性来解析颜色以替换diffuse变量或者这是如何完成的?

1 个答案:

答案 0 :(得分:1)

我建议使用颜色的统一变量

// put this in Shader.vsh, before the main()
uniform vec4 diffuseColor;

并在代码中设置值:

glUseProgram(progID);

// object 1 (R, G, B, A is a color)
glUniform4f(glGetUniformLocation(progID, "diffuseColor"), R, G, B, A);
draw_object_1();

// object 2 (R, G, B, A is a color)
glUniform4f(glGetUniformLocation(progID, "diffuseColor"), R, G, B, A);
draw_object_2();

同样可以通过灯光位置来完成。