OpenGL ES 地球月亮渲染案例

思维导图

长截图 2019-03-25 下午04.58.39.jpg

处理ArrayBuffer封装

创建顶点缓存数组

// 此方法在当前的OpenGL ES上下文中创建一个顶点属性数组缓冲区,用于调用此方法的线程.
- (id)initWithAttribStride:(GLsizeiptr)aStride
   numberOfVertices:(GLsizei)count
   bytes:(const GLvoid *)dataPtr
   usage:(GLenum)usage;
{
   NSParameterAssert(0 < aStride);
   NSAssert((0 < count && NULL != dataPtr) ||
      (0 == count && NULL == dataPtr),
      @"data must not be NULL or count > 0");
      
   if(nil != (self = [super init]))
   {
      stride = aStride;
      bufferSizeBytes = stride * count;
      // 第一步
      glGenBuffers(1,
         &name);
      // 第二步
      glBindBuffer(GL_ARRAY_BUFFER,
         self.name);
       
      // 第三步
      glBufferData(
         GL_ARRAY_BUFFER,  // 初始化缓存区的内容
         bufferSizeBytes,  // 要复制的字节数
         dataPtr,          // 要复制的字节地址
         usage);           //GPU内存中的缓存
         
      NSAssert(0 != name, @"Failed to generate name");
   }
   
   return self;
}   

分配顶点数据,准备绘制

// 当应用程序希望使用缓冲区呈现任何几何图形时,必须准备一个顶点属性数组缓冲区。当你的应用程序准备一个缓冲区时,一些OpenGL ES状态被改变,允许绑定缓冲区和配置指针。
- (void)prepareToDrawWithAttrib:(GLuint)index
   numberOfCoordinates:(GLint)count
   attribOffset:(GLsizeiptr)offset
   shouldEnable:(BOOL)shouldEnable
{
   NSParameterAssert((0 < count) && (count < 4));
   NSParameterAssert(offset < self.stride);
   NSAssert(0 != name, @"Invalid name");

   glBindBuffer(GL_ARRAY_BUFFER,
      self.name);

   if(shouldEnable)
   {
       glEnableVertexAttribArray(index);
   }

   glVertexAttribPointer( 
      index,            
      count,            
      GL_FLOAT,         
      GL_FALSE,         
      self.stride,      
      NULL + offset);
    
#ifdef DEBUG
   {
      GLenum error = glGetError();
      if(GL_NO_ERROR != error)
      {
         NSLog(@"GL Error: 0x%x", error);
      }
   }
#endif
}

绘制

// 提交由模式标识的绘图命令,并指示OpenGL ES从准备好的缓冲区中的顶点开始,从先前准备好的缓冲区中使用计数顶点。
+ (void)drawPreparedArraysWithMode:(GLenum)mode
   startVertexIndex:(GLint)first
   numberOfVertices:(GLsizei)count;
{
   glDrawArrays(mode, first, count);
}

重新缓存顶点数组

// 此方法加载由接收器存储的数据
- (void)reinitWithAttribStride:(GLsizeiptr)aStride
   numberOfVertices:(GLsizei)count
   bytes:(const GLvoid *)dataPtr;
{
   NSParameterAssert(0 < aStride);
   NSParameterAssert(0 < count);
   NSParameterAssert(NULL != dataPtr);
   NSAssert(0 != name, @"Invalid name");

   self.stride = aStride;
   self.bufferSizeBytes = aStride * count;
   
    // 第二步
   glBindBuffer(GL_ARRAY_BUFFER,
      self.name);
    // 第三步
   glBufferData(
      GL_ARRAY_BUFFER,  
      bufferSizeBytes,  
      dataPtr,
      GL_DYNAMIC_DRAW); 
}

ViewDidLoad

新建opengles上下文及GLKView配置

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

配置baseEffect光照信息

//创建GLKBaseEffect 只能有3个光照、2个纹理
self.baseEffect = [[GLKBaseEffect alloc]init];

-(void)configureLight
{
    
    //1.是否开启light0光照
    self.baseEffect.light0.enabled = GL_TRUE;
   
    /*
     union _GLKVector4
     {
     struct { float x, y, z, w; };
     struct { float r, g, b, a; };
     struct { float s, t, p, q; };
     float v[4];
     } __attribute__((aligned(16)));
     typedef union _GLKVector4 GLKVector4;
     
     union共用体
     有3个结构体,
     比如表示顶点坐标的x,y,z,w
     比如表示颜色的,RGBA;
     表示纹理的stpq
     
     */
    //2.设置漫射光颜色
    self.baseEffect.light0.diffuseColor = GLKVector4Make(
                                                         1.0f,//Red
                                                         1.0f,//Green
                                                         1.0f,//Blue
                                                         1.0f);//Alpha
    /*
     The position of the light in world coordinates.
      世界坐标中的光的位置。
     If the w component of the position is 0.0, the light is calculated using the directional light formula. The x, y, and z components of the vector specify the direction the light shines. The light is assumed to be infinitely far away; attenuation and spotlight properties are ignored.
     如果位置的w分量为0,则使用定向光公式计算光。向量的x、y和z分量指定光的方向。光被认为是无限远的,衰减和聚光灯属性被忽略。
     If the w component of the position is a non-zero value, the coordinates specify the position of the light in homogenous coordinates, and the light is either calculated as a point light or a spotlight, depending on the value of the spotCutoff property.
    如果该位置的W组件是一个非零的值,指定的坐标的光在齐次坐标的位置,和光是一个点光源和聚光灯计算,根据不同的spotcutoff属性的值
     The default value is [0.0, 0.0, 1.0, 0.0].
     默认值[0.0f,0.0f,1.0f,0.0f];
     */
    
    self.baseEffect.light0.position = GLKVector4Make(
                                                     1.0f, //x
                                                     0.0f, //y
                                                     0.8f, //z
                                                     0.0f);//w
    
    //光的环境部分
    self.baseEffect.light0.ambientColor = GLKVector4Make(
                                                         0.2f,//Red
                                                         0.2f,//Green
                                                         0.2f,//Blue
                                                         1.0f);//Alpha
    
}

设置模型矩阵,投影矩阵

//获取屏幕纵横比
    GLfloat aspectRatio = self.view.bounds.size.width / self.view.bounds.size.height;
    
    //4.创建投影矩阵 -> 透视投影
    self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeOrtho(-1.0 * aspectRatio, 1.0 * aspectRatio, -1.0, 1.0, 1.0, 120.0f);
    
    //5.设置模型矩阵 -5.0f表示往屏幕内移动-5.0f距离
    self.baseEffect.transform.modelviewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -5.0f);

处理顶点数据

-(void)bufferData
{
    //1、GLKMatrixStackCreate()创建一个新的空矩阵
    self.modelViewMatrixStack = GLKMatrixStackCreate(kCFAllocatorDefault);
    
    //2、为将要缓存区数据开辟空间
    //sphereVerts 在sphere.h文件中存在
    /*
     参数1:数据大小 3个GLFloat类型,x,y,z
     参数2:有多少个数据,count
     参数3:数据大小
     参数4:用途 GL_STATIC_DRAW,
     */
    //顶点数据缓存,顶点数据从sphere.h文件的sphereVerts数组中获取顶点数据x,y,z
    self.vertexPositionBuffer = [[AGLKVertexAttribArrayBuffer alloc]initWithAttribStride:(3 * sizeof(GLfloat)) numberOfVertices:sizeof(sphereVerts)/(3 * sizeof(GLfloat)) bytes:sphereVerts usage:GL_STATIC_DRAW];
    
    //法线,光照坐标 sphereNormals数组 x,y,z
    self.vertexNormalBuffer = [[AGLKVertexAttribArrayBuffer alloc]initWithAttribStride:(3 * sizeof(GLfloat)) numberOfVertices:sizeof(sphereNormals)/(3 * sizeof(GLfloat)) bytes:sphereNormals usage:GL_STATIC_DRAW];
    
    //纹理坐标 sphereTexCoords数组 x,y
    self.vertextTextureCoordBuffer = [[AGLKVertexAttribArrayBuffer alloc]initWithAttribStride:(2 * sizeof(GLfloat)) numberOfVertices:sizeof(sphereTexCoords)/ (2 * sizeof(GLfloat)) bytes:sphereTexCoords usage:GL_STATIC_DRAW];
    
    
    //3.获取地球纹理
    CGImageRef earthImageRef = [UIImage imageNamed:@"Earth512x256.jpg"].CGImage;

    //控制图像加载方式的选项
    NSDictionary *earthOptions = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],GLKTextureLoaderOriginBottomLeft, nil];
    
    //将纹理图片加载到纹理数据对象earchTextureInfo中
    /*
     参数1:加载的纹理图片
     参数2:控制图像加载的方式的选项-字典
     参数3:错误信息
     */
    self.earchTextureInfo = [GLKTextureLoader textureWithCGImage:earthImageRef options:earthOptions error:NULL];
    
    //4.获取月亮纹理
    CGImageRef moonImageRef = [UIImage imageNamed:@"Moon256x128"].CGImage;
    
    NSDictionary *moonOptions = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],GLKTextureLoaderOriginBottomLeft, nil];
    
    self.moomTextureInfo = [GLKTextureLoader textureWithCGImage:moonImageRef options:moonOptions error:NULL];
    
    //矩阵堆
    //用所提供的矩阵替换最顶层矩阵,将self.baseEffect.transform.modelviewMatrix,替换self.modelViewMatrixStack
    GLKMatrixStackLoadMatrix4(self.modelViewMatrixStack, self.baseEffect.transform.modelviewMatrix);
        
    //初始化在轨道上月球位置
    self.moonRotationAngleDegress = -20.0f;
    
        
}

渲染场景

#pragma mark - drawRect
//渲染场景
-(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);
    
    //地球旋转角度
    _earthRotationAngleDegress += 360.0f/60.0f;
    //月球旋转角度
    _moonRotationAngleDegress += (360.0f/60.0f)/SceneDaysPerMoonOrbit;
    
    //2、准备绘制
    /*
     其实就是把数据传递过去,然后指定读取方式
     参数1:数据是做什么用的
     参数2:数据读取个数
     参数3:数据读取索引
     参数4:是否调用glEnableVertexAttribArray
     
     着色器能否读取到数据,由是否启用了对应的属性决定,这就是glEnableVertexAttribArray的功能,允许顶点着色器读取GPU(服务器端)数据。

     
     默认情况下,出于性能考虑,所有顶点着色器的属性(Attribute)变量都是关闭的,意味着数据在着色器端是不可见的,哪怕数据已经上传到GPU,由glEnableVertexAttribArray启用指定属性,才可在顶点着色器中访问逐顶点的属性数据。glVertexAttribPointer或VBO只是建立CPU和GPU之间的逻辑连接,从而实现了CPU数据上传至GPU。但是,数据在GPU端是否可见,即,着色器能否读取到数据,由是否启用了对应的属性决定,这就是glEnableVertexAttribArray的功能,允许顶点着色器读取GPU(服务器端)数据。
     
     那么,glEnableVertexAttribArray应该在glVertexAttribPointer之前还是之后调用?答案是都可以,只要在绘图调用(glDraw*系列函数)前调用即可。
     */
    [self.vertexPositionBuffer prepareToDrawWithAttrib:GLKVertexAttribPosition numberOfCoordinates:3 attribOffset:0 shouldEnable:YES];
    [self.vertexNormalBuffer prepareToDrawWithAttrib:GLKVertexAttribNormal numberOfCoordinates:3 attribOffset:0 shouldEnable:YES];
    [self.vertextTextureCoordBuffer prepareToDrawWithAttrib:GLKVertexAttribTexCoord0 numberOfCoordinates:2 attribOffset:0 shouldEnable:YES];
    
    //3.开始绘制
    [self drawEarth];
    [self drawMoon];
    
}

绘制地球

-(void)drawEarth
{
    //获取纹理的name、target
    self.baseEffect.texture2d0.name = self.earchTextureInfo.name;
    self.baseEffect.texture2d0.target = self.earchTextureInfo.target;
    
    /*
     current matrix:
     1.000000 0.000000 0.000000 0.000000
     0.000000 1.000000 0.000000 0.000000
     0.000000 0.000000 1.000000 0.000000
     0.000000 0.000000 -5.000000 1.000000
     
     为什么?因为你在viewDidLoad中设置的
     //5.设置模型矩形 -5.0f表示往屏幕内移动-5.0f距离
     self.baseEffect.transform.modelviewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -5.0f);
     */
    
    //将当前的modelViewMatrixStack 压栈
    GLKMatrixStackPush(self.modelViewMatrixStack);
    
    //在指定的轴上旋转最上面的矩阵。
    GLKMatrixStackRotate(self.modelViewMatrixStack, GLKMathDegreesToRadians(SceneEarthAxialTiltDeg), 1.0f, 0.0f, 0.0f);
    
  
     /*
     current matrix:
     1.000000 0.000000 0.000000 0.000000
     0.000000 0.917060 0.398749 0.000000
     0.000000 -0.398749 0.917060 0.000000
     0.000000 0.000000 -5.000000 1.000000
    
     为什么?
      将矩阵与围绕X旋转的旋转矩阵相乘,即可得上述结果
     */
    self.baseEffect.transform.modelviewMatrix = GLKMatrixStackGetMatrix4(self.modelViewMatrixStack);
    
    //准备绘制
    [self.baseEffect prepareToDraw];
    
    //调用AGLKVertexAttribArrayBuffer,绘制图形
    /*
     参数1:绘制的方式,三角形
     参数2:绘制数据读取的索引
     参数3:绘制数据的大小
     */
    
    [AGLKVertexAttribArrayBuffer drawPreparedArraysWithMode:GL_TRIANGLES startVertexIndex:0 numberOfVertices:sphereNumVerts];
    
    //绘制完毕,则出栈
    /*
     current matrix:
     0.994522 0.041681 -0.095859 0.000000
     0.000000 0.917060 0.398749 0.000000
     0.104528 -0.396565 0.912036 0.000000
     0.000000 0.000000 -5.000000 1.000000
     */
    GLKMatrixStackPop(self.modelViewMatrixStack);
   
    /*
     current matrix:
     1.000000 0.000000 0.000000 0.000000
     0.000000 1.000000 0.000000 0.000000
     0.000000 0.000000 1.000000 0.000000
     0.000000 0.000000 -5.000000 1.000000
     */
    self.baseEffect.transform.modelviewMatrix = GLKMatrixStackGetMatrix4(self.modelViewMatrixStack);
    
}

绘制月球

-(void)drawMoon
{
    //获取纹理的name、target
    self.baseEffect.texture2d0.name = self.moomTextureInfo.name;
    self.baseEffect.texture2d0.target = self.moomTextureInfo.target;
    
    //压栈
    GLKMatrixStackPush(self.modelViewMatrixStack);
    
    //围绕Y轴旋转moonRotationAngleDegress角度
    //自转
    GLKMatrixStackRotate(self.modelViewMatrixStack, GLKMathDegreesToRadians(self.moonRotationAngleDegress), 0.0f, 1.0f, 0.0f);
  
    //平移 -月球距离地球的距离
    GLKMatrixStackTranslate(self.modelViewMatrixStack, 0.0f, 0.0f, SceneMoonDistanceFromEarth);
    
    //缩放,把月球缩放
    GLKMatrixStackScale(self.modelViewMatrixStack, SceneMoonRadiusFractionOfEarth, SceneMoonRadiusFractionOfEarth, SceneMoonRadiusFractionOfEarth);
    
    //旋转 围绕Y轴旋转
    GLKMatrixStackRotate(self.modelViewMatrixStack, GLKMathDegreesToRadians(self.moonRotationAngleDegress), 0.0f, 1.0f, 0.0f);
    self.baseEffect.transform.modelviewMatrix = GLKMatrixStackGetMatrix4(self.modelViewMatrixStack);
    
    [self.baseEffect prepareToDraw];
    
    [AGLKVertexAttribArrayBuffer drawPreparedArraysWithMode:GL_TRIANGLES startVertexIndex:0 numberOfVertices:sphereNumVerts];
    
    GLKMatrixStackPop(self.modelViewMatrixStack);
    
    self.baseEffect.transform.modelviewMatrix = GLKMatrixStackGetMatrix4(self.modelViewMatrixStack);
}

切换投影方法

#pragma mark -Switch Click
//切换正投影效果或透视投影效果
- (IBAction)switchClick:(UISwitch *)sender {
    
    GLfloat aspect = self.view.bounds.size.width / self.view.bounds.size.height;
    
    if ([sender isOn]) {
    
        //正投影
        self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeFrustum(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0, 2.0, 120.0);
        
    }else
    {
        //透视投影
        self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeOrtho(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0, 2.0, 120.0);
    }
    
}

效果图

12.gif
13.gif
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,295评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,928评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,682评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,209评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,237评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,965评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,586评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,487评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,016评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,136评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,271评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,948评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,619评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,139评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,252评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,598评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,267评论 2 358

推荐阅读更多精彩内容