iOS-----Opengl--opengl ES iOS entry 2---> Draw a polygon

Source: Internet
Author: User

In the previous article we learned how to build a development environment for OpenGL under iOS, and then we'll learn how to draw a polygon.

Before 2.0, ES was rendered using a fixed pipeline, what is a fixed pipeline, is a set of template flow, local coordinate transformation, the World coordinate transformation------observation of the coordinate transformation-----back elimination, light----- > rasterization, programmers just need to call a fixed API to modify some configuration parameters to complete the entire rendering process. By the 2.0, the fixed pipeline changed to a programmable pipeline, we can re-program the entire rendering process, there is no fixed API for you to call, everything depends on shader to complete. So what is shader:

The Shader is divided into vertex shaders (Vertex Shader) and fragment shaders (Fragment Shader). Vertex shader is mainly responsible for the geometric relations of vertices, Pixel shader mainly responsible for the calculation of the color of the film source. We are using the openGLES2.0.  Therefore, it is necessary to use Shader,shader to write in OpenGL coloring language (Glsl―opengl shading Language), which is not described in detail here. First, set up the cache.
Gluint _renderbuffer; Gluint _framebuffer;  Glgenrenderbuffers (1, &_renderbuffer);  Glbindrenderbuffer (Gl_renderbuffer, _renderbuffer);  [_eaglcontext renderbufferstorage:gl_renderbuffer fromdrawable:  (id<eagldrawable>) Self.layer];      Glgenframebuffers (1, &_framebuffer);  Glbindframebuffer (Gl_framebuffer, _framebuffer);  Glframebufferrenderbuffer (Gl_framebuffer,                              gl_color_attachment0,                              gl_renderbuffer,                              _renderbuffer);    

Before setting up the cache, it's best to clean it up first, avoiding duplicate settings

if (_framebuffer) {        gldeleteframebuffers (1, &_framebuffer);        _framebuffer = 0;    }        if (_renderbuffer) {        gldeleterenderbuffers (1, &_renderbuffer);        _renderbuffer = 0;    }

After the cache has been set up to compile the shader, basically the steps to compile the shader are fixed, image processing, and the filter implementation is basically done through shaders. The following is the code that compiles the shader.

Gluint _program; Glunit _positionslot;_program = [mtshaderoperations compileshaders:@ "Vertex" shaderfragment:@ "Fragment"                                   ]; Gluseprogram (_program);  _positionslot = Glgetattriblocation (_program, "Position");

Gluseprogram (_program);

Parameters in the binding shader

_positionslot = Glgetattriblocation (_program, "Position");

 + (Gluint) compileshaders: (NSString *) Shadervertex shaderfragment: (NSString *) shaderfragment {//1 vertex and Fragmen    T two SHADER are to be compiled gluint vertexshader = [mtshaderoperations Compileshader:shadervertex withtype:gl_vertex_shader];        Gluint Fragmentshader = [mtshaderoperations compileshader:shaderfragment withtype:gl_fragment_shader];    2 connect vertex and fragment shader into a complete program gluint _glprogram = Glcreateprogram ();    Glattachshader (_glprogram, vertexshader);        Glattachshader (_glprogram, Fragmentshader);        Link program Gllinkprogram (_glprogram);    3 Check link status Glint linksuccess;    GLGETPROGRAMIV (_glprogram, Gl_link_status, &linksuccess);        if (linksuccess = = gl_false) {Glchar messages[256];        Glgetprograminfolog (_glprogram, sizeof (messages), 0, &messages[0]);        NSString *messagestring = [NSString stringwithutf8string:messages];        NSLog (@ "%@", messagestring);    Exit (1); } return _glprogram;} 

+ (Gluint) Compileshader: (nsstring*) shadername Withtype: (glenum) Shadertype {//1 Find shader file nsstring* Shaderpath = [    [NSBundle Mainbundle] pathforresource:shadername oftype:@ "GLSL"];    nserror* error; nsstring* shaderstring = [NSString stringwithcontentsoffile:shaderpath encoding:nsutf8stringencoding error:&    ERROR];        if (!shaderstring) {NSLog (@ "Error Loading shader:%@", error.localizeddescription);    Exit (1);        }//2 Create an OpenGL object representing shader, specifying vertex or fragment shader gluint shaderhandle = Glcreateshader (Shadertype);    3 Get shader Source const char* shaderStringUTF8 = [shaderstring utf8string];    int shaderstringlength = (int) [shaderstring length];        Glshadersource (Shaderhandle, 1, &shaderstringutf8, &shaderstringlength);        4 Compiling shader Glcompileshader (shaderhandle);    5 Query the information of shader object Glint compilesuccess;    Glgetshaderiv (Shaderhandle, Gl_compile_status, &compilesuccess); if (compilesuccess = = Gl_false) {Glchar messages[256];        Glgetshaderinfolog (Shaderhandle, sizeof (messages), 0, &messages[0]);        NSString *messagestring = [NSString stringwithutf8string:messages];        NSLog (@ "%@", messagestring);    Exit (1); } return shaderhandle;}

Of course, to compile the shader, first we have to write the shader code well. Shader code for drawing polygons is very simple, if you do not know child shoes can refer to OpenGL coloring language (Glsl―opengl shading Language)

Create a new empty file, and then change the suffix to glsh to start writing the shader code.

The Vertex shader code is as follows:

Attribute vec4 position;void Main (void) {    gl_position = Position;    }

The Fragment shader code is as follows

void Main (void) {        Gl_fragcolor = VEC4 (0,1,1, 1.0);}

After compiling the shader, we can begin to draw the graph, it is important to note that in the opengles can only draw triangles, all the graphics are made of triangles.

Also, when defining vertices, be aware that the coordinate system in OpenGL is different from Uikit.

First define the vertex array

Const Glfloat vertices[] = {        -1,-1, 0,   //left lower        1,  -1, 0,   //Lower right        -1, 1,  0,   ///upper left        1,  1,  0}; Top Right

Draw a graphic

Incoming vertex parameters

Glvertexattribpointer (_positionslot, 3, gl_float, Gl_false, 0, vertices);

Glenablevertexattribarray (_positionslot);

Drawing polygons

Gldrawarrays (Gl_triangle_strip, 0, 4);

In the above we draw a polygon, this polygon is a vertex array in order to draw all the triangles, in many cases, does not meet our requirements. We can try to change the last sentence above

Gldrawarrays (Gl_triangle_strip, 1, 4);

The resulting image is as follows

Since OpenGL can only draw triangles, it is important that the vertices follow the order in which they are linked in the vertex array. Thus, another method is provided in the opengles.

Defining an indexed array
Const Glubyte indices[] = { 0,1,2, N-only };

Draw polygons based on the order of indexed arrays

Gldrawelements (gl_triangles, sizeof (indices)/sizeof (Indices[0]), gl_unsigned_byte, indices);

So we draw a quadrilateral, and the other polygons are the same steps.

In the next chapter we will talk about how to pass in a texture, so please look forward.

iOS-----Opengl--opengl ES iOS entry 2---> Draw a polygon

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.