[OpenGL ES 01] early experience of OpenGL ES on iOS

Source: Internet
Author: User
ArticleDirectory
    • 1. What is OpenGL ES?
    • 2. How to use OpenGL ES on iOS?

[OpenGL ES 01] experience of OpenGL ES

Luo chaohui (http://www.cnblogs.com/kesalin)

This article follows the "signature-non-commercial use-consistency" creation public agreement   1. What is OpenGL ES?

OpenGL ES is a simplified version of OpenGL designed for handheld devices. The latest version of OpenGL is 3.0. OpenGL ES can be implemented on different mobile phone systems, or on a browser (Web GL ). Currently, the newer IOS version supports OpenGL ES 2.0. Here, I will introduce how to use OpenGL ES 2.0 on IOS.

 

2. How to use OpenGL ES on iOS? 1. Preparations

1) Open xcode (4.2 is used) and create an empty application.

2), name it tutorial01, and select Device Family as iPhone. Keep the default selected use automatic reference counting to use the automatic reference count.

3) Add the required libraries, and perform OpenGL es development and opengles on the iOS platform. framework and quartzcore. framework is required. select target: tutorial01 and click + in build phase-> link binary with libraries to add the two libraries:

After the project structure is added, you can drag the two frameworks to the frameworks folder. No one wants to mess up the project structure, right?

4) at this point, the simulator is blank during compilation and running! Because the empty application template is empty, which even has a window. Therefore, we need to add a window. Right-click the supporting Files folder and choose New File> User Interface> window:

Input name: mainwindow

5) To associate appdelegate with window, we also need to create an object in mainwindow. XIB. Select mainwindow. XIB and drag an object to it:

After adding, the effect is as follows:

6), then we modify the custom class of the object to appdelegate, so that it representsCodeAppdelegate.

7) to associate the window with app delegate, we need to add the iboutlet modifier before the code window attribute in appdelegate. h:

 
@ Property (strong, nonatomic) iboutlet uiwindow * window;

8) Select mainwindow. XIB, right-click appdelegate, and drag the outlet window to the window above it. In this way, the window in appdelegate is associated with the real window.

9) Similarly, we also need to modify the custom class of the file's owner to uiapplication and use the same drag-and-drop technique as in 8, associate the delegate of the file's owner with the app delegate.

10) now the preparation is complete. Compile and run it. The simulator is still blank because we have not added a View to the window. Next we will add a view.

2. Set the OpenGL ES Runtime Environment

1) Although iOS 5 provides glkview in glkit, we can create our own gl es view manually from scratch, so that we can further understand that OpenGL ES is used on IOS. In the new file in the tutorial01 directory, Select User Interface-> view as the template and name it openglview:

2) Modify openglview. h:

# Import<Uikit/uikit. h># Import<Quartzcore/quartzcore. h># Include<Opengles/ES2/Gl. h># Include<Opengles/ES2/glext. h>@ InterfaceOpenglview: uiview {caeagllayer*_ Eagllayer; eaglcontext*_ Context; gluint _ colorrenderbuffer; gluint _ framebuffer ;}@ End

These variables will be described later.

3) Add the following functions in openglview. M:

+(Class) layerclass {//Only a layer of the [caeagllayer class] type can depict OpenGL content on it.Return[CaeagllayerClass];}

In order for uiview to display OpenGL content, we must change the default layer type to the caeagllayer type (this dynamic modification of the return class type means to explain the key value observation (KVO) in [simple cocoa) and its implementation mechanism ).

4) The default calayer is transparent. We need to set it to opaque to see what is depicted on it. To this end, we use the anonymous category technique to start with openglview. m (at @ implementationAbove openglview) Add anonymous category and declare the private function setuplayer:

//Use anonymous category to declare Private Members@ InterfaceOpenglview ()-(Void) Setuplayer;@ End

Next, add the setuplayer implementation between @ implementation and @ end:

-( void  ) setuplayer {_ eagllayer  = (caeagllayer * ) self. layer;   //   calayer is transparent by default. You must set it to Opacity to make it visible  _ eagllayer. opaque =  yes;  ///   sets the descriptive attribute, here, the rendering content and color format are not maintained as rgba8  _ eagllayer. drawableproperties =  [nsdictionary attributes: [nsnumber numberwithbool: No], keys, keaglcolorformatrgba8, keagldrawablepropertycolorformat, nil];}  

5) Now that the layer configuration is ready, let's create and set items related to OpenGL ES. First, we need to create the OpenGL ES rendering context (the corresponding implementation in IOS is eaglcontext). This context manages all the States, commands, and Resource Information depicted using OpenGL ES. Then, you need to set it to the current context, because we need to use OpenGL ES for rendering (plotting ). Add the-(void) setupcontext; declaration to the anonymous category and add its implementation between @ implement and @ end. This is the same as creating a core graphics context when using core graphics for profiling.

-( Void  ) Setupcontext {  //  Specify the version of the OpenGL rendering API. Here we use OpenGL ES 2.0 Eaglrenderingapi API = Keaglrenderingapiopengles2; _ Context = [[Eaglcontext alloc] initwithapi: API];  If (!_ Context) {nslog (  @"  Failed to initialize opengles 2.0 Context  "  ); Exit (  1  );}  //  Set to current context      If (! [Eaglcontext setcurrentcontext: _ context]) {nslog (  @"  Failed to set current OpenGL Context  " ); Exit (  1  );}} 

6) Create renderbuffer

With the context, OpenGL also needs to describe on a buffer. This buffer is renderbuffer (OpenGL ES has a total of three different uses of color buffer, depth buffer and stencel buffer, here is the most basic color buffer ). Next, we still create the private method setuprenderbuffer to generate the color Buffer:

 
-(Void) Setuprenderbuffer {glgenrenderbuffers (1,&_ Colorrenderbuffer); glbindrenderbuffer (gl_renderbuffer, _ colorrenderbuffer );//Allocate storage space for color renderbuffer[_ Context renderbufferstorage: gl_renderbuffer fromdrawable: _ eagllayer];

The prototype of glgenrenderbuffers is:

VoidGlgenrenderbuffers (glsizei N, gluint * renderbuffers)

It applies for an ID (or name) for renderbuffer ). Parameter n indicates the number of renderbuffer requests to be generated, while renderbuffers returns the ID allocated to renderbuffer. Note: The returned ID is not 0, and Id 0 is reserved by OpenGL ES, we cannot use renderbuffer with ID 0.

The following is a prototype of glbindrenderbuffer:

 
VoidGlbindrenderbuffer (glenum target, gluint renderbuffer)

This function sets the renderbuffer of the specified ID to the current renderbuffer. The target parameter must be gl_renderbuffer, And the renderbuffer parameter is the ID generated by glgenrenderbuffers. When the renderbuffer with the specified ID is set to the current renderbuffer for the first time, the renderbuffer object is initialized and its initial value is:

Width and height: the width and height of the pixel unit. The default value is 0;

Internal format: Internal format, one of the three buffer formats-color, depth or stencel;

Color bit-depth:OnlyWhen the internal format is color, set the bit-Depth Color. The default value is 0;

Depth bit-depth:OnlyWhen the internal format is depth, the default value is 0;

Stencel bit-depth:OnlyWhen the internal format is stencel, the default value is 0;

Function -(Bool) Renderbufferstorage :(Nsuinteger) Target fromdrawable :(ID<Eagldrawable>) Drawable; used drawable internally (here is the eagllayer) related information (Do you still remember to set some attributes of drawableproperties during setuplayer ?) Glrenderbufferstorage (glenum target, glenum internalformat, glsizei width, glsizei height) is called as a parameter; glrenderbufferstorage specifies the width and height of the image stored in renderbuffer and the color format, the storage space is allocated according to the specification. Here, we will call glrenderbufferstorage using the color format rgba8 of the eagllayer and the width and height of the eagllayer as the parameter.

7) create a framebuffer object

Framebuffer object is also called FBO. It is equivalent to the manager of buffer (color, depth, stencer). Three major buffers can be attached to one FBO. We use FBO for rendering on off-screen buffer. Next, we still create the private method setupframebuffer to generate the frame buffer:

 
-(Void) Setupframebuffer {glgenframebuffers (1,&_ Framebuffer );//Set to the current framebufferGlbindframebuffer (gl_framebuffer, _ framebuffer );//Assemble _ colorrenderbuffer to the assembly point gl_color_attachment0.Glframebufferrenderbuffer (gl_framebuffer, gl_color_attachment0, gl_renderbuffer, _ colorrenderbuffer );}

The setupframebuffer is roughly the same as the preceding setuprenderbuffer. The ID allocated by glgenframebuffers cannot be 0, and the framebuffer with the ID 0 is reserved by OpenGL ES, which points to the framebuffer provided by the window system, we also cannot use framebuffer with ID 0, otherwise the system will fail. The function prototype of glframebufferrenderbuffer is:

 
VoidGlframebufferrenderbuffer (glenum target, glenum attachment, glenum renderbuffertarget, gluint renderbuffer)

This function attach the related buffer (one of the three major buffers) to the framebuffer (if the renderbuffer is not 0, you can see why the ID returned by glgenrenderbuffers is not 0) or detach from framebuffer (if renderbuffer is 0 ). The attachment parameter specifies the buffer to which the renderbuffer is assembled. The value is gl_color_attachment0, gl_depth_attachment, and gl_stencil_attachment, which correspond to three major buffers: color, depth, and stencel.

8) When the layout of the uiview changes, the original renderbuffer will not be consistent due to the variation of the width and height of the layer. we need to destroy the existing renderbuffer and framebuffer. Next, we still create the private method destoryrenderandframebuffer to destroy the generated Buffer:

-(Void) Destoryrenderandframebuffer {gldeleteframebuffers (1,&_ Framebuffer); _ framebuffer=0; Gldeleterenderbuffers (1,&_ Colorrenderbuffer); _ colorrenderbuffer=0;}

9) So far, the theory is too much. Let's draw something and see how it works. Next, we still create a private method render for real profiling:

-( void  ) render {glclearcolor (  0 ,  1.0 ,  0 ,  1.0  ); glclear (gl_color_buffer_bit); [_ context presentrenderbuffer: gl_renderbuffer];}  

Glclearcolor (GlclampfRed,GlclampfGreen,GlclampfBlue,GlclampfAlpha) is used to set the screen color. The default value is black. glclear (GlbitfieldMask) is used to specify the buffer specified by the mask to be cleared by the screen color. The mask can be a free combination of gl_color_buffer_bit, gl_depth_buffer_bit, and gl_stencil_buffer_bit. Here we only use color buffer, so the clolor buffer is cleared. -(Bool) presentrenderbuffer :( nsuinteger) target is to present the specified renderbuffer on the screen. Here we specify the one already bound to the current renderbuffer before renderbuffer can be rendered, requiredRenderbufferstorage: fromdrawable:Allocate a bucket to it. When we set the drawable attribute, we set keagldrawablepropertyretainedbacking to false, indicating that we do not want to keep the rendered content. Therefore, during the next rendering, the appProgramIt must be completely repainted once. Setting this parameter to true is relatively high for performance and resource images. Therefore, keagldrawablepropertyretainedbacking is set to true only when renderbuffer needs to keep its content unchanged.

3. Rendering

1. With the preparations, let's take a look at our results. First, use openglview as the view of the window in appdelegate, and change appdelegate. h:

 
# Import<Uikit/uikit. h># Import "Openglview. h"@ InterfaceAppdelegate: uiresponder <uiapplicationdelegate>{Openglview*_ Glview;} @ property (strong, nonatomic) iboutlet uiwindow*Window; @ property (strong, retain) iboutlet openglview*Glview;@ End

2. Implement the following code in appdelegate. M:

 @ Implementation  Appdelegate @ Synthesize Window = _ Window;  @ Synthesize Glview = _ Glview; -(Bool) Application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary * ) Launchoptions {self. Window = [[Uiwindow alloc] initwithframe: [[uiscreen mainscreen] bounds]; cgrect screenbounds = [[Uiscreen mainscreen] bounds]; self. glview = [[Openglview alloc] initwithframe: screenbounds]; [self. Window addsubview: Self. glview]; self. Window. backgroundcolor =[Uicolor whitecolor]; [self. Window makekeyandvisible];  Return  Yes ;} 

Because we use arc, we don't have to worry about resource release.

3. Return openglview. M and add the function in it:

 
-(Void) Layoutsubviews {[self setuplayer]; [self setupcontext]; [self destoryrenderandframebuffer]; [self setuprenderbuffer]; [self setupframebuffer]; [self render];}

4. Compile and run the program:

 

5. If you have not saved your code, select File-source control-> commit to submit your code to git. It is a good habit to submit code from time to time. The code written here will be used in subsequent articles. This articleSource codeCan be viewed and downloaded here: https://github.com/kesalin/OpenGLES

4. refference

OpenGL ES 2.0 for iPhone

OpenGL ES 2.0 programming guide

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.