GLuint viewRenderbuffer,viewFramebuffer; //兩個無符號整形代表opengles的幀緩衝區和渲染緩衝區
GLuint depthRenderbuffer //代表opengles的深度緩衝區
渲染緩衝區是渲染這一幀所在的位置,渲染之後就被複制到CAEAGLLayer的後臺緩衝區中,然後顯示在屏幕上。(後臺緩衝區不解釋)
深度緩衝區比較難,基本就是爲了解決物體前後遮擋問題,以後再說。
下面是創建幀緩衝區和渲染緩衝區的代碼,放到了一個方法中
- (BOOL)createFramebuffer
{
glGenFramebuffersOES(1, &viewFramebuffer);
glGenRenderbuffersOES(1, &viewRenderbuffer);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDrawable>)self.layer];
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
return NO;
}
return YES;
}
首先生成幀緩衝和渲染緩衝區,然後綁定幀緩衝和渲染緩衝區。再取得幀緩衝和渲染緩衝區的寬度和長度,以待以後使用。
下面代碼第一句就是設置視口。然後去的投影矩陣,把矩陣設爲單位矩陣,然後設置投影矩陣。
glclearcolor()設置背景顏色。
glvertexpointer()用數組生成定點。
glenableclientstate()允許程序用數組生成頂點,用數組生成紋理座標。
glViewport(0, 0, backingWidth, backingHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(-1.0f, 1.0f, -1.5f, 1.5f, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
// Clears the view with black
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Sets up pointers and enables states needed for using vertex arrays and textures
glVertexPointer(2, GL_FLOAT, 0, spriteVertices);
glEnableClientState(GL_VERTEX_ARRAY);
glTexCoordPointer(2, GL_SHORT, 0, spriteTexcoords);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
下面是生成紋理數據的代碼,opengles只接收數據塊,要把圖像轉成數據塊拷入opengles內。spriteData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));
glGenTextures(1, &spriteTexture);
// Bind the texture name.
glBindTexture(GL_TEXTURE_2D, spriteTexture);
// Set the texture parameters to use a minifying filter and a linear filer (weighted average)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// Specify a 2D texture image, providing the a pointer to the image data in memory
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData);
// Release the image data
free(spriteData);
// Enable use of the texture
glEnable(GL_TEXTURE_2D);
// Set a blending function to use
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// Enable blending
glEnable(GL_BLEND);
生成紋理,綁定紋理,設置紋理大小座標已經生成方法。別忘記釋放數據塊,以免內存泄露啊。