OpenGL ES 学习和探索

OpenGL ES案例-分别用GLSL和GLKit绘制可旋转的金

2020-08-03  本文已影响0人  Sheisone

前面我们有使用OpenGL来实现绘制可旋转的金字塔,现在我们来使用OpenGL ES实现同样的效果,然后再实现金字塔贴上纹理并和颜色混合的效果。

一、最终结果以及准备工作

金字塔.gif

我们用到了一个三方的OpenGL ES的矩阵库,类似的矩阵库很多,可以github上搜索。

矩阵库.png

二、GLSL实现

代码主体和上一个案例一样,我们自定义两个着色器:顶点着色器shaderv.glsl 和片源着色器shaderf.glsl,再自定义一个ShaderView,并指定为当面Viewcontroller的view。
工程结构:

image.png

1.shaderv.glsl代码:

attribute vec4 position;
attribute vec4 positionColor;

uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;

varying lowp vec4 varyColor;


void main()
{
    varyColor = positionColor;
   
    vec4 vPos;
   
    //4*4 * 4*4 * 4*1
    vPos = projectionMatrix * modelViewMatrix * position;
    gl_Position = vPos;
}

在顶点着色器里面,我们实现了将顶点颜色通过varyColor传递到片源着色器中,然后通过透视矩阵projectionMatrix和模型视图矩阵modelViewMatrix左乘我们的顶点坐标来得到最后变换后的坐标位置。

2.shaderf.glsl代码:

precision highp float;
varying lowp vec4 varyColor;
void main()
{
     gl_FragColor = varyColor;
}
>片源着色器很简单,拿到从顶点着色器传递过来的颜色数据,直接运用即可。

3. ShaderView代码

接下来我们,着重看下ShaderView里面的代码,因为要控制金字塔的旋转,所以我们需要定义几个成员变量:

@implementation ShaderView{
    CGFloat xDegree; //X轴旋转角度
    CGFloat yDegree; //Y轴旋转角度
    CGFloat zDegree; //Z轴旋转角度
    
    BOOL isXRotate;
    BOOL isYRotate;
    BOOL isZRotate;
    
    NSTimer* myTimer;
    
}

然后依然和上一个案例一样,重写layoutSubviews方法,实现6步:

-(void)layoutSubviews
{
    //1.设置图层
    [self setupLayer];
    
    //2.设置上下文
    [self setupContext];
    
    //3.清空缓存区
    [self deletBuffer];
    
    //4.设置renderBuffer;
    [self setupRenderBuffer];
    
    //5.设置frameBuffer
    [self setupFrameBuffer];
    
    //6.绘制
    [self render];
}

前五部都一样,我们重点看第六步代码实现:

-(void)render
{
    //1.清屏颜色
    glClearColor(0, 0.0, 0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    
    
    CGFloat scale = [[UIScreen mainScreen] scale];
    //2.设置视口
    glViewport(self.frame.origin.x * scale, self.frame.origin.y * scale, self.frame.size.width * scale, self.frame.size.height * scale);
    
    //3.获取顶点着色程序、片元着色器程序文件位置
    NSString* vertFile = [[NSBundle mainBundle] pathForResource:@"shaderv" ofType:@"glsl"];
    NSString* fragFile = [[NSBundle mainBundle] pathForResource:@"shaderf" ofType:@"glsl"];
    
    //4.判断self.myProgram是否存在,存在则清空其文件
    if (self.myProgram) {
        
        glDeleteProgram(self.myProgram);
        self.myProgram = 0;
    }
    
    //5.加载程序到myProgram中来。
    self.myProgram = [self loadShader:vertFile frag:fragFile];
    
    //6.链接
    glLinkProgram(self.myProgram);
    GLint linkSuccess;
    
    //7.获取链接状态
    glGetProgramiv(self.myProgram, GL_LINK_STATUS, &linkSuccess);
    if (linkSuccess == GL_FALSE) {
        GLchar messages[256];
        glGetProgramInfoLog(self.myProgram, sizeof(messages), 0, &messages[0]);
        NSString *messageString = [NSString stringWithUTF8String:messages];
        NSLog(@"error%@", messageString);
        
        return ;
    }else {
        glUseProgram(self.myProgram);
    }
    
    //8.创建顶点数组 & 索引数组
    //(1)顶点数组 前3顶点值(x,y,z),后3位颜色值(RGB)
    GLfloat attrArr[] =
    {
        -0.5f, 0.5f, 0.0f,      1.0f, 0.0f, 1.0f,     0.0f, 1.0f, //左上0
        0.5f, 0.5f, 0.0f,       1.0f, 0.0f, 1.0f,     1.0f, 1.0f,//右上1
        -0.5f, -0.5f, 0.0f,     1.0f, 1.0f, 1.0f,     0.0f, 0.0f,//左下2
        
        0.5f, -0.5f, 0.0f,      1.0f, 1.0f, 1.0f,     1.0f, 0.0f,//右下3
        0.0f, 0.0f, 1.0f,       0.0f, 1.0f, 0.0f,     0.5f, 0.5f,//顶点4
        
    };
    
    //(2).索引数组
    GLuint indices[] =
    {
        0, 3, 2,
        0, 1, 3,
        0, 2, 4,
        0, 4, 1,
        2, 3, 4,
        1, 4, 3,
    };

    //(3).判断顶点缓存区是否为空,如果为空则申请一个缓存区标识符
    if (self.myVertices == 0) {
        glGenBuffers(1, &_myVertices);
    }
    
    
    //9.-----处理顶点数据-------
    //(1).将_myVertices绑定到GL_ARRAY_BUFFER标识符上
    glBindBuffer(GL_ARRAY_BUFFER, _myVertices);
    //(2).把顶点数据从CPU内存复制到GPU上
    glBufferData(GL_ARRAY_BUFFER, sizeof(attrArr), attrArr, GL_DYNAMIC_DRAW);
    
    //(3).将顶点数据通过myPrograme中的传递到顶点着色程序的position
    //1.glGetAttribLocation,用来获取vertex attribute的入口的.
    //2.告诉OpenGL ES,通过glEnableVertexAttribArray,
    //3.最后数据是通过glVertexAttribPointer传递过去的。
    //注意:第二参数字符串必须和shaderv.vsh中的输入变量:position保持一致
    GLuint position = glGetAttribLocation(self.myProgram, "position");
    
    //(4).打开position
    glEnableVertexAttribArray(position);
    
    //(5).设置读取方式
    //参数1:index,顶点数据的索引
    //参数2:size,每个顶点属性的组件数量,1,2,3,或者4.默认初始值是4.
    //参数3:type,数据中的每个组件的类型,常用的有GL_FLOAT,GL_BYTE,GL_SHORT。默认初始值为GL_FLOAT
    //参数4:normalized,固定点数据值是否应该归一化,或者直接转换为固定值。(GL_FALSE)
    //参数5:stride,连续顶点属性之间的偏移量,默认为0;
    //参数6:指定一个指针,指向数组中的第一个顶点属性的第一个组件。默认为0
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8, NULL);
   
    //10.--------处理顶点颜色值-------
    //(1).glGetAttribLocation,用来获取vertex attribute的入口的.
    //注意:第二参数字符串必须和shaderv.glsl中的输入变量:positionColor保持一致
    GLuint positionColor = glGetAttribLocation(self.myProgram, "positionColor");
   
    //(2).设置合适的格式从buffer里面读取数据
    glEnableVertexAttribArray(positionColor);
    
    //(3).设置读取方式
    //参数1:index,顶点数据的索引
    //参数2:size,每个顶点属性的组件数量,1,2,3,或者4.默认初始值是4.
    //参数3:type,数据中的每个组件的类型,常用的有GL_FLOAT,GL_BYTE,GL_SHORT。默认初始值为GL_FLOAT
    //参数4:normalized,固定点数据值是否应该归一化,或者直接转换为固定值。(GL_FALSE)
    //参数5:stride,连续顶点属性之间的偏移量,默认为0;
    //参数6:指定一个指针,指向数组中的第一个顶点属性的第一个组件。默认为0
    glVertexAttribPointer(positionColor, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8, (float *)NULL + 3);

    //11.找到myProgram中的projectionMatrix、modelViewMatrix 2个矩阵的地址。如果找到则返回地址,否则返回-1,表示没有找到2个对象。
    GLuint projectionMatrixSlot = glGetUniformLocation(self.myProgram, "projectionMatrix");
    GLuint modelViewMatrixSlot = glGetUniformLocation(self.myProgram, "modelViewMatrix");
    
    float width = self.frame.size.width;
    float height = self.frame.size.height;
    
    //12.创建4 * 4投影矩阵
    KSMatrix4 _projectionMatrix;
    //(1)获取单元矩阵
    ksMatrixLoadIdentity(&_projectionMatrix);
    //(2)计算纵横比例 = 长/宽
    float aspect = width / height; //长宽比
    //(3)获取透视矩阵
    /*
     参数1:矩阵
     参数2:视角,度数为单位
     参数3:纵横比
     参数4:近平面距离
     参数5:远平面距离
     参考PPT
     */
    ksPerspective(&_projectionMatrix, 30.0, aspect, 5.0f, 20.0f); //透视变换,视角30°
    //(4)将投影矩阵传递到顶点着色器
    /*
     void glUniformMatrix4fv(GLint location,  GLsizei count,  GLboolean transpose,  const GLfloat *value);
     参数列表:
     location:指要更改的uniform变量的位置
     count:更改矩阵的个数
     transpose:是否要转置矩阵,并将它作为uniform变量的值。必须为GL_FALSE
     value:执行count个元素的指针,用来更新指定uniform变量
     */
    glUniformMatrix4fv(projectionMatrixSlot, 1, GL_FALSE, (GLfloat*)&_projectionMatrix.m[0][0]);
    

    //13.创建一个4 * 4 矩阵,模型视图矩阵
    KSMatrix4 _modelViewMatrix;
    //(1)获取单元矩阵
    ksMatrixLoadIdentity(&_modelViewMatrix);
    //(2)平移,z轴平移-10
    ksTranslate(&_modelViewMatrix, 0.0, 0.0, -10.0);
    //(3)创建一个4 * 4 矩阵,旋转矩阵
    KSMatrix4 _rotationMatrix;
    //(4)初始化为单元矩阵
    ksMatrixLoadIdentity(&_rotationMatrix);
    //(5)旋转
    ksRotate(&_rotationMatrix, xDegree, 1.0, 0.0, 0.0); //绕X轴
    ksRotate(&_rotationMatrix, yDegree, 0.0, 1.0, 0.0); //绕Y轴
    ksRotate(&_rotationMatrix, zDegree, 0.0, 0.0, 1.0); //绕Z轴
    //(6)把变换矩阵相乘.将_modelViewMatrix矩阵与_rotationMatrix矩阵相乘,结合到模型视图
     ksMatrixMultiply(&_modelViewMatrix, &_rotationMatrix, &_modelViewMatrix);
    //(7)将模型视图矩阵传递到顶点着色器
    /*
     void glUniformMatrix4fv(GLint location,  GLsizei count,  GLboolean transpose,  const GLfloat *value);
     参数列表:
     location:指要更改的uniform变量的位置
     count:更改矩阵的个数
     transpose:是否要转置矩阵,并将它作为uniform变量的值。必须为GL_FALSE
     value:执行count个元素的指针,用来更新指定uniform变量
     */
    glUniformMatrix4fv(modelViewMatrixSlot, 1, GL_FALSE, (GLfloat*)&_modelViewMatrix.m[0][0]);
    
   
    //14.开启剔除操作效果
    glEnable(GL_CULL_FACE);

    
    //15.使用索引绘图
    /*
     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);
    
  
    //16.要求本地窗口系统显示OpenGL ES渲染<目标>
    [self.myContext presentRenderbuffer:GL_RENDERBUFFER];

}

再次提醒,需要重写+ (Class)layerClass方法,否则会失败。

4.旋转逻辑事件

为了实现金字塔的旋转,我们新建三个Button并实现它们的点击事件:

#pragma mark -- actions

- (IBAction)xRotate:(id)sender {
    [self startTimer];
    isXRotate = !isXRotate;
}
- (IBAction)yRotate:(id)sender {
    [self startTimer];
    isYRotate = !isYRotate;
}
- (IBAction)zRotate:(id)sender {
    [self startTimer];
    isZRotate = !isZRotate;
}
- (void)startTimer{
    //开启定时器
       if (!myTimer) {
           myTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(reDegree) userInfo:nil repeats:YES];
       }
}

-(void)reDegree
{
    //如果停止X轴旋转,X = 0则度数就停留在暂停前的度数.
    //更新度数
    xDegree += isXRotate * 5;
    yDegree += isYRotate * 5;
    zDegree += isZRotate * 5;
    //重新渲染
    [self render];
    
}

ok,这样我们就实现了绘制一个可旋转的金字塔。运行一下:

三、GLKit实现

GLK实现相对简单很多,我们不需要单独编写顶点着色器和片源着色器文件,先配置工程

1.工程配置

#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>
@interface ViewController : GLKViewController


@end

2.代码实现

@interface ViewController ()
@property(nonatomic,strong)EAGLContext *mContext;
@property(nonatomic,strong)GLKBaseEffect *mEffect;

@property(nonatomic,assign)int count;

//旋转的度数
@property(nonatomic,assign)float XDegree;
@property(nonatomic,assign)float YDegree;
@property(nonatomic,assign)float ZDegree;

//是否旋转X,Y,Z
@property(nonatomic,assign) BOOL isXRotate;
@property(nonatomic,assign) BOOL isYRotate;
@property(nonatomic,assign) BOOL isZRotate;
@end


@implementation ViewController{
    dispatch_source_t  myTimer;
}

- (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);
    
    
}
- (void)render{
    GLfloat attrArr[] =
    {
        -0.5f, 0.5f, 0.0f,      1.0f, 0.0f, 1.0f, //左上
        0.5f, 0.5f, 0.0f,       1.0f, 0.0f, 1.0f, //右上
        -0.5f, -0.5f, 0.0f,     1.0f, 1.0f, 1.0f, //左下
        
        0.5f, -0.5f, 0.0f,      1.0f, 1.0f, 1.0f, //右下
        0.0f, 0.0f, 1.0f,       0.0f, 1.0f, 0.0f, //顶点
    };
    
    //2.绘图索引
    GLuint indices[] =
    {
        0, 3, 2,
        0, 1, 3,
        0, 2, 4,
        0, 4, 1,
        2, 3, 4,
        1, 4, 3,
    };
    
    //顶点个数
    self.count = sizeof(indices) /sizeof(GLuint);

    //将顶点数组放入数组缓冲区中 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);
       
       //使用颜色数据
       glEnableVertexAttribArray(GLKVertexAttribColor);
       glVertexAttribPointer(GLKVertexAttribColor, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, (GLfloat *)NULL + 3);

       
       //着色器
       self.mEffect = [[GLKBaseEffect alloc]init];

       //投影视图
       CGSize size = self.view.bounds.size;
       float aspect = fabs(size.width / size.height);
       GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(90.0), aspect, 0.1f, 100.0);
       projectionMatrix = GLKMatrix4Scale(projectionMatrix, 1.0f, 1.0f, 1.0f);
       self.mEffect.transform.projectionMatrix = projectionMatrix;
       
       //模型视图
       GLKMatrix4 modelViewMatrix = GLKMatrix4Translate(GLKMatrix4Identity, 0.0f, 0.0f, -2.0f);
       self.mEffect.transform.modelviewMatrix = modelViewMatrix;
       
       
       //定时器
       double seconds = 0.1;
       myTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
       dispatch_source_set_timer(myTimer, DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC, 0.0);
       dispatch_source_set_event_handler(myTimer, ^{
          
           self.XDegree += self.isXRotate * 0.1f;
           self.YDegree += self.isYRotate * 0.1f;
           self.ZDegree += self.isZRotate * 0.1f;
           
       });
       dispatch_resume(myTimer);
    
}
#pragma mark -- actions

- (IBAction)xRotate:(id)sender {
    self.isXRotate = !self.isXRotate;
}
- (IBAction)yRotate:(id)sender {
    self.isYRotate = !self.isYRotate;
}
- (IBAction)zRotate:(id)sender {
    self.isZRotate = !self.isZRotate;
}
#pragma mark - Delegate
- (void)update{
    GLKMatrix4 modelViewMatrix = GLKMatrix4Translate(GLKMatrix4Identity, 0.0f, 0.0f, -2.5f);
    modelViewMatrix = GLKMatrix4RotateX(modelViewMatrix, self.XDegree);
    modelViewMatrix = GLKMatrix4RotateY(modelViewMatrix, self.YDegree);
    modelViewMatrix = GLKMatrix4RotateZ(modelViewMatrix, self.ZDegree);
       
       self.mEffect.transform.modelviewMatrix = modelViewMatrix;
}
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect{
    glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    
    [self.mEffect prepareToDraw];
    glDrawElements(GL_TRIANGLES, self.count, GL_UNSIGNED_INT, 0);
}

接下来,运行工程即可。

觉得不错记得点赞哦!听说看完点赞的人逢考必过,逢奖必中。ღ( ´・ᴗ・` )比心

上一篇下一篇

猜你喜欢

热点阅读