OpenGL ES from entry to the senseless force --OpenGL ES quickly understand GLKit

OpenGL ES Background

OpenGL ES (OpenGL for Embedded Systems) is based on the watch for the destination time handheld and embedded target ADVANCED 3D graphics application programming Connector (API) OpenGL ES is the dominant smartphone platform graphics API ⽀ hold..: iOS, Andriod, BlackBerry, bada, Linux, Windows.

OpenGL ES Open Graphics Library (OpenGL) is used for visualization ⼆ dimensional and three-dimensional data. It is a versatile open standard graphics library, ⽀ support 2D and 3D digital content creation, mechanical and architectural design, virtual prototyping, simulation fly ⾏, video games and other applications. You can use the OpenGL 3D graphics pipeline configured to submit data. Vertices are transformed and lit, a combination of primitives, and rasterized to create a 2D image. OpenGL is designed to convert the function call can be sent to the underlying graphics hardware graphics commands. Because the underlying hardware dedicated to processing graphics commands, so fast OpenGL graphics typically comes in handy.

OpenGL for Embedded Systems (OpenGL ES) is a simplified version of OpenGL, it eliminates redundant functions, providing both an easy to learn and easier to implement in mobile graphics hardware in the library.
12791315-716adfaff9674126.png
OpenGL ES.png
OpenGL ES allows applications to leverage the power of the underlying graphics processors. On iOS GPU can perform complex 2D and 3D graphics, and the final image for each pixel discolored with complex calculations.

About GLKit

GLKit framework is designed to simplify application development based on the OpenGL / OpenGL ES's. It appears to accelerate OpenGL ES or OpenGL development of the applications. Use math library, background texture loading, pre-created shader effects, as well as the standard view and the view controller to achieve rendering loop.
GLKit framework provides functions and classes required can be reduced to create a new application based on the workload shader, or an existing application to support a fixed function vertex or process dependent release segment earlier version of OpenGL ES or OpenGL provided.
GLKit features:
1. Load texture
2. To provide a high-performance math
3. ⻅ often provided with a target mark is
4 provides a view and a view controller.

It is part of the GLKit Cocoa Touch and a plurality of other frames (containing the UIKit) a. GLKView and GLKViewController class is part of the framework of the GLKit.
GLKView is built Cocoa Touch UIView subclass of class, provide venues draw (View);
GLKViewController is built UIViewController subclass (extension to the standard UIKit design patterns Use to view the contents of the drawing management and presentation.)

GLKit的Hello World

New Xcode project, import the header files in ViewController.h

#import <GLKit/GLKit.h>
#import <OpenGLES/ES3/gl.h>
#import <OpenGLES/ES3/glext.h>

And ViewController inherit change GLKViewController, will inherit change the view of the ViewController is GLKView.

{
    EAGLContext *context;   //上下文
    GLKBaseEffect *cEffect; //完成着色器的工作
}

1.OpenGL ES related initialization

-(void)setUpConfig
{
//1.初始化上下文&设置当前上下文
context = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES3];
//判断context是否创建成功
if (!context) {
        NSLog(@"Create ES context Failed");
    }
//设置当前上下文
[EAGLContext setCurrentContext:context];
    
//2.获取GLKView & 设置context
GLKView *view =(GLKView *) self.view;
view.context = context;

//3.配置视图创建的渲染缓存区.
view.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888;
view.drawableDepthFormat = GLKViewDrawableDepthFormat16;
    
//4.设置背景颜色
glClearColor(1, 0, 0, 1.0);
}

Annotation. 1:
EAGLContext render layer is implemented under the Apple iOS OpenGLES internet.
KEAGLRenderingAPIOpenGLES1 =. 1, the fixed line
kEAGLRenderingAPIOpenGLES2 = 2,
kEAGLRenderingAPIOpenGLES3 =. 3,

Annotation 2:
. (. 1) drawableColorFormat: color buffer format.
Introduction: OpenGL ES has a cache, it is stored for a color to be displayed in the screen. You can use that property to set the color format buffer for each pixel.
GLKViewDrawableColorFormatRGBA8888 = 0,
the smallest part (the RGBA) for each pixel using the default buffer area 8 'bit, (4 bytes so that each pixel, 4 * 8 bit).
GLKViewDrawableColorFormatRGB565,
if your APP allows a smaller range of colors, you can set this. APP will let you consume less resources (memory and processing time)

(2) drawableDepthFormat:. Depth buffer format
GLKViewDrawableDepthFormatNone = 0, meaning there is no depth buffer
GLKViewDrawableDepthFormat16,
GLKViewDrawableDepthFormat24,
if you want to use this property (generally used for 3D games), you should choose GLKViewDrawableDepthFormat16 or GLKViewDrawableDepthFormat24. The difference here is the use of GLKViewDrawableDepthFormat16 will consume fewer resources

2. Load vertex / texture coordinate data

//1.设置顶点数组(顶点坐标,纹理坐标)
 /*
纹理坐标系取值范围[0,1];原点是左下角(0,0);
故而(0,0)是纹理图像的左下角, 点(1,1)是右上角.
*/
GLfloat vertexData[] = {
        0.5, -0.5, 0.0f,    1.0f, 0.0f, //右下
        0.5, 0.5, -0.0f,    1.0f, 1.0f, //右上
        -0.5, 0.5, 0.0f,    0.0f, 1.0f, //左上
        
        0.5, -0.5, 0.0f,    1.0f, 0.0f, //右下
        -0.5, 0.5, 0.0f,    0.0f, 1.0f, //左上
        -0.5, -0.5, 0.0f,   0.0f, 0.0f, //左下
    };

//2.开辟顶点缓存区
//(1).创建顶点缓存区标识符ID
GLuint bufferID;
glGenBuffers(1, &bufferID);
//(2).绑定顶点缓存区.(明确作用)
glBindBuffer(GL_ARRAY_BUFFER, bufferID);
//(3).将顶点数组的数据copy到顶点缓存区中(GPU显存中)
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
    
//3.打开读取通道.
//顶点坐标数据
glEnableVertexAttribArray(GLKVertexAttribPosition);
 /*
     typedef NS_ENUM(GLint, GLKVertexAttrib)
     {
     GLKVertexAttribPosition,顶点
     GLKVertexAttribNormal,法线
     GLKVertexAttribColor,颜色值
     GLKVertexAttribTexCoord0,纹理0
     GLKVertexAttribTexCoord1 纹理1
     } NS_ENUM_AVAILABLE(10_8, 5_0);
     */
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLfloat *)NULL + 0);
//纹理坐标数据
//打开对应attribute开关
glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLfloat *)NULL + 3);

Note 1:
vertex array: Developers can choose to set the function pointer, calling at the time of drawing methods, passed directly from the vertex data memory, that is part of the data before it is stored in the memory of them, called the vertex array.

Vertex buffer: higher performance practice is to allocate a block of memory in advance, the vertex data which previously passed into memory. This memory portion is called a vertex buffer.
Note 2:
(1) In iOS, by default, for performance reasons, the attributes of all the vertex shader (the Attribute) variables are closed.
Means, vertex shader data terminal (server) is unavailable even if you already use glBufferData method, the vertex data is copied from memory to the vertex buffer area (GPU video memory).
Therefore, we must open the channel by the glEnableVertexAttribArray methods specified access properties. to let the vertex shader to access to copy from the CPU . the data to the GPU
Note: the data in the GPU end is visible, i.e., a shader can read data corresponding to the attribute determined by whether or not enabled, this is glEnableVertexAttribArray feature that allows reading GPU vertex shader (server )data.

(2)方法简介
glVertexAttribPointer (GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* ptr)

Function: upload data to a memory of the vertex (provided in a suitable manner inside the buffer to read data from)
the list of parameters:
index: Specifies the vertex attribute to be modified index value, for example,
size: every time the number of read. (E.g., by three position (x, y, z) the composition, it is 4 and the color (r, g, b, a ), the texture is two.)
Type: Specifies the type of data in the array for each component. Symbolic constants have available GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_FIXED, and GL_FLOAT, the initial value GL_FLOAT.
normalized: Specifies when accessed, whether the value of the fixed point data should be normalized (GL_TRUE) or direct conversion to a fixed point value (GL_FALSE,)
a stride of: specified offset between consecutive vertex attributes. If it is 0, the vertex attributes as will be understood: that they are closely spaced together. The initial value of 0
PTR: specify a pointer to a first array of first component vertex attributes, initial value 0.

3. Load texture data (using GLBaseEffect)

 //1.获取纹理图片路径
NSString * filepath = [[NSBundle mainBundle] pathForResource:@"shiyuan1" ofType:@"jpg"];
//2.设置纹理参数
//纹理坐标原点是左下角,但是图片显示原点应该是左上角.
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:@(1),GLKTextureLoaderOriginBottomLeft, nil];
GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithContentsOfFile:filePath options:options error:nil];
    
//3.使用苹果GLKit 提供GLKBaseEffect 完成着色器工作(顶点/片元)
cEffect = [[GLKBaseEffect alloc]init];
cEffect.texture2d0.enabled = GL_TRUE;
cEffect.texture2d0.name = textureInfo.name;

4. Content pictorial view of the

#pragma mark -- GLKViewDelegate
//绘制视图的内容
/*
 GLKView对象使其OpenGL ES上下文成为当前上下文,并将其framebuffer绑定为OpenGL ES呈现命令的目标。然后,委托方法应该绘制视图的内容。
*/
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
//1.清除颜色缓存区
glClear(GL_COLOR_BUFFER_BIT);
//2.准备绘制
[cEffect prepareToDraw];
//3.开始绘制
glDrawArrays(GL_TRIANGLES, 0, 6);  
}

Draw Results:
12791315-c681060a35ef7cb5.png
Draw results .png

Here to be a form of mind maps OpenGL ES GLKit summary loaded picture:
12791315-9d6e5a1684509b04.png
Mind Mapping .png

Common API resolved

1.GLKView
GLKView Using OpenGL ES rendering content with a view to achieve default:
1. Initialize a new view

- (instancetype)initWithFrame:(CGRect)frame context:(EAGLContext *)context;

2. View Agent

@property (nullable, nonatomic, assign) IBOutlet id <GLKViewDelegate> delegate;

3. OpenGL ES-view content used for rendering context

@property (nonatomic, retain) EAGLContext *context;

4. Configuration frame buffer objects

drawableColorFormat 颜⾊渲染缓存区格式
/*
GLKViewDrawableColorFormatRGBA8888 = 0,
GLKViewDrawableColorFormatRGB565,
GLKViewDrawableColorFormatSRGBA8888,
*/
drawableDepthFormat 深度渲染缓存区格式
/*
GLKViewDrawableDepthFormatNone = 0,
GLKViewDrawableDepthFormat16,
GLKViewDrawableDepthFormat24,
*/
drawableStencilFormat 模板渲染缓存区的格式
/*
GLKViewDrawableStencilFormatNone = 0,
GLKViewDrawableStencilFormat8,
*/
drawableMultisample 多重采样缓存区的格式
/*
GLKViewDrawableMultisampleNone = 0,
GLKViewDrawableMultisample4X,
*/

The frame buffer properties

drawableHeight 底层缓存区对象的⾼度(以像素为单位)
drawableWidth 底层缓存区对象的宽度(以像素为单位)

6. The underlying object is bound to OpenGL ES FrameBuffer

- (void)bindDrawable;

7. Remove the view associated with the drawable / Delete View objects FrameBuffer

- (void)deleteDrawable;

8. pictorial view content and returns it as a new image object

@property (readonly, strong) UIImage *snapshot;

9.布尔值(BOOL),指定视图是否响应使得视图内容无效的消息

@property (nonatomic) BOOL enableSetNeedsDisplay;

10.立即重绘视图内容

- (void)display;

11.绘制视图内容(必须实现代理)

//GLKViewDelegate ⽤用于GLKView 对象回调⽅方法
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect;

2. GLKViewController
GLKViewController 管理OpenGL ES 渲染循环的视图控制器
1.视图控制器的代理

@property (nullable, nonatomic, assign) IBOutlet id <GLKViewControllerDelegate> delegate;

2.配置视图的帧速率

//视图控制器调用视图以及更新视图内容的速率
@property (nonatomic) NSInteger preferredFramesPerSecond;
//视图控制器调用视图以及更新其内容的实际速率
@property (nonatomic, readonly) NSInteger framesPerSecond;

3.控制帧更新

//Bool值,渲染循环是否已暂停
@property (nonatomic, getter=isPaused) BOOL paused;
//Bool值,当前程序重新激活活动状态时视图控制器是否自动暂停循环渲染
@property (nonatomic) BOOL pauseOnWillResignActive;
//Bool值,当前程序变为活动状态时视图控制器是否自动恢复呈现渲染
@property (nonatomic) BOOL resumeOnDidBecomeActive;

4.获取有关视图view的更新信息

//视图控制器自创建以来发送的帧更新数
@property (nonatomic, readonly) NSInteger framesDisplayed;
//⾃视图控制器第⼀次恢复发送更新事件以来经过的时间量
@property (nonatomic, readonly) NSTimeInterval timeSinceFirstResume;
//自上次视图控制器恢复发送更新事件以来更新的时间量
@property (nonatomic, readonly) NSTimeInterval timeSinceLastResume;
//⾃上次视图控制器调用委托⽅法以及经过的时间量
@property (nonatomic, readonly) NSTimeInterval timeSinceLastUpdate;
//⾃上次视图控制器调用视图display 方法以来经过的时间量
@property (nonatomic, readonly) NSTimeInterval timeSinceLastDraw;

5.渲染循环回调方法--更新视图内容,处理更新事件,
在这里,其实系统还有一个方法用于更新视图:- (void)update;

//在显示每个帧之前调用
- (void)glkViewControllerUpdate:(GLKViewController *)controller;

注:
如果不对GLKViewController进行子类化,则会调用glkViewControllerUpdate进行视图更新,如果GLKViewController被子类化,并且手动实现了- (void)update;则此时就不会调用glkViewControllerUpdate,相当于update覆盖了glkViewControllerUpdate,其实本质上update和glkViewControllerUpdate是相同的。

6.暂停/恢复通知

//在渲染循环暂停或者恢复之前调用
- (void)glkViewController:(GLKViewController *)controller willPause:(BOOL)pause;

3.GLKit 纹理加载GLTextureLoader
GLKTextureInfo类创建OpenGL纹理信息。该类包含以下属性:

name : OpenGL上下文中纹理名称
target : 纹理绑定的目标
height: 加载的纹理高度
width : 加载的纹理宽度
textureOrigin : 加载纹理中的原点位置
alphaState : 加载纹理中alpha分量状态

GLTextureLoader 简化从各种资源文件中加载纹理:

  1. 初始化
//初始化一个新的纹理加载到对象中
- (instancetype)initWithSharegroup:(EAGLSharegroup *)sharegroup;
//初始化一个新的纹理加载对象
- (instancetype)initWithShareContext:(NSOpenGLContext *)context;

2.从文件资源中加载纹理

//从文件加载2D纹理图像并从数据中创建新的纹理
+ (nullable GLKTextureInfo *)textureWithContentsOfFile:(NSString *)path options:(nullable NSDictionary<NSString*, NSNumber*> *)options  error:(NSError * __nullable * __nullable)outError; 
//从文件中异步加载2D纹理图像,并根据数据创建新纹理
- (void)textureWithContentsOfFile:(NSString *)path options:(nullable NSDictionary<NSString*, NSNumber*> *)options queue:(nullable dispatch_queue_t)queue completionHandler:(GLKTextureLoaderCallback)block; 

3. Load texture from a URL address

//用URL加载2D纹理图像并从数据中创建新的纹理
+ (nullable GLKTextureInfo *)textureWithContentsOfURL:(NSURL *)url options:(nullable NSDictionary<NSString*, NSNumber*> *)options error:(NSError * __nullable * __nullable)outError;
//用URL异步加载2D纹理图像,并根据数据创建新纹理
- (void)textureWithContentsOfFile:(NSString *)path options:(nullable NSDictionary<NSString*, NSNumber*> *)options queue:(nullable dispatch_queue_t)queue completionHandler:(GLKTextureLoaderCallback)block;

4. Create the texture data from memory

//从内存空间加载2D纹理图像并从数据中创建新的纹理
+ (nullable GLKTextureInfo *)textureWithContentsOfData:(NSData *)data options:(nullable NSDictionary<NSString*, NSNumber*> *)options error:(NSError * __nullable * __nullable)outError;
//从内存空间异步加载2D纹理图像,并根据数据创建新纹理
- (void)textureWithContentsOfData:(NSData *)data options:(nullable NSDictionary<NSString*, NSNumber*> *)options queue:(nullable dispatch_queue_t)queue completionHandler:(GLKTextureLoaderCallback)block;

5. Create textures from CGImages

//从Quartz加载2D纹理图像并从数据中创建新的纹理
+ (nullable GLKTextureInfo *)textureWithCGImage:(CGImageRef)cgImage options:(nullable NSDictionary<NSString*, NSNumber*> *)options error:(NSError * __nullable * __nullable)outError;
//从Quartz异步加载2D纹理图像,并根据数据创建新纹理
- (void)textureWithCGImage:(CGImageRef)cgImage options:(nullable NSDictionary<NSString*, NSNumber*> *)options queue:(nullable dispatch_queue_t)queue completionHandler:(GLKTextureLoaderCallback)block;

6. Create a cube texture loaded from URL

//从单个URL加载⽴方体贴图纹理图像,并根据数据创建新纹理
+ (nullable GLKTextureInfo*)cubeMapWithContentsOfURL:(NSURL *)url options:(nullable NSDictionary<NSString*, NSNumber*> *)options error:(NSError * __nullable * __nullable)outError;
//从单个URL异步加载⽴方体贴图纹理图像,并根据数据创建新纹理
- (void)cubeMapWithContentsOfURL:(NSURL *)url options:(nullable NSDictionary<NSString*, NSNumber*> *)options queue:(nullable dispatch_queue_t)queue completionHandler:(GLKTextureLoaderCallback)block;

7. Create texture from the resource file to load cube

//从单个文件加载⽴方体贴图纹理对象,并从数据中创建新纹理
+ (nullable GLKTextureInfo*)cubeMapWithContentsOfFile:(NSString *)path options:(nullable NSDictionary<NSString*, NSNumber*> *)options error:(NSError * __nullable * __nullable)outError;
//从单个文件异步立方体贴图纹理图像,并根据数据创建新纹理
- (void)cubeMapWithContentsOfFile:(NSString *)path options:(nullable NSDictionary<NSString*, NSNumber*> *)options queue:(nullable dispatch_queue_t)queue completionHandler:(GLKTextureLoaderCallback)block;
//从一系列文件加载立方体贴图纹理图像.并根据数据创建新的纹理
+ (nullable GLKTextureInfo*)cubeMapWithContentsOfFiles:(NSArray<id> *)paths options:(nullable NSDictionary<NSString*, NSNumber*> *)options error:(NSError * __nullable * __nullable)outError;
//从一系列文件异步立方体贴图纹理图像,并根据数据创建新纹理
- (void)cubeMapWithContentsOfFiles:(NSArray<id> *)paths options:(nullable NSDictionary<NSString*, NSNumber*> *)options queue:(nullable dispatch_queue_t)queue completionHandler:(GLKTextureLoaderCallback)block;

4.GLKit light GLKBaseEffect
1. Effect named

//给Effect(效果)命名
 NSString  *label; 

2. The configuration model-view transform

//绑定效果时应用于顶点数据的模型视图,投影和纹理变换
GLKEffectPropertyTransform  *transform;

Configuration lighting effects

//⽤于计算每个片段的光照策略,
GLKLightingType  lightingType;

注:
GLKLightingTypePerVertex 表示在三⻆形中每个顶点执⾏光照计算,然后在三角形进行插值。
GLKLightingTypePerPixel 表示光照计算的输⼊在三角形内插入,并且在每个片段执行光照计算。

4. The light configuration

//布尔值,表示为基元的两侧计算光照
GLboolean  lightModelTwoSided;
//计算渲染图元光照使⽤用的材质属性
GLKEffectPropertyMaterial *material;  
//环境颜色,应⽤效果渲染的所有图元
GLKVector4  lightModelAmbientColor;
//场景中第一个光照属性,第二个光照属性,第三个光照属性
GLKEffectPropertyLight   *light0, *light1, *light2; 

5. Configuration Texture

//第⼀个纹理属性,第二个纹理属性
GLKEffectPropertyTexture  *texture2d0, *texture2d1;
//纹理应⽤于渲染图元的顺序
NSArray<GLKEffectPropertyTexture*> *textureOrder; 

6. Configure atomization

//应用于场景的雾属性
GLKEffectPropertyFog  *fog;  

7. Configure the color information

//布尔值,表示计算光照与材质交互时是否使用颜色顶点属性
GLboolean  colorMaterialEnabled;
//布尔值,指示是否使用常量颜⾊
GLboolean  useConstantColor;
//不提供每个顶点颜色数据时使用常量颜⾊
GLKVector4  constantColor; 

8. Preparing the Drawing Effect

//准备渲染效果
- (void) prepareToDraw;

So far OpenGL ES GLKit basic common API that these follow-up will continue coming up. If clerical error, annotation error, please also indicate using the wrong method. THX.

Guess you like

Origin blog.csdn.net/weixin_34234823/article/details/90807520