1. import GLKit/GLKit.h
ViewContrllor 继承自 GLKViewController
storyboard view 类 GLKView
2、
//1. OpenGLES上下文
{
self.mContext= [[EAGLContextalloc]initWithAPI:kEAGLRenderingAPIOpenGLES2];
GLKView* view = (GLKView*)self.view;//Storybord里设置view类glkview
view.context=self.mContext;
view.drawableColorFormat=GLKViewDrawableColorFormatRGBA8888;//颜色缓冲器格式
//view.drawableDepthFormat = GLKViewDrawableDepthFormat24; //模板缓冲区格式
[EAGLContextsetCurrentContext:self.mContext];
}
//2.
//顶点数据,前三个是顶点坐标,后面两个是纹理坐标,每行一个顶点
//顶点坐标xyz,中心- 0,0, 0,OpenGLES的世界坐标系是[-1, 1],
//纹理坐标左下角0,0
GLfloatsquareVertexData[] = {
0.5, -0.5,0.0f,1.0f,0.0f,//右下
-0.5,0.25,0.0f,0.0f,1.0f,//左上
-0.5, -0.35,0.0f,0.0f,0.0f,//左下
0.5,0.5, -0.0f,1.0f,1.0f,//右上
};
//顶点索引
//索引数组是顶点数组的索引,把squareVertexData数组看成4个顶点,每个顶点会有5个GLfloat数据,索引从0开始。
GLuintindices[] = {
0,1,2,
1,3,0
};
self.mCount=sizeof(indices) /sizeof(GLuint);
//3、顶点数据缓存
/**
glGenBuffers申请一个标识符
glBindBuffer把标识符绑定到GL_ARRAY_BUFFER上
glBufferData把顶点数据从cpu内存复制到gpu内存
glEnableVertexAttribArray是开启对应的顶点属性
glVertexAttribPointer设置合适的格式从buffer里面读取数据
*/
//-(void)vertexBuffer
{
//定点数据缓存
GLuintbuffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER,sizeof(squareVertexData), squareVertexData,GL_STATIC_DRAW);
GLuintindex;
glGenBuffers(1, &index);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices), indices,GL_STATIC_DRAW);
glEnableVertexAttribArray(GLKVertexAttribPosition);//顶点数据缓存
glVertexAttribPointer(GLKVertexAttribPosition,3,GL_FLOAT,GL_FALSE,sizeof(GLfloat) *5, (GLfloat*)NULL+0);
glEnableVertexAttribArray(GLKVertexAttribTexCoord0);//纹理
glVertexAttribPointer(GLKVertexAttribTexCoord0,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat) *5, (GLfloat*)NULL+3);
}
//4、纹理贴图
/**
GLKTextureLoader读取图片,创建纹理GLKTextureInfo
创建着色器GLKBaseEffect,把纹理赋值给着色器
*/
//- (void)textureLoader
{
NSString* filePath = [[NSBundlemainBundle]pathForResource:@"Untitled"ofType:@"png"];
NSDictionary* options = [NSDictionarydictionaryWithObjectsAndKeys:@(1),GLKTextureLoaderOriginBottomLeft,nil];
////GLKTextureLoaderOriginBottomLeft纹理坐标系是相反的
GLKTextureInfo* textureInfo = [GLKTextureLoadertextureWithContentsOfFile:filePathoptions:optionserror:nil];
//着色器
self.mEffect= [[GLKBaseEffectalloc]init];
self.mEffect.texture2d0.enabled=GL_TRUE;
self.mEffect.texture2d0.name= textureInfo.name;
}