【发布时间】:2012-04-19 17:13:51
【问题描述】:
想要将 OpenGL 1.1 代码转换为 OpenGL 2.0。
我使用的是 Cocos2d v2.0(构建 2D 游戏的框架)
【问题讨论】:
-
你需要绑定着色器来绘制一些东西。如果没有着色器,将不会绘制任何内容。
标签: iphone opengl-es cocos2d-iphone opengl-es-2.0
想要将 OpenGL 1.1 代码转换为 OpenGL 2.0。
我使用的是 Cocos2d v2.0(构建 2D 游戏的框架)
【问题讨论】:
标签: iphone opengl-es cocos2d-iphone opengl-es-2.0
首先,您必须将着色器放入您的程序中。您可以将着色器代码直接复制到 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);
}
【讨论】: