在学习OpenGLES时遇到一个概念,索引缓存。网上查资料大部分代码均是针对安卓或者桌面平台的,而且大部分的代码拷贝下来不能达到效果。经过几天的努力,终于了解了索引绘图的概念,所谓索引绘图是一种在绘制大网格(mesh)时的一种可以高效绘图的一种方式,普通的绘制三角形需要为每个三角形在array_buffer里面分配三个顶点的位置,每个顶点至少需要sizeof(glfloat)*3的内存,其实在网格里面很多顶点都是共享的,也就是说不需要为重复的顶点再分配内存,需要找到一种方法为gpu指定绘图时绘制哪一个点,这就是索引绘图的用处。使用索引绘图,array_buffer里面的顶点会默认的根据顶点在顶点数组里面的位置设置索引,,我们在绘图之前指定gpu绘图的索引顺序,当绘图时调用gldrawelement(),gpu就可以按照我们指定的顶点顺序绘图.下面是代码片段,简单的设置ViewController为GLKViewController并且设置self.view为GLKView就可以运行
GLKView *view = (GLKView *)self.view;
NSAssert([view isKindOfClass:[GLKView class]],
@"View controller's view is not a GLKView");
// Create an OpenGL ES 2.0 context and provide it to the
// view
view.context = [[EAGLContext alloc]
initWithAPI:kEAGLRenderingAPIOpenGLES2];
// Make the new context current
[EAGLContext setCurrentContext:view.context];
// Create a base effect that provides standard OpenGL ES 2.0
// Shading Language programs and set constants to be used for
// all subsequent rendering
self.baseEffect = [[GLKBaseEffect alloc] init];
self.baseEffect.useConstantColor = GL_TRUE;
self.baseEffect.constantColor = GLKVector4Make(
1.0f, // Red
1.0f, // Green
1.0f, // Blue
1.0f);// Alpha
// Set the background color stored in the current context
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // background color
// Generate, bind, and initialize contents of a buffer to be
// stored in GPU memory
glGenBuffers(1, // STEP 1
&vertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, // STEP 2
vertexBufferID);
glBufferData( // STEP 3
GL_ARRAY_BUFFER, // Initialize buffer contents
sizeof(vertices), // Number of bytes to copy
vertices, // Address of bytes to copy
GL_STATIC_DRAW); // Hint: cache in GPU memory
GLuint index;
glGenBuffers(1, &index);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexs), indexs, GL_STATIC_DRAW);