7 变量类型
着色程序中常用的变量是uniform,attribute变量。
uniform的值只能被图元修改,不能在glBegin / glEnd 间被修改。这意味着uniform不能用作顶点属性,uniform适用于在图元, 桢, 或整个scene都不变的量。uniform变量能在顶点和片断着色器中读。
attribute可以为顶点赋值。attribute在任何时候都可以被更新。只能用于用于顶点着色器,不能用于片断着色器。
7.1 uniform变量的应用:
下面是着色器中的定义的变量:
uniform float specIntensity;
uniform vec4 specColor;
uniform float t[2];
uniform vec4 colors[3];
下面是opengl中的代码部分:
GLint loc1,loc2,loc3,loc4;
float specIntensity = 0.98;
float sc[4] = {0.8,0.8,0.8,1.0};
float threshold[2] = {0.5,0.25};
float colors[12] = {0.4,0.4,0.8,1.0,
0.2,0.2,0.4,1.0,
0.1,0.1,0.1,1.0};
loc1 = glGetUniformLocation(p,"specIntensity");/*给着色程序传值*/
glUniform(loc1,specIntensity);
loc2 = glGetUniformLocation(p,"specColor");
glUniform4fv(loc2,1,sc);/*1*4=4,1必须是着色器中声明的值*/
/*或者是:
loc2 = glGetUniformLocation(p,"specColor");
glUniform(loc2,sc[0],sc[1],sc[2],sc[3]);
*/
loc3 = glGetUniformLocation(p,"t");
glUniform1fv(loc3,2,threshold);/*2必须是着色器中声明的值*/
loc4 = glGetUniformLocation(p,"colors");
glUniform4fv(loc4,3,colors);/*3*4=12,3必须是着色器中声明的值*/
注意:
GLint glUniform{1,2,3,4}f(GLint location, GLsizei count, GLfloat *v); 是用浮点数赋值
GLint glUniform{1,2,3,4}fv(GLint location, GLsizei count, GLfloat *v); 用浮点数组赋值
7.2 attribute变量的应用:
glBegin(GL_TRIANGLE_STRIP);
glVertexAttrib(loc,2.0);
glVertex(-1,1);
glVertexAttrib(loc,2.0);
glVertex(1,1);
glVertexAttrib(loc,-2.0);
glVertex(-1,-1);
glVertexAttrib(loc,-2.0);
glVertex(1,-1);
glEnd();
下面是着色器中的定义的变量:
attribute float height;
下面是opengl中的代码部分:
loc = glGetAttribLocation(p,"height");
..........................
glBegin(GL_TRIANGLE_STRIP);
glVertexAttrib(loc,2.0);
glVertex(-1,1);
glVertexAttrib(loc,2.0);
glVertex(1,1);
glVertexAttrib(loc,-2.0);
glVertex(-1,-1);
glVertexAttrib(loc,-2.0);
glVertex(1,-1);
glEnd();
使用数组:
float vertices[8] = {-1,1, 1,1, -1,-1, 1,-1};
float heights[4] = {2,2,-2,-2};
...
loc = glGetAttribLocationARB(p,"height");
glEnableClientState(GL_VERTEX_ARRAY);
glEnableVertexAttribArrayARB(loc);
glVertexPointer(2,GL_FLOAT,0,vertices);
glVertexAttribPointerARB(loc,1,GL_FLOAT,0,0,heights);