美文网首页
GLKit索引绘图并添加纹理案例

GLKit索引绘图并添加纹理案例

作者: CrazySnow | 来源:发表于2020-08-20 16:53 被阅读0次

索引绘图的理解及案例效果,请查看GLSL索引绘图

GLKit索引绘图流程.png

一、绘制准备

  • 创建context
  • 设置GLKView对象
  • 设置当前的上下文
  • 开启深度测试
- (void) setupContext{

    //1.新建OpenGL ES上下文
    self.mContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    
    GLKView *view = (GLKView*)self.view;
    view.context = self.mContext;
    view.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888;
    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
    
    [EAGLContext setCurrentContext:self.mContext];
    
    glEnable(GL_DEPTH_TEST);
    
}

二、render函数,渲染图形

  • 创建顶点数组,索引数组
  • 将顶点数据从CPU拷贝到GPU
//将顶点数组放入数组缓冲区中 GL_ARRAY_BUFFER
    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(attrArr), attrArr, GL_STATIC_DRAW);
    
//    开辟索引缓存区
    //将索引数组存储到索引缓冲区 GL_ELEMENT_ARRAY_BUFFER
    GLuint index;
    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)*6, NULL);

三、实现GLKitView代理方法

调用索引绘制的方法

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect{
    glClearColor(0.3, 0.3, 0.3, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
//    准备绘制
    [self.mEffect prepareToDraw];
    glDrawElements(GL_TRIANGLES, self.count, GL_UNSIGNED_INT, 0);
}

四、实现GLKitView 的update方法

update函数的功能就等同于GLKViewControllerDelegate中的代理方法glkViewControllerUpdate(:),苹果官方文档针对这部分有详细说明:当你没有实现glkViewControllerUpdate(:)时,可以通过update来实现,也是一样的道理.

在update函数中主要是根据按钮的点击事件,判断是否围绕某个轴旋转,且在定时器方法中根据bool值设置旋转度数,最后在update函数中更改模型视图矩阵,系统调用代理方法重新绘制,表现为效果图中图形的旋转.

//场景数据变化
- (void)update{
    
    GLKMatrix4 modelViewMatrix = GLKMatrix4Translate(GLKMatrix4Identity, 0, 0, -2.5);
    modelViewMatrix = GLKMatrix4RotateX(modelViewMatrix, self.xDegree);
    modelViewMatrix = GLKMatrix4RotateY(modelViewMatrix, self.yDegree);
    modelViewMatrix = GLKMatrix4RotateZ(modelViewMatrix, self.zDegree);
    
    self.mEffect.transform.modelviewMatrix = modelViewMatrix;
}

完整demo

给图形添加纹理

1、修改顶点数据,在顶点数组中添加纹理坐标
2、将纹理坐标传递到顶点着色器

//    ------使用纹理数据
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*8, (GLfloat*)NULL+6);

3、获取纹理数据并加载图片

//    ------获取纹理路路径
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"mouse" ofType:@"jpg"];
    NSDictionary *option = [NSDictionary dictionaryWithObjectsAndKeys:@"1", GLKTextureLoaderOriginBottomLeft, nil];
    GLKTextureInfo *info = [GLKTextureLoader textureWithContentsOfFile:filePath options:option error:nil];

纹理demo

相关文章

网友评论

      本文标题:GLKit索引绘图并添加纹理案例

      本文链接:https://www.haomeiwen.com/subject/vqosjktx.html