OpenGL ES 索引绘图 & 自定义着色器 绘制金字塔

GLSL_自定义着色器纹理中,介绍了如果利用自定义着色器绘制纹理的步骤;

索引绘图

索引绘图是一种由开发者指定顶点连接顺序的绘图方式。优势是可以复用顶点,减少内存的使用。
如绘制一个金字塔3D图形时,如果使用三角形带或三角形组合绘制时,将会有多个顶点的重复,但如果使用索引绘图,则只需要5个点,重复利用,指定其连接顺序即可实现金字塔3D图形的绘制。

索引绘图 + 自定义着色器


- (void)renderDisplay
{
    
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(0.4, 0.6, 0.7, 1);
    
    CGFloat scale = [[UIScreen mainScreen] scale];
    // 设置视口
    CGPoint orgin = self.frame.origin;
    CGSize size = self.frame.size;
    glViewport(orgin.x * scale, orgin.y * scale, size.width * scale, size.height * scale);
    
    // 获取顶点着色程序、片元着色程序文件文职
    NSString * shaderVertex = [[NSBundle mainBundle] pathForResource:@"shaderv" ofType:@"glsl"];
    NSString * shaderFragment = [[NSBundle mainBundle] pathForResource:@"shaderf" ofType:@"glsl"];
    // 判断program是否存在,否则清空program
    if (self.mProgram) {
        glDeleteProgram(self.mProgram);
        self.mProgram = 0;
    }
    // 加载程序到program中来
    self.mProgram = [self loadShaderV:shaderVertex frag:shaderFragment];
    // 链接程序与着色器
    glLinkProgram(self.mProgram);
    // 获取链接状态,为true 则glUseProgram
    GLint linkStatus;
    glGetProgramiv(self.mProgram, GL_LINK_STATUS, &linkStatus);
    if (linkStatus == GL_FALSE) {
        GLchar message[256];
        glGetProgramInfoLog(self.mProgram, sizeof(message), 0, &message[0]);
        NSString * messageInfo = [NSString stringWithUTF8String:message];
        NSLog(@"program link error:%@",messageInfo);
        return;
    }
    NSLog(@"program link success");
    glUseProgram(self.mProgram);
    
    //====准备顶点数据 & 索引数组=====
    GLfloat attrArr[] =
    {
        -0.5f, 0.5f, 0.0f,      1.0f, 0.0f, 1.0f, //左上0
        0.5f, 0.5f, 0.0f,       1.0f, 0.0f, 1.0f, //右上1
        -0.5f, -0.5f, 0.0f,     1.0f, 1.0f, 1.0f, //左下2
        
        0.5f, -0.5f, 0.0f,      1.0f, 1.0f, 1.0f, //右下3
        0.0f, 0.0f, 1.0f,       0.0f, 1.0f, 0.0f, //顶点4
    };
    
    //(2).索引数组
    GLuint indices[] =
    {
        0, 3, 2,
        0, 1, 3,
        0, 2, 4,
        0, 4, 1,
        2, 3, 4,
        1, 4, 3,
    };
    
    // 判断顶点缓存区是否为空,如果为空则申请一个缓存区标识符
    if (self.mVertices == 0) {
        glGenBuffers(1, &_mVertices);
    }
    
    // =====处理顶点数据======
    // 将 _mVertices 绑定到 GL_ARRAY_BUFFER
    glBindBuffer(GL_ARRAY_BUFFER, _mVertices);
    // 把顶点数据从CPU内存copy到GPU显存中处理
    glBufferData(GL_ARRAY_BUFFER, sizeof(attrArr), attrArr, GL_DYNAMIC_DRAW);
    // 将顶点数据通过myPrograme中的传递到顶点着色程序的position
    GLuint position = glGetAttribLocation(self.mProgram, "position");
    
    // 打开通道
    glEnableVertexAttribArray(position);
    // 设置读取方式
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, NULL);
    
    // =====处理顶点颜色值=====
    GLuint positionColor = glGetAttribLocation(self.mProgram, "positionColor");
    glEnableVertexAttribArray(positionColor);
    glVertexAttribPointer(positionColor, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, (float *)NULL + 3);
    
    // 根据program 找到 projectionMatrix、modelViewMatrix
    GLuint projectionMatrix = glGetUniformLocation(self.mProgram, "projectionMatrix");
    GLuint modelViewMatrix = glGetUniformLocation(self.mProgram, "modelViewMatrix");
    
    
    
    float width = self.frame.size.width;
    float height = self.frame.size.height;
    
    // 创建4 * 4 投影矩阵
    KSMatrix4 _projectionMatrix;
    ksMatrixLoadIdentity(&_projectionMatrix);
    // 长宽比
    float aspect = width/height;
    
    // 获取透视矩阵
    /*
    参数1:矩阵
    参数2:视角,度数为单位
    参数3:纵横比
    参数4:近平面距离
    参数5:远平面距离
    */
    ksPerspective(&_projectionMatrix, 30.0, aspect, 5.0f, 20.0f);
    //将投影矩阵传递到顶点着色器
    /*
     location:指要更改的uniform变量的位置
     count:更改矩阵的个数
     transpose:是否要转置矩阵,并将它作为uniform变量的值。必须为GL_FALSE
     value:执行count个元素的指针,用来更新指定uniform变量
     */
    glUniformMatrix4fv(projectionMatrix, 1, GL_FALSE, (CGFloat *)&_projectionMatrix.m[0][0]);
    
    // 创建一个model视图矩阵
    KSMatrix4 _modelViewMatrix;
    // 获取单元矩阵
    ksMatrixLoadIdentity(&_modelViewMatrix);
    // z轴平移-10
    ksTranslate(&_modelViewMatrix,0.0,0.0,-10.0);
    // 创建一个4 * 4 矩阵,旋转矩阵
    KSMatrix4 _rotationMatrix;
    // 初始化为单元矩阵
    ksMatrixLoadIdentity(&_rotationMatrix);
    
    // 旋转
    // 绕x轴
    ksRotate(&_rotationMatrix, xDegree, 1.0, 0.0, 0.0);
    // 绕y轴
    ksRotate(&_rotationMatrix, yDegree, 0.0, 1.0, 0.0);
    // 绕z轴
    ksRotate(&_rotationMatrix, zDegree, 0.0, 0.0, 1.0);
    // 把变换矩阵相乘 将 _modelViewMatrix 矩阵 与 _rotationMatrix 矩阵相乘,结合到模型视图
    ksMatrixMultiply(&_modelViewMatrix, &_rotationMatrix, &_modelViewMatrix);
    //(7)将模型视图矩阵传递到顶点着色器
    /*
     location:指要更改的uniform变量的位置
     count:更改矩阵的个数
     transpose:是否要转置矩阵,并将它作为uniform变量的值。必须为GL_FALSE
     value:执行count个元素的指针,用来更新指定uniform变量
     */
    glUniformMatrix4fv(modelViewMatrix, 1, GL_FALSE, (GLfloat *)&_modelViewMatrix.m[0][0]);
    
    // 开启背面剔除
    glEnable(GL_CULL_FACE);
    
    // 使用索引绘图
    /*
     void glDrawElements(GLenum mode,GLsizei count,GLenum type,const GLvoid * indices);
     参数列表:
     mode:要呈现的画图的模型
                GL_POINTS
                GL_LINES
                GL_LINE_LOOP
                GL_LINE_STRIP
                GL_TRIANGLES
                GL_TRIANGLE_STRIP
                GL_TRIANGLE_FAN
     count:绘图个数
     type:类型
             GL_BYTE
             GL_UNSIGNED_BYTE
             GL_SHORT
             GL_UNSIGNED_SHORT
             GL_INT
             GL_UNSIGNED_INT
     indices:绘制索引数组

     */
    
    glDrawElements(GL_TRIANGLES, sizeof(indices) / sizeof(indices[0]), GL_UNSIGNED_INT, indices);
    // 本地视口显示渲染缓冲区
    [self.mContext presentRenderbuffer:GL_RENDERBUFFER];
    // 开启定时器
    [self gcdTimer];
}


- (void)gcdTimer
{
    double seconds = 0.1;
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC, 0.0);
    dispatch_source_set_event_handler(timer, ^{
       
        [self refreshAngle];
    });
    dispatch_resume(timer);
}
- (IBAction)X_Clicked:(id)sender {
   // 开启定时器
    boolX = !boolX;
    
}
- (IBAction)Y_Clicked:(id)sender {
    boolY = !boolY;
}
- (IBAction)Z_Clicked:(id)sender {
    boolZ = !boolZ;
}
- (void)refreshAngle
{
    // 更新度数
    xDegree += boolX * 5;
    yDegree += boolY * 5;
    zDegree += boolZ * 5;
    // 重新绘制
    [self renderDisplay];
    
}

效果

小bug

在renderDisplay方法的设置读取方式中,设置stride连续顶点属性之间的偏移量时,如果使用的是CGFloat修饰,会出现一个bug

 // 设置读取方式
 glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, sizeof(CGFloat) * 6, NULL);
    

CGFloat修饰stride的bug

可以看到并不是三角体,同理设置颜色值时,顶点颜色值也不是正常的效果

 glVertexAttribPointer(positionColor, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, (float *)NULL + 3);

顶点颜色stride用CGFloat修饰

GLfloat 是OpenGL ES库中定义的,为typedef float GLfloat;
CGFloat 是 CoreGraphics库CGBase.h定义的


/* Definition of `CGFLOAT_TYPE', `CGFLOAT_IS_DOUBLE', `CGFLOAT_MIN', and
 `CGFLOAT_MAX'. */

#if defined(__LP64__) && __LP64__
# define CGFLOAT_TYPE double
# define CGFLOAT_IS_DOUBLE 1
# define CGFLOAT_MIN DBL_MIN
# define CGFLOAT_MAX DBL_MAX
#else
# define CGFLOAT_TYPE float
# define CGFLOAT_IS_DOUBLE 0
# define CGFLOAT_MIN FLT_MIN
# define CGFLOAT_MAX FLT_MAX
#endif

/* Definition of the `CGFloat' type and `CGFLOAT_DEFINED'. */

typedef CGFLOAT_TYPE CGFloat;

使用GLfloat修饰则就是正常的显示,由两者的定义可以知道当使用sizeof取值时,两者是不一样的,CGFloat为8 ,GLfloat为4;而stride是用typedef int32_t GLsizei修饰的,接受长度为32Bits4个字节的数据,当使用CGFloat时就出现了这个bug。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值