想要将OpenGL 1.1代码转换为OpenGL 2.0。
我使用Cocos2d v2.0(构建2D游戏的框架)
答案 0 :(得分:2)
首先,您必须将着色器放入您的程序中。您可以将着色器代码直接复制到const char *中,就像我在下面显示的那样,或者您可以在运行时从文件中加载着色器,这取决于您正在开发的平台,因此我不会显示如何执行此操作。
const char *vertexShader = "... Vertex Shader source ...";
const char *fragmentShader = "... Fragment Shader source ...";
为顶点着色器和片段着色器创建着色器并存储其ID:
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
在这里,您可以使用您复制粘贴到const char *或从文件加载的数据填充刚创建的着色器:
glShaderSource(vertexShader, 1, &vertexShader, NULL);
glShaderSource(fragmentShader, 1, &fragmentShader, NULL);
然后你告诉程序编译你的着色器:
glCompileShader(vertexShader);
glCompileShader(fragmentShader);
创建一个着色器程序,它是来自OpenGL的着色器的接口:
shaderProgram = glCreateProgram();
将着色器附加到着色器程序:
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
将着色器程序链接到您的程序:
glLinkProgram(shaderProgram);
告诉OpenGL您想要使用您创建的着色器程序:
glUseProgram(shaderProgram);
顶点着色器:
attribute vec4 a_Position; // Attribute is data send with each vertex. Position
attribute vec2 a_TexCoord; // and texture coordinates is the example here
uniform mat4 u_ModelViewProjMatrix; // This is sent from within your program
varying mediump vec2 v_TexCoord; // varying means it is passed to next shader
void main()
{
// Multiply the model view projection matrix with the vertex position
gl_Position = u_ModelViewProjMatrix* a_Position;
v_TexCoord = a_TexCoord; // Send texture coordinate data to fragment shader.
}
片段着色器:
precision mediump float; // Mandatory OpenGL ES float precision
varying vec2 v_TexCoord; // Sent in from Vertex Shader
uniform sampler2D u_Texture; // The texture to use sent from within your program.
void main()
{
// The pixel colors are set to the texture according to texture coordinates.
gl_FragColor = texture2D(u_Texture, v_TexCoord);
}