OpenGL ES 2 (iOS) [01]: start with a small triangle

Directory structure:

The first step, clear what to do

A. target B. effect C. analysis

The second step, how to draw (pure theory)

A.OpenGL ES 2 b. rendering pipeline the drawing process of each unit [1] to the left to right) OpenGL ES 2 API 2) Vertex Arrays / Buffer Objects 3) Vertex Shader 4) Primitive Assembly 5) Rasterization 6) Texture Memory 7) Fragment Shader 8) Per-Fragment Operations 9) Render Buffer & Frame Buffer 10) EAGL API C. OpenGL ES Shader Language) * the simple flow chart

The third step, how to draw (actual)

The rendering process refinement of a.OpenGL ES 2) 2) 1 configuration initialization data) OpenGL ES 3 configuration Shader 4) rendering process B. code, a configuration rendering environment 1) configuration of the rendering window [inherited from UIView] 2) configuration rendering context 3) configuration frame rendering 4) configuration renderbuffer 5) frame buffer loading renderbuffer content 6) rendering context bound (two layers), the rendering window to modify the background color three, four, ES initialization data configuration OpenGL Shader 1) Vertex Shader written Code file 2) write Fragment Shader Code 3) Vertex Shader 4 configuration file) configuration Fragment Shader 5) to create a Shader Program 6) Shader and Vertex loading Fragment Shader 7 Shader Program five) link and rendering 1) empty the old render cache 2) set the render window 3) using Shder Program * * * * * * * * * * 5) to draw the graphic C. object oriented redesign

The fourth step, practice

A. modify the background color B. modify the triangle fill color C. modify the triangle of the three vertices of the color (fill color)

The first step, clear what to do

1 goals:

Using OpenGL ES 2 to draw a triangle in the iOS emulator.

2 effect:

OpenGL ES 2 (iOS) [01]: start with a small triangle

3 Analysis graphics:

1) background color is blue
–> modify the background color

2) right triangle
–> draw triangle

4 draw a triangle? What constitutes a triangle?

–> three points + three lines + the middle of the fill color, that is, the formation of a line of three points into a triangle.

1) what are the three endpoints (screen coordinates)?
to answer this question we must first understand how the coordinates of the OpenGL ES on the screen is distributed:

OpenGL ES 2 (iOS) [01]: start with a small triangle
OpenGL coordinate system {x, y, z}, ES

Note: picture cut from “Learning OpenGL For iOS” book

A. through the three-dimensional coordinates of the picture can know:

It is a three-dimensional coordinate system of {x, y, z} - dimensional coordinates of the center in the cube of the geometric center of {0, 0, 0} - the whole coordinate is [0, 1], OpenGL is only 0 ~ 1 point support

Note that the 0 and the, which are discussed here, are best understood as a –&gt of 0; an infinitesimal, of the order of –&gt, an infinite number of not more than the length of the 0 units, or the length of the 1 units.

Let’s look at the B. We draw the triangle, the coordinates in the iOS simulator or on a real machine consists of:

OpenGL ES 2 (iOS) [01]: start with a small triangle
three dimensional coordinates + coordinate value demo

Note: picture through CINEMA4D (C4D) 3D software rendering

Two dimensional is like this:

OpenGL ES 2 (iOS) [01]: start with a small triangle
2D coordinates (z = 0)

2) the three line?

A. connects three endpoints to form a closed triangle, so can the OpenGL ES draw the triangle directly? –> the answer is yes.

B. so OpenGL can draw a square directly?
–> the answer is no..

C. what does the OpenGL draw directly?
–&gt: the answer is: point sprites, lines, triangles, they are collectively referred to as the Primitive.

Note: the answer comes from the “OpenGL ES 2 Programming Guide Primitive Assembly and Rasterization” 7 chapter is as follows:
OpenGL ES 2 (iOS) [01]: start with a small triangle

. 1) line element Line Strip, refers to the line is connected, the first line and the last line is not connected together;
Line Loops, refers to the line is connected, the first the last line and a line connecting together, i.e. closed curve;
OpenGL ES 2 (iOS) [01]: start with a small triangle
Line Triangle Strip 2) triangular element, a band connected triangle
Triangle Fan, a fan connected
OpenGL ES 2 (iOS) [01]: start with a small triangle
Triangle OpenGL ES 2 (iOS) [01]: start with a small triangle
triangle fan 3) is mainly used in the sprite [texture]

3) fill color?

RGBA refers to the color value; (^_^ feel good waste but I still want to say)

The second step, how to draw (pure theory)

How to draw, is through a number of steps to complete a complete rendering rendering process, of course, here refers to the OpenGL ES 2 rendering pipeline process

OpenGL ES 2 rendering pipeline

OpenGL ES 2 (iOS) [01]: start with a small triangle
graphics pipeline (Graphics Pipeline)

because this is the iOS side of the map, so re mapping:

OpenGL ES 2 (iOS) [01]: start with a small triangle
ES 2 rendering flow chart of OpenGL

Note: this map is based on the “OpenGL ES 2 programming guide” Graphics Pipeline and Diney [All about ES 2.x (part 2/3)] pipeline map re – drawn in. [drawing software: Visio 2016]

1 describe the process of each unit to the left to right

OpenGL ES 2 API:

OpenGL ES 2 (iOS) [01]: start with a small triangle
iOS environment

gltypes.h contains the definition of OpenGL ES 2 basic data types;
glext.h includes a variety of macro definition, function and matrix used;
gl.h is OpenGL ES 2 all core functions (command);

The extended
OpenGL ES 2 Reference (
OpenGL ES 2 (iOS) [01]: start with a small triangle
online query function) Card
OpenGL ES 2 (iOS) [01]: start with a small triangle
function selection on the left click the red box function can be
offline to query the choice you can save I recommend using offline card to open the OpenGL ES 2 (iOS) [01]: start with a small triangle
red arrow, not affected by the network, but also at a glance. With the official Programming Guide to use the best.

2 Vertex Arrays / Buffer Objects:

1) Vertex Arrays Objects (VAOs), vertex array object, is an array that contains the vertex coordinates, color value, texture coordinate data; through the CPU memory related to the GPU memory area used by GPU;

The official explanation: Vertex data may [be sourced from arrays that are stored in application memory (via a pointer) or faster GPU (memory in a buffer (object). It means the vertex array stored in the program memory or fast GPU memory, the former to access the data, through an array of pointers to the latter directly through Buffer Objects access. [refers to VAOs or VBOs access]]

Draw the triangle array (three top (end) point coordinates) as follows:

OpenGL ES 2 (iOS) [01]: start with a small triangle
vertex array
OpenGL ES 2 (iOS) [01]: start with a small triangle

this is the knowledge of the C language, it should not be difficult to understand.

2) Vertex Buffer Objects (abbreviation: VBOs [Vertex Buffer Objects]), cache object, is holding the vertex array object [subscript data or data does not refer to the object inside the well, actually a memory block] GPU.

The official explanation: Buffer objects hold [vertex array data or indices in high-performance server memory. (meaning: VBOs is a cache object. The vertex data or subscript vertex data in GPU rapid memory area.) ]

Why is a. server?
–> a OpenGL, is designed based on CS mode, the client operation is equivalent to what we write OpenGL (OpenGL API commands) of various operations, the server is related to graphics hardware. ES, of course, that means

The official explanation: OpenGL is implemented [as a client-server system, with the application you write being considered the client, and the OpenGL implementation provided by the manufacturer of your computer graphics hardware being the server.]

1) [A.B. (ES) 2 Reference Card can be found in the official explanation…
2) [B.1] in the official explanation… “OpenGL Programming Guide” Introduction OpenGL 8th chapter of the first section of What Is OpenGL explained.

3 Vertex Shader (vertex shader):

Processing vertex related data, including the vertex position in the screen (matrix transformation), the vertex of the lighting calculation, texture coordinates, etc..

Vertex shader signal:

OpenGL ES 2 (iOS) [01]: start with a small triangle

Note: picture cut from: OpenGL ES 2 Guide Introduction 1 to ES OpenGL – OpenGL ES 2 – Vertex Shader section of the

1) input signal: Attributes, Uniforms, Samplers (optional)

A. Attributes: the meaning of attributes, each vertex data;

B. Uniforms:

B-1. unified meaning, is a read-only global constant, stored in the program
b-2. constant region; when Vertex Shader and Fragment Shader defines the name of the same type Uniform constant, the Uniform constant becomes global constants (pointing to the same memory area constant);

C. Samplers (optional):
is a special Uniforms save is Texteures (texture) data;

2) output signal: Varying

A. It is the interface between Vertex Shader and Fragment Shader, is to solve the functional problem (two Shader information interaction);

B. store Vertex Shader output information;

C. Vertex Shader and Fragment Shader must have the same type of Varying must be variable, otherwise it will compile error; (because it is the information interface two Shader ah, is not the same as what is connected to the mouth ah.)

3) interactive information: Temporary Variables

Temporary Variables:
A. refers to the temporary variable;
B. stored in the middle value of the Shader process used;
C. declaration in Funtions (function) or Variable (variable) inside;

4) output built-in variables: gl_Position, gl_FrontFacing, gl_PointSize

A. gl_Position (highp vec4):
is the output value of Vertex Position, Vertex Shader, and must be assigned variables; only in the use of Vertex Shader will be effective;

Note: highp vec4, highp (high precision) high precision means, is the precision qualifier; vec4 (Floating Point Vector) floating point vector, OpenGL ES data types.

B. gl_PointSize (mediump float
Vertex Shader variables): tell the grid point size (pixels pixel), want to change the drawing point size is to use this variable only in the Vertex Shader to be effective;

Note: mediump, mediump (medium precision) medium precision means, is the precision qualifier; and the last one is lowp (low precision), low precision means.

C. gl_FrontFacing (bool variable):
Front Facing to change the render object and Back Facing, is used for processing object variable illumination, double-sided light (3D objects inside and outside light) when the problem will use variables can only be set in Vertex Shader, Fragment Shader is read-only;

4 Primitive Assembly (Graphic assembly):

1) the first step, the Vertex Shader after the treatment of vertex data into OpenGL ES can directly render the basic graphics: points, lines, triangles;

2) the second step, cutting (Clipping), only retained in the rendering area (visual cone, visual area) in the image;

3) the second step, eliminate (Culling), can be programmed to eliminate the front, back, or all;

cones, is actually a three-dimensional cone contains regions of space formed by the camera and the object capture
OpenGL ES 2 (iOS) [01]: start with a small triangle
; cones photograph “explain” a perspective projection

5 Rasterization (rasterization):

Grating signal:

OpenGL ES 2 (iOS) [01]: start with a small triangle

The role is, will the basic primitives (points, lines, triangles) into a two-dimensional sheet element (Fragment, include 2D coordinates, color value, texture coordinates, pixel attributes and so on) the basic elements which can draw on the screen (display).

6 Texture Memory (texture memory):

Texture refers to the preservation of the picture (bitmap) of all the colors of the cache; Texture Memory is the color of a picture (pixels) memory; the size of the Texture Memory of each embedded system is limited;

1) the full iOS rendering pipeline diagram, pointing to the dotted line of Vertex Shader, means that the Texture Coordinate (texture coordinates) information is provided by the program to it;

2) complete iOS rendering pipeline map, line point to Fragment Shader, because Fragment Shader is the raster data, i.e. pixel data, and Texture itself is the pixel data, so Texture Memory can be used as the input of Shader Fragment;

7 Fragment Shader (sheet shader):

Pixel shader:

OpenGL ES 2 (iOS) [01]: start with a small triangle

1) input signal: Varying, Uniforms, Samples
and Vertex Shader input is the same meaning, please refer to the specific interpretation of the Vertex Shader ~ ~ ~ ~ ~;

2) input built-in variables: gl_FragCoord, gl_FrontFacing, gl_PointCoord

A. gl_FragCoord (mediump vec4 read-only variables):
is the relative coordinates of the window to save the {x, y, Z, 1/w} variable, Z represents the depth (will be used the fragment’s depth), w said rotation;

B. gl_PointCoord (mediump int read only variable):
is the current two-dimensional coordinates of the original point of the original location of the unit; point range is [0, 1];

C. gl_FrontFacing:
please view the explanation at Vertex Shader;

3) output signal (built-in variables): gl_FragColor, gl_FragData (not written on the map)

A. gl_FragColor (mediump vec4):
chip color value;

B. gl_FragData (mediump vec4):
is an array of meta color sets;

Note: the two output signal can only exist at the same time a gl_FragColor is to write, write gl_FragData, not vice versa; If a shader statically assigns [a value to gl_FragColor, it may not assign a value to any element of gl_FragData. If a shader statically writes a value to any element of gl_FragData, it may not assign a value to gl_FragColor. That is, a shader may assign values to either gl_FragColor or gl_FragData but not both.]

Supplemental knowledge (For Shader)
OpenGL ES 2 (iOS) [01]: start with a small triangle

8 Per-Fragment Operations:

Signal graph:

OpenGL ES 2 (iOS) [01]: start with a small triangle

1) Pixel ownership test (:
pixels belonging test) whether the pixel location in Framebuffer is not for the current OpenGL ES Context, which is a test of whether a pixel belongs to the current Context or whether it is displayed (whether by user visible);

2) Scissor Test (clipping test):
to determine whether the pixel is defined in the clipping area defined by glScissor*, and the pixels that are not within the clipping region will be discarded;

3) Stencil Test (template test):
template cache value and a reference value for comparison, so as to deal with the corresponding;

4) Depth Test (depth test):
compares the depth of the next fragment with the depth of the fragment in the frame buffer, thereby determining which pixel is in front and which pixel is occluded;

5 (Blending):
(mixed) the color of the fragment and the existing color values in the frame buffer to be mixed, and the new value of the mixed write to the frame buffer (FrameBuffer);

6) Dithering:
(jitter) using a limited color let you see is more colorful than the actual image display mode, in order to alleviate the value of the color accuracy is not big enough and cause color change problem.

9 Render Buffer & Frame Buffer:

Relation graph:

OpenGL ES 2 (iOS) [01]: start with a small triangle

1) Render Buffer (render cache):

A. RBO, Render Buffer Object;
B. (Application) by the program is assigned 2D
C. Render Buffer image cache; can be allocated and storage (color), color depth (depth), template (stectil) value, also can put the three values are loaded into the Frame Buffer;

2) Frame Buffer (frame buffer):

A. FBO, Frame Buffer Object;
B. is the color, depth, the template cache loaded at FBO all loading point collection;
C. attribute state the size and type of color, depth, template;
D. attribute state name Texture;
E. Render description loaded on FBO Buffer Objects (renderbuffer object) the state of the property;

The expansion of knowledge (FBO): FBO API support operation is as follows:
1) only through the OpenGL ES command (API) to create FBO object;
2) using a EGL Context to create and use a number of FBO, that is not to create a rendering context of each FBO object (rendering context);
off-screen, 3) to create the color depth, texture and template renderbuffer loading in FBO;
4) through multiple FBO to share the color, depth, template cache;
5) properly loaded texture color or depth to FBO, to avoid copying;


OpenGL ES 2 (iOS) [01]: start with a small triangle

The official is EGL API and platform independent, because it itself can be customized platform, so iOS has been customized under the Apple EAGL API.

EAGL.h: inside the core class is EAGLContext, context;
EAGLDrawable.h: EAGLContext for rendering rendering output classification;

Note: in addition to the above two, there is a class CAEAGLLayer, which is the iOS end of the rendering window layer;

[see here:
1) EGL API is designed for the purpose of OpenGL ES 2 can be in the window system (screen, iOS is the CAEAGLLayer class for the boarding layer) rendering rendering;

2) EGL rendering can be based on the premise that:

A. can display device (iOS or
of mobile phone simulator) to create B. (rendering surface), surface rendering device screen (on-screen) or (pixel Buffer) pixel cache (off-screen)

Note: pixel Buffer, the buffer is not directly display, can only become a rendering surface or by other API sharing out, such as: Pbuffers is often used in Texture maps, because Texture itself is a pixel;

3) create the rendering context (rendering context), that is, OpenGL ES 2 Rendering Context;

Note: OpenGL ES Context: save all data and status information rendering process;

OpenGL ES 2 (iOS) [01]: start with a small triangle

graphic interpretation: picture cut from RW., Beginning. OpenGL ES.and.GLKit Tutorials tutorial

Brief introduction of Language ES Shader OpenGL

Flow chart in the Vertex Shader and Fragment Shader is to use the GLSL ES language for programming

1 GLSL ES version:

OpenGL ES 2 corresponds to the GLSL version of the ES is 1, the version number is 100;

2 iOS Shader class:

IOS environment provides a simple Shader GLKit – class GLKBaseEffect;

OpenGL ES 2 (iOS) [01]: start with a small triangle

3 OpenGL itself is a C Base language, can adapt to multiple platforms, and in the iOS package is GLKit;

4 GLSL ES (also known as ESSL)?

Simple flow chart:

OpenGL ES 2 (iOS) [01]: start with a small triangle
ES Shader flow chart of OpenGL

1) write Shader code:

At the same time, a. Code and Fragment Code
write Vertex B. to write the proposal in the form of a document, does not recommend the use of “… A string written…”, the former will have compiler hints as an auxiliary to prevent certain input errors, but the latter does not, in order to unnecessary trouble, the use of the former should form xxxVertexShader.glsl /; xxxFragmentShader.glsl uses the C. file name

(Note: in fact, the file name and suffix can be arbitrary, but you when programming for readability, suggest such writing, but also to prevent unnecessary trouble; Xcode) [only in the file suffix glsl file to indicate, of course, sometimes a wind is normal]

D. to grasp the knowledge of the Shader is Data Typies (data types, such as: GLfloat, etc.), Build-in Variables (built-in variables, such as: attribute, etc.), process control statements (if, etc.);

2) in addition to the preparation of Shader Code, the other processes are a corresponding GLSL ES API (function) for the corresponding operation;

Note: This is just a Program map, not only can have a Program, but can have more than one, need to use how many, determined by the specific project.

The third step, how to draw (actual)

In this paper, the small triangle, for example, start the waves ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~!

OpenGL ES 2 (iOS) [01]: start with a small triangle

OpenGL ES 2 rendering process actual rendering environment, process refinement

OpenGL ES 2 (iOS) [01]: start with a small triangle
ES 2 iOS rendering logic flow chart.Png OpenGL

1 configuration environment:

1) the main task is to set up the EAGL API.

OpenGL ES 2 (iOS) [01]: start with a small triangle
EAGL Class

2) core operations:

A. CAEAGLLayer to replace the default CALayer configuration,
B. EAGLContext, drawing property; Render Context, OpenGL ES API is set to 2, and make it become the active context;
C. Frame Buffers / Render Buffer to create and use, and the content of
D. binding; EAGLContext binding (on-screen), rendering window CAEAGLLayer;

CAEAGLLayer extension:
OpenGL ES 2 (iOS) [01]: start with a small triangle

inheritance chain CALayer CAEAGLLayer also has some, of course; 2)
a. The CAEAGLLayer class: supports drawing OpenGL content in iPhone applications. If you plan to use OpenGL for your rendering, use this class as the backing layer for your views by returning it from your view “s layerClass class method. The returned CAEAGLLayer object is a wrapper for a Core Animation surface that is fully compatible with OpenGL ES function calls.
–&gt CAEAGLLayer; it is dedicated to rendering OpenGL, ES content of the OpenGL layer; if you want to use to override the layerClass method. B. Prior to designating the layer s associated view as the “render target for a graphics context, you can change the rendering attributes you want using the drawableProperties property.
–> it is in the EAGLContext bound CAEAGLLayer prior to the rendering window, can be changed by modifying the drawableProperties attribute attribute rendering. 3) Note:
A. used to modify the opaque property to YES (CAEAGLLayer.opaque = YES;
; B.) Transform
C. do not change; when the screen switch, and Rotate not to change the CAEAGLLayer Transform, but through OpenGL / OpenGL to ES Rotate to render content. EAGLContext
is the management of OpenGL ES rendering context (including information, and the state of the openGL ES command (API), OpenGL ES needs to draw resources) object, to use the OpenGL ES API (command) will make the Context become the active rendering context. (source: An EAGLContext object manages an OpenGL ES rendering context the state information, commands and, resources needed to draw using OpenGL ES. To execute OpenGL ES commands, you need a current rendering context.)

2 initialization data

Here is mainly to consider whether to use VBOs, because the mobile terminal to the efficiency requirements, so the general use of VBOs cache;

3 configuration OpenGL ES Shader

1) the core of the work is Shader Code, that is, learning GLSL ES language;
2) iOS end using glsl suffix to write the code file;

4 render

1 here is the need to pay attention to empty the old cache, set the window, although only a question of the code, but it is still very important;
2) is the core of learning glDraw* draw API;

Process code

1 configuration rendering environment

1) configure the render window [from UIView]

A. rewriting layerClass class method

(Class) layerClass {return [CAEAGLLayer class]};}

B. configuration drawableProperties, is to draw the attributes

- (void) commit {CAEAGLLayer = *glLayer (CAEAGLLayer * self.layer); / / Drawable / / A. / / Property Keys / * kEAGLDrawablePropertyRetainedBacking The key specifying whether the drawable surface retains its contents after displaying them. kEAGLDrawablePropertyColorFormat key specifying / / b. / / The the internal color buffer format for the drawable surface. * / glLayer.drawableProperties = @{kEAGLDrawablePropertyRetainedBacking: @ (YES), / / retained unchange kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8 / / 32-bits Color [UIScreen}; glLayer.contentsScale = mainScreen].scale; glLayer.opaque = YES;}

2) configuring rendering context

The definition of EAGLContext @interface VFGLTriangleView (/ / a.) @property (assign, nonatomic) VertexDataMode vertexMode @property (strong, nonatomic); EAGLContext *context; @end
The use of OpenGL / / b. ES 2 API, and the Context has become the active Context - (void) settingContext [[EAGLContext alloc] {self.context = initWithAPI:kEAGLRenderingAPIOpenGLES2]; [EAGLContext setCurrentContext:self.context];}

3) frame rendering

- (GLuint) createFrameBuffer {GLuint ID; glGenFramebuffers (FrameMemoryBlock, & ID); glBindFramebuffer (GL_FRAMEBUFFER, ID); return ID;}
function describe
GlGenFramebuffers Create frame buffer object
GlBindFramebuffer Frame buffer object
Void glGenFramebuffers (GLsizei n, GLuint * framebuffers)
N refers to the number of Frame Buffer objects returned
Framebuffers refers to the memory address of the identifier of the Frame Buffer object
Void glBindFramebuffer (GLenum target, GLuint framebuffer)
Target can only fill GL_FRAMEBUFFER
Framebuffer refers to the identifier of the Frame Buffer object

4) configuration render cache

- (GLuint) createRenderBuffer {GLuint ID; glGenRenderbuffers (RenderMemoryBlock, & ID); glBindRenderbuffer (GL_RENDERBUFFER, ID); return ID;}
function describe
GlGenRenderbuffers Create render cache object
GlBindRenderbuffer Render cache object
Void glGenRenderbuffers (GLsizei n, GLuint *renderbuffers)
N refers to the number of Render Buffer objects returned
Renderbuffers refers to the memory address of the identifier of the Render Buffer object
Void glBindRenderbuffer (GLenum target, GLuint renderbuffer)
Target can only fill GL_RENDERBUFFER
Renderbuffers refers to the identifier of the Render Buffer object

5) the frame cache loads the contents of the render cache

- (void) attachRenderBufferToFrameBufferWithRenderID: (GLuint) renderBufferID {glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderBufferID);}
function describe
GlFramebufferRenderbuffer Load the contents of the render cache to the frame buffer object
Void glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
Target can only fill GL_FRAMEBUFFER
Attachment can only be one of three: GL_COLOR_ATTACHMENT0 (color cache), GL_DEPTH_ATTACHMENT (depth buffer), GL_STENCIL_ATTACHMENT (template cache)
Renderbuffertarget can only fill GL_RENDERBUFFER
Renderbuffer refers to the identifier of the Render Buffer object, and the current Render Buffer object must be available

6) rendering context binding rendering window (layer)

- (void) bindDrawableObjectToRenderBuffer {[self.context fromDrawable: (CAEAGLLayer *) self.layer];}; renderbufferStorage:GL_RENDERBUFFER
function describe
RenderbufferStorage: fromDrawable: Associate current rendering context and render window
RenderbufferStorage: fromDrawable:
– (BOOL) renderbufferStorage: (NSUInteger) target fromDrawable: (id< EAGLDrawable>) drawable
Target can only fill GL_RENDERBUFFER
Drawable can only be CAEAGLLayer object

1) in order to create the Render Buffer content can be displayed on the screen, in order to use this function to bind Render Buffer and distributed shared memory;
2) to display the contents of the Buffer Render, you must use presentRenderbuffer to display content;
: 3) the function is equivalent to OpenGL in ES it [the content is too much, Jane books don’t
OpenGL ES 2 (iOS) [01]: start with a small triangle
] typesetting function to describe the glRenderbufferStorage content glRenderbufferStorage void glRenderbufferStorage save renderbuffer (GLenum target, GLenum internalformat, GLsizei width, GLsizei height target GL_RENDERBUFFER internalformat) can only be filled with three kinds of color render buffer, depth render, buffer stencil Render buffer width pixels, the size must be < GL_MAX_RENDERBUFFER_SIZE = height pixels, the size must be < GL_MAX_RENDERBUFFER_SIZE = color render buffer [01] GL_RGB565 internalformat, GL_RGBA4, GL_RGB5_A1, color render buffer [02] GL_RGB8_OES, GL_RGBA8_OES depth render buffer [01] GL_DEPTH_COMPONENT16, depth render buffer [02] GL_DEPTH_COMPONENT24_OES, GL_DEPTH_COMPONENT32_OE stencil render buffer GL_STENCIL_INDEX8, GL_STENCIL_INDEX4_OES, GL_STENCIL_INDEX1_OE

2 modify the background color

Typedef struct {CGFloat red; CGFloat green; CGFloat blue; CGFloat alpha; RGBAColor static inline RGBAColor}; RGBAColorMake (CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha) {RGBAColor color = {.Red = red,.Green = green,.Blue = blue,.Alpha = Alpha, return}; color;} - (void setRenderBackgroundColor: color (RGBAColor)) {glClearColor (,,, color.alpha);}
function describe
GlClearColor Empty Render Buffer Render Buffer for RGBA color Color
Void glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
Red refers to the red value of [0, 1]
Green refers to the green value of [0, 1]
Blue refers to [0, 1] blue value
Alpha refers to [0, 1] transparency value

Note: do not want to define the RGBAColor, you can directly use the GLKit provided by GLKVector4, the prototype is #if defined (__STRICT_ANSI__) struct _GLKVector4 {float v[4];} (__attribute__ (aligned (16))); typedef struct _GLKVector4 GLKVector4; #else union _GLKVector4 {struct {float x, y, Z, w;}; struct {float R, G, B, a;}; / / in the… Struct… T, s {float, P, q; float v[4];}}; __attribute__ ((aligned (16))); typedef union _GLKVector4 GLKVector4; / / is a common body of #endif GLK_INLINE GLKVector4 (float x, GLKVector4Make float y, float Z, float w) {GLKVector4 v = {x, y, Z, w return V;}};

3 initialization data

If you want to use VBOs is best to create a VBOs object and bind the vertex data here, of course, directly in the association data step by step is also no problem;

#define VertexBufferMemoryBlock (1) - (GLuint) createVBO {GLuint vertexBufferID; glGenBuffers (VertexBufferMemoryBlock, & vertexBufferID); return vertexBufferID;} #define PositionCoordinateCount (3) typedef struct {GLfloat position[PositionCoordinateCount]}; VFVertex static; const VFVertex vertices[] = {{{-0.5f, -0.5f, 0.0}}, left / / lower corner 0.5f -0.5f, 0.0}}, turning. Right corner / / lower {{-0.5f, 0.5f, 0.0}}, left, upper / corner}; - (void) bindVertexDatasWithVertexBufferID: (GLuint vertexBufferID) {glBindBuffer (GL_ARRAY_BUFFER, vertexBufferID); / / create a resource (context) glBufferData (GL_ARRAY_BUFFER / cache block type sizeof (vertices), / / create The cache block size vertices, GL_STATIC_DRAW / / vertex data to bind); / / cache block use}
function describe
GlGenBuffers Apply VBOs object memory
GlBindBuffer Bind VBOs object
GlBufferData Associate vertex data and create memory
Void glGenBuffers (GLsizei n, GLuint * buffers)
N refers to how many VBO to return
Buffers refers to the VBO identifier memory address
Void glBindBuffer (GLenum target, GLuint buffer)
Buffer means VBO identifier
Void glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage)
Size bytes of data in memory size (sizeof (…))
Data vertex data memory pointer
Usage tells the program how to use these vertex data
Usage value
GL_STATIC_DRAW The program specifies only once the data of the memory object (vertex data), and the data will be used many times (very often) for drawing primitives.
GL_DYNAMIC_DRAW The program continuously specifies the data (vertex data) of the memory object, and the data will be used for drawing primitives many times.
GL_STREAM_DRAW The program specifies only once the data of the memory object (vertex data), and the data will be several times (several times uncertain) for drawing primitives.

GlGenBuffers, glBindBuffer, glBufferData have done?

1) glGenBuffers will be in OpenGL ES Context (GPU) inside, to apply for a designated size of the memory area;

2 (glBindBuffer) will be applied to that piece of memory is declared as GL_ARRAY_BUFFER, is what kind of memory to use;

3 (glBufferData) associated with the vertex data stored in the program memory (CPU memory) to the area of memory just applied;

OpenGL ES 2 (iOS) [01]: start with a small triangle

Note: the picture cut from RW., Beginning. OpenGL ES.and.GLKit Tutorials tutorial; the picture of the 3 vertex data copy) ~ ~ ~ ~ “correct” 3) associated with the vertex data, because the copy from CPU data to GPU is in the OpenGL ES (triggering method of drawing into the back) will be time;

4 configuration OpenGL ES Shader

1) write Vertex Shader Code file

A. This is the form of the document, it is recommended to use this, Xcode will be key words

#version 100 attribute v_Position; void main (void) {gl_Position = v_Position;}
OpenGL ES 2 (iOS) [01]: start with a small triangle
a corresponds to the picture

B. This is a direct GLchar * string form

+ (GLchar * vertexShaderCode) {return "#version 100 /n" attribute "vec4 v_Position /n"; "void main (void) {/n" gl_Position = v_Position ";" /n ";}}"
OpenGL ES 2 (iOS) [01]: start with a small triangle
B corresponds to the picture

It is clear that a, regardless of writing and reading are very easy, and B is a bunch of red, I do not know what the ghost, look at the eyes will be very tired for a long time;

Interpretation of the code:
a. #version 100, the first OpenGL ES 2 version of the GLSL ES is used, this is nothing to explain. “OpenGL ES 2 programming Guide” has referred to

OpenGL ES 2 (iOS) [01]: start with a small triangle

also shows that when we write GLSL Code, we use the language version of “OpenGL ES Shading Language”;

OpenGL ES 2 (iOS) [01]: start with a small triangle

B. attribute v_Position vec4,
attribute storage type qualifier, said link, link OpenGL ES each vertex data to the vertex shader (one by one);

1) attribute vec2, vec3 can only define float, vec4, mat2, mat3, mat4 these types of variables cannot be structure or array;
2) can only be used in the vertex shader, cannot be used in the fragment shader, it will compile error;

Additional storage type qualifiers

qualifier describe
None (default) represents the local read-write memory or input parameters
Const That represents the compile – time fixed or read-only function parameters
Attribute Represents a link that links each vertex data of the OpenGL ES to the vertex shader (one by one)
Uniform Represents a variable that cannot be changed when it is being processed, a linker, a OpenGL ES, and a shader variable
Varying Represents the internal data of the link vertex shader and the pixel shader

B-2. [vec4], the basic data types, directly above

OpenGL ES 2 (iOS) [01]: start with a small triangle

Note: picture cut from, OpenGL ES Language 1 Reference Card Quick Page 3

C. gl_Position built-in variable
because vertex data inside

OpenGL ES 2 (iOS) [01]: start with a small triangle

Just use the Position vertex data;

2) write Fragment Shader Code file

A. file format

#version 100 void main (void) {gl_FragColor = vec4 (1, 1, 1, 1); / / fill color, white}

B. string form

* (GLchar *) fragmentShaderCode {return "#version 100 /n" "void main (void) {/n" "gl_FragColor = vec4 (1, 1, 1, 1);}}"}

3) configure Vertex Shader

- (GLuint) createShaderWithType: (GLenum type) {GLuint shaderID = glCreateShader (type); const (type = GLchar * code = = GL_VERTEX_SHADER)? [[self class] vertexShaderCode]: [[self class] fragmentShaderCode]; glShaderSource (shaderID, ShaderMemoryBlock, & code, NULL); return shaderID;} - (void) compileVertexShaderWithShaderID: (GLuint) shaderID type: (GLenum type) {glCompileShader (shaderID); GLint compileStatus; glGetShaderiv (shaderID, GL_COMPILE_STATUS, & compileStatus); if (compileStatus = = GL_FALSE) {GLint infoLength; glGetShaderiv (shaderID, GL_INFO_LOG_LENGTH, & infoLength); if (infoLength > 0) {GLch AR *infoLog = malloc (sizeof (GLchar) * infoLength); glGetShaderInfoLog (shaderID, infoLength, NULL, infoLog); NSLog (@%s ->%s (type = GL_VERTEX_SHADER), "?" vertex shader ":" fragment shader ", infoLog); free (infoLog);}}}
function describe
GlCreateShader Create a shader object
GlShaderSource Associated vertex, fragment shader code
GlCompileShader Compile shader code
GlGetShaderiv Gets information about the shader object
GlGetShaderInfoLog Gets the print message for the shader
GLuint glCreateShader (GLenum type)
Return GLuint returns the shader’s memory identifier
Void glShaderSource (GLuint shader, GLsizei count, const GLchar * const* string, const GLint* length)
Shader shader memory identifier
Count how many coloring code string resources
String shader code string pointer
Length shader code string length
Void glCompileShader (GLuint shader)
Shader shader memory identifier
Void glGetShaderiv (GLuint shader, GLenum pname, GLint *params)
Shader shader memory identifier
Pname specify the type of access to information, there are GL_COMPILE_STATUS, GL_DELETE_STATUS, GL_INFO_LOG_LENGTH, GL_SHADER_SOURCE_LENGTH, GL_SHADER_TYPE five
Params is used to store the variable memory address of the current information
Void glGetShaderInfoLog (GLuint shader, GLsizei maxLength, GLsei* length, GLchar *infoLog)
Shader shader memory identifier
MaxLength refers to the maximum length of information
Length access to the information length, if you do not know can be NULL
InfoLog memory address of the variable that stores the information

4) configure Fragment Shader
with 3) method;

5) create Shader Program

- (GLuint) createShaderProgram {return glCreateProgram ();}
function describe
GlCreateProgram Create Shader Program object
GLuint glCreateProgram ()
Return GLuint returns the identifier of the shader program

6) loading Vertex Shader and Fragment Shader

- (void) attachShaderToProgram: (GLuint) programID vertextShader: (GLuint) vertexShaderID fragmentShader: (GLuint fragmentShaderID) {glAttachShader (programID, vertexShaderID); glAttachShader (programID, fragmentShaderID);}
function describe
GlAttachShader Load Shader object
Void glAttachShader (GLuint program, GLuint shader)
Program shader program identifier
Shader to load the shader object identifier

7) link Shader Program

- (void) linkProgramWithProgramID: (GLuint programID) {glLinkProgram (programID); GLint linkStatus; glGetProgramiv (programID, GL_LINK_STATUS, & linkStatus); if (linkStatus = = GL_FALSE) {GLint infoLength; glGetProgramiv (programID, GL_INFO_LOG_LENGTH, & infoLength); if (infoLength > 0) {GLchar *infoLog = malloc (sizeof (GLchar) * infoLength); glGetProgramInfoLog (programID, infoLength, NULL, infoLog); NSLog (@ "%s", infoLog); free (infoLog);}}}
function describe
GlLinkProgram Link Shader Program object
GlGetProgramiv Gets information about the shader program
GlGetProgramInfoLog Gets the print information for the shader program
Void glLinkProgram (GLuint program)
Program shader program identifier
Void glGetProgramiv (GLuint program, GLenum pname, GLint *params)
Program shader program identifier
Params memory address of the variable that stores the information
Void glGetProgramInfoLog (GLuint program, GLsizei maxLength, GLsizei* length, GLchar *infoLog)
Program shader program identifier
MaxLength refers to the maximum length of information
Length access to the information length, if you do not know can be NULL
InfoLog memory address of the variable that stores the information

5 render

1) empty old render cache

- (void) clearRenderBuffer {glClear (GL_COLOR_BUFFER_BIT);}
function describe
GlClear Empty render cache old content
Void glClear (GLbitfield mask)
Mask three in a GL_COLOR_BUFFER_BIT (color cache), GL_DEPTH_BUFFER_BIT (depth cache), GL_STENCIL_BUFFER_BIT (template cache)

2) rendering window

- (void) setRenderViewPortWithCGRect: (CGRect) rect {glViewport (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);}
function describe
GlViewport Set the location and size of the render window
Void glViewport (GLint x, GLint y, GLsizei W, GLsizei h)
X, y rendering window offset screen coordinates of the lower left corner of the number of pixels
W, H rendering window width and height, the value must be greater than 0

3) using Shder Program

- (void) userShaderWithProgramID: (GLuint) programID {glUseProgram (programID)};}
function describe
GlUseProgram Use Shader Program
Void glUseProgram (GLuint program)
Program shader program identifier

4) associated data

#define VertexAttributePosition (0) #define StrideCloser (0) - attachTriangleVertexArrays (void) {glEnableVertexAttribArray (VertexAttributePosition); if (self.vertexMode = = VertexDataMode_VBO) {glVertexAttribPointer (VertexAttributePosition, PositionCoordinateCount, GL_FLOAT, GL_FALSE, sizeof (VFVertex), (const * GLvoid) offsetof (VFVertex, position));} else {glVertexAttribPointer (VertexAttributePosition, PositionCoordinateCount GL_FLOAT, GL_FALSE, StrideCloser, vertices);}}
function describe
GlEnableVertexAttribArray Enable vertex array data
GlVertexAttribPointer Associated vertex data

A. enable vertex cache

Void glEnableVertexAttribArray (GLuint index)
Index attribute variable subscript, the range is [0, GL_MAX_VERTEX_ATTRIBS – 1]

B. associated vertex data

Void glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *ptr)
Index attribute variable subscript, the range is [0, GL_MAX_VERTEX_ATTRIBS – 1]
Size refers to the top point of the group, a attribute element of the variable component is the number of coordinates (such as: position, the program is provided by {x, y, z} point is 3 coordinate components), the range is [1, 4]
Normalized refers to the meaning of data type conversion, GL_TRUE or GL_FALSE
Stride refers to the offset of each data in memory, if fill 0 (zero) is that each data closely next to.
PTR data memory first address

The expansion of knowledge:
1) to obtain the maximum attribute index method GLint maxVertexAttribs n will be; / / &gt = 8; glGetIntegerv (GL_MAX_VERTEX_ATTRIBS, & maxVertexAttribs); 2) on the size
OpenGL ES 2 (iOS) [01]: start with a small triangle
supplementary note, picture cut from, “OpenGL ES 2 Programming Guide” sixth chapter 3) enable vertex array data? In fact,
processing data in the vertex shader has two input types, CVOs (Constant
Vertex Objects), VAOs (Vertex Array Objects);
and glEnableVertexAttribArray, the glDisableVertexAttribArray function is the use of CVOs or VAOs in a group of pictures:
OpenGL ES 2 (iOS) [01]: start with a small triangle switch,
note: the picture cut from, “OpenGL ES 2 Programming Guide sixth” chapter if the use of CVOs as input data, to use the following function to replace the glVertexAttribPointer function OpenGL ES 2 (iOS) [01]: start with a small triangle
OpenGL ES 2 (iOS) [01]: start with a small triangle

: 4) OpenGL ES only supports the float-pointer data type, so there will be a normalized parameter; 5) vertex shader data transfer graph,
WPAP 60244602img
note: the picture cut from, “OpenGL ES 2 Programming Guide” sixth chapters to remind, VBOs is only a means to speed up the data access scheduling and rendering, and a data input mode;

It is strongly recommended that you take a look at the “OpenGL ES 2 Programming Guide” of the 6 Vertex Attributes, Vertex Arrays, and Buffer Objects this chapter;

5) drawing graphics

#define PositionStartIndex (0) #define DrawIndicesCount (3) - (void) drawTriangle (GL_TRIANGLES, PositionStartIndex, glDrawArrays {DrawIndicesCount});
function describe
GlDrawArrays Draw all primitives
Void glDrawArrays (GLenum mode, GLint first, GLsizei count)
First starts drawing from the first vertex index
Count refers to how many vertices need to be plotted

6) rendering graphics

- (void) render {[self.context presentRenderbuffer:GL_RENDERBUFFER];}
function describe
PresentRenderbuffer: The contents of the Renderbuffer display to the window system (CAEAGLLayer)
(BOOL) presentRenderbuffer: (NSUInteger) target
Target can only be GL_RENDERBUFFER
Return BOOL returns whether the binding is successful

Added: at the same time, this function also explains why the kEAGLDrawablePropertyRetainedBacking is set to YES
OpenGL ES 2 (iOS) [01]: start with a small triangle

: if you want to save the contents of the Renderbuffer to drawableProperties the CARAGLLayer property of the kEAGLDrawablePropertyRetainedBacking is set to YES.
OpenGL ES 2 (iOS) [01]: start with a small triangle

Above all the code of the project file, on the Github DrawTriangle_OneStep

Object oriented redesign:

The main process of message processing is the sequence of the signal flow chart above.
object oriented, that is, all the messages to the object to deal with the strategy, the focus is on the message delivery and processing. Can be designed according to your preferences, anyway, scalability and maintainability are better on the line, of course, can not pass the message becomes very complicated

OpenGL ES 2 (iOS) [01]: start with a small triangle
OpenGL ES 2 iOS rendering logic chart _ object-oriented

Project file structure:

OpenGL ES 2 (iOS) [01]: start with a small triangle

Complete code on Github DrawTriangle_OOP

OpenGL ES 2 (iOS) [01]: start with a small triangle

The fourth step, practice

Proposal to write a project in accordance with their own ideas

1 modify the background color

OpenGL ES 2 (iOS) [01]: start with a small triangle

Tip: glClear function

2 modify the fill color of the triangle:

OpenGL ES 2 (iOS) [01]: start with a small triangle

Tip: CVOs, three vertices are unified color data

3 modify the color of the three vertices of the triangle (fill color):

OpenGL ES 2 (iOS) [01]: start with a small triangle

Tip: VAOs / VBOs, add new color data based on three vertices

The three is to learn how to associate data, the corresponding project is: Github: DrawTriangle_OOP_Challenges_1

If you find any errors in the article, please comment in the comments area!!!