1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| GLuint vbo; GLuint program; GLint positionLocation; GLint modelMatrixLocation; GLint viewMatrixLocation; GLint projectionMatrixLocation; GLint colorLocation; GLint texcoordLocation; GLint textureLocation; glm::mat4 modelMatrix, viewMatrix, projectionMatrix; GLuint texture; ... // 位置不是按照shader代码里写的变量的顺序确定的 positionLocation = glGetAttribLocation(program, "position"); colorLocation = glGetAttribLocation(program, "color"); texcoordLocation = glGetAttribLocation(program, "texcoord");
modelMatrixLocation = glGetUniformLocation(program, "ModelMatrix"); viewMatrixLocation = glGetUniformLocation(program, "ViewMatrix"); projectionMatrixLocation = glGetUniformLocation(program, "ProjectionMatrix"); textureLocation = glGetUniformLocation(program, "U_Texture");
...
glUseProgram(program); // 参数含义:插槽位置,几个矩阵(单插槽可以多矩阵),CPU传到GPU时是否需要转置,矩阵地址(从定义看是第一个数据的位置) glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(modelMatrix)); glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(viewMatrix)); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projectionMatrix));
// 使用纹理 glBindTexture(GL_TEXTURE_2D, texture); glUniform1i(textureLocation, 0);
glBindBuffer(GL_ARRAY_BUFFER, vbo); // attribute插槽中某一个位置生效 glEnableVertexAttribArray(positionLocation);
// GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* pointer // 插槽位置 , 插槽中数据有几个分量(现在的位置是4个,xyzw),分量类型, // 是否归一化(传入的如果不是float会变成float,e.g. 255,255,255,255→ 1.0,1.0,1.0,1.0) // 紧挨着的两个点起始地址相距多远,这个位置信息从vbo的什么地址开始取值(从0号位置开始取值) glVertexAttribPointer(positionLocation, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 10, 0);
// 给color变量赋值 glEnableVertexAttribArray(colorLocation); glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 10, (void*)(sizeof(float) * 4));
// 给texcoord赋值 glEnableVertexAttribArray(texcoordLocation); glVertexAttribPointer(texcoordLocation, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 10, (void*)(sizeof(float) * 8));
// 绘制什么,从第几个点开始绘制,绘制几个三角形。 glDrawArrays(GL_TRIANGLES, 0, 3);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glUseProgram(0);
|