实现一个正六边形旋转效果.
时序图:
大致代码
1.开启OpenGLES
上下文
EAGLContext * context = [[EAGLContext alloc]initWithAPI:(kEAGLRenderingAPIOpenGLES3)];
[EAGLContext setCurrentContext:context];
2.获取纹理图片
NSString * path = [[NSBundle mainBundle]pathForResource:@"image" ofType:@"png"];
UIImage * img = [UIImage imageWithContentsOfFile:path];
GLKTextureInfo * info = [GLKTextureLoader textureWithCGImage:img.CGImage options:@{GLKTextureLoaderOriginBottomLeft : @1} error:nil];
3.设置纹理.开启光照
//设置纹理.使用baseEffect
self.baseEffect = [[GLKBaseEffect alloc]init];
self.baseEffect.texture2d0.name = info.name;
self.baseEffect.texture2d0.target = info.target;
//开启光照效果
self.baseEffect.light0.enabled = YES;
self.baseEffect.light0.diffuseColor = GLKVector4Make(1, 1, 1, 1);
self.baseEffect.light0.position = GLKVector4Make(-0.5, -0.5, 5, 1);
4.开辟缓存区
//开辟一个顶点数据空间
self.vertexs = malloc(sizeof(CCVertex) * kCoordCount);
<省略顶点数据.请查看源码>
//开辟缓存区
glGenBuffers(1, &_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
//将数据从cpu拷贝到gpu
glBufferData(GL_ARRAY_BUFFER, sizeof(CCVertex) * kCoordCount, self.vertexs, GL_STATIC_DRAW);
5.开启顶点通道
参数解释: 此处的3.指的是xyz笛卡尔三维坐标值
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(CCVertex), NULL + offsetof(CCVertex, positionCoord));
6.开启纹理通道
参数解释: 此处的2.指的是纹理坐标系的值
glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(CCVertex), NULL + offsetof(CCVertex, textureCoord));
7.开启法线通道
参数解释: 此处的3.指的是法线坐标系的值
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, sizeof(CCVertex), NULL + offsetof(CCVertex, normal));
8.最后在代理方法中使用GL_TRIANGLES
图元进行连接
//代理方法
-(void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
//开启深度测试
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
[self.baseEffect prepareToDraw];
//开始绘制--开始绘制
glDrawArrays(GL_TRIANGLES, 0, kCoordCount);
}