2012年4月4日 星期三

OpenGL ES 入門: 三. 透視觀點

since: 2012/04/04
update: 2012/04/04

reference:
1. 原文:
iPhone Development: OpenGL ES From the Ground Up, Part 3: Viewports in Perspective

2. 翻譯:
從零開始學習OpenGL ES之三 – 透視

透視觀點

A. 說明
     1. viewport: 可看成是虛擬的相機鏡頭(觀察者)所照到的範圍.

     2. 在 OpenGL ES 中具有的兩種不同的 viewport 類型:
         正交(orthographic)和透視(perspective)

     3. 正交(orthographic):
         這種類型的 viewport, 視線永遠不會交匯而且物體不會改變其大小. 沒有透視效果,
         看上去是不真實的. 對於正交 viewport, 就像你將攝影機置於鐵軌上, 但這些鐵軌永
         遠不會交匯. 它們將隨着遠離你的視線而繼續保持等距. 無論你定義了多大的
         viewport, 這些線仍保持等距. 正交 viewport 的優點是容易定義, 因為線永不交匯.

     4. 透視(perspective):
         物體會隨着移遠而越來越小, 視線會在物體移離觀察者時最終交匯. 這是對真實視覺
         的模擬; 人們就是以這種方式觀察世界的. 隨着視線越來越遠, 你可以看到更廣闊的
         世界, 所以如果你使用透視, 那麼你定義的空間將不是一個立方體, 而是稱為錐台
          (frustum) 的可見空間.

---------------------------------------------------------------------------------

B. 正交 viewport 設定方式
    1. 說明: 在使用 glViewport() 函數定義 viewport 前, 你可以通過 glOrthof()
                   通知 OpenGL ES 你希望使用正交 viewport.

    2. 例子:
    // 獲取視窗的尺寸
   
CGRect rect = view.bounds;

    // 設定 viewport 空間的寬度為兩個單位, 沿 x 軸從 -1.0 到 +1.0
    glOrthof(-1.0,                                                 // Left
                      1.0,                                                 // Right

    // 設定底部和頂部
    //
    // 定義空間的 X 和 Y 坐標的寬高比與視窗的寬高比.
    // 確保 viewport 的 x 和 y 坐標遵循一樣的比例.
                     -1.0 / (rect.size.width / rect.size.height),   // Bottom
                      1.0 / (rect.size.width / rect.size.height),   // Top

    // 定義 near (遠) 和 far (近) 範圍來描述觀察的深度
    //
    // near 參數說明了 viewport 開始的位置. 如果我們站在原點處, viewport 就位於
    // 我們的面前, 所以習慣上使用 .01 或 .001 作為正交 viewport 的起點. 這使得
    // viewport 處於原點 "前方" 一點點.
    //
    // far 可以根據你程序的需要來設定. 如果你程序中的物體永遠不會遠過20個單位,
    // 那麼你不需要將 far 設置為 20,000 個單位. 具體的數字隨程序的不同而不同.
                      0.01,                                         // Near
                      10000.0);                                     // Far

    // 使用視窗矩形來呼叫 glViewport()
    glViewport(0, 0, rect.size.width, rect.size.height);

---------------------------------------------------------------------------------

C. 透視 viewport 設定方式
     1. 說明: 
         a. 要設定透視 viewport , 我們使用 glFrustumf() 函數.

         b. 要計算錐台,我們首先要理解視野 (field of vision) 的概念, 它是由兩個角度
             定義的, 並決定了左右與上下的視野寬度(有窄視野與寬視角之分).

         c. 如果用攝影術語描述, 你可將視野當作虛擬相機的虛擬光圈的焦距. 窄視野很像
             攝遠鏡頭, 它造就了一個緩慢增長的長錐台. 寬視角就像廣角鏡, 它造就了一個
             增長很快的錐台.

     2. 例子:
CGRect rect = view.bounds; 

// 取視角 (45度) 一半的正切值
GLfloat size = .01 * tanf(DEGREES_TO_RADIANS(45.0) / 2.0); 

glFrustumf(-size,                                           // Left
            size,                                           // Right
           -size / (rect.size.width / rect.size.height),     // Bottom
            size / (rect.size.width / rect.size.height),    // Top
            .01,                                           // Near
            1000.0);                                      // Far

---------------------------------------------------------------------------------

D. 繪製透視多面體的前置作業
     1. 開啓 GLView.h 檔案, 修改如下:
....
@protocol GLViewDelegate

@required
- (void)setupView:(GLView *)view;

@optional
//@update for drawing
- (void)drawView:(GLView *)view;
- (void)drawTriangle3D; // 畫三角形
- (void)drawSquare; // 畫正方形
- (void)drawVertexColor; // 畫頂點顏色
- (void)drawIcosahedron; // 畫二十面體
- (void)drawPerspective; // 畫透視多面體

@end
....

     2. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫透視多面體
- (void)drawPerspective
{
    NSLog(@"ViewController => drawPerspective");
    // Draw code here
}
....

     3. 開啓 GLView.m 檔案, 修改如下:
....
- (void)drawView
{
....
    //[self.delegate drawTriangle3D]; // 畫三角形
    //[self.delegate drawSquare]; // 畫正方形
    //[self.delegate drawVertexColor]; // 畫頂點顏色
    //[self.delegate drawIcosahedron]; // 畫二十面體
    [self.delegate drawPerspective]; // 畫透視多面體
....
}
....

---------------------------------------------------------------------------------


E. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫透視多面體
- (void)drawPerspective
{
    NSLog(@"ViewController => drawPerspective");
    // Draw code here
    //
    // 1. 建立了一個靜態變數來跟蹤物體的旋轉
    static GLfloat rot = 0.0;
   
    // 2. 定義頂點陣列:
    //
    // 使用了一個與前不同的方法, 但結果是一樣的. 由於我們的幾何體根本不會變化,
    // 所以我們將其定義為 const, 這樣就不需要每一 frame 都分配/清除記憶體:
    static const Vertex3D vertices[]= {
        {0, -0.525731, 0.850651},             // vertices[0]
        {0.850651, 0, 0.525731},              // vertices[1]
        {0.850651, 0, -0.525731},             // vertices[2]
        {-0.850651, 0, -0.525731},            // vertices[3]
        {-0.850651, 0, 0.525731},             // vertices[4]
        {-0.525731, 0.850651, 0},             // vertices[5]
        {0.525731, 0.850651, 0},              // vertices[6]
        {0.525731, -0.850651, 0},             // vertices[7]
        {-0.525731, -0.850651, 0},            // vertices[8]
        {0, -0.525731, -0.850651},            // vertices[9]
        {0, 0.525731, -0.850651},             // vertices[10]
        {0, 0.525731, 0.850651}               // vertices[11]
    };
   
    // 3. 建立一個顏色陣列:
    //
    // 創建一個 Color3D 物件陣列, 每項對應於前一個陣列的頂點:
    static const Color3D colors[] = {
        {1.0, 0.0, 0.0, 1.0},
        {1.0, 0.5, 0.0, 1.0},
        {1.0, 1.0, 0.0, 1.0},
        {0.5, 1.0, 0.0, 1.0},
        {0.0, 1.0, 0.0, 1.0},
        {0.0, 1.0, 0.5, 1.0},
        {0.0, 1.0, 1.0, 1.0},
        {0.0, 0.5, 1.0, 1.0},
        {0.0, 0.0, 1.0, 1.0},
        {0.5, 0.0, 1.0, 1.0},
        {1.0, 0.0, 1.0, 1.0},
        {1.0, 0.0, 0.5, 1.0}
    };
   
    // 4. 建立二十面體:
    //
    // 上述十二個頂點本身並未描述形狀. OpenGL 需要知道怎樣將它們聯繫在一起,
    // 所以我們建立了一個整數陣列 (GLubyte) 指向構成各三角形的頂點.
    //
    // 二十面體的第一個面的三個數是 1,2,6 代表繪製處於索引1 (0.850651, 0, 0.525731),
    // 2 (0.850651, 0, 0.525731), 和 6 (0.525731, 0.850651, 0) 之間的三角形.
    static const GLubyte icosahedronFaces[] = {
        1, 2, 6,
        1, 7, 2,
        3, 4, 5,
        4, 3, 8,
        6, 5, 11,
        5, 6, 10,
        9, 10, 2,
        10, 9, 3,
        7, 8, 9,
        8, 7, 0,
        11, 0, 1,
        0, 11, 4,
        6, 2, 10,
        1, 6, 11,
        3, 5, 10,
        5, 4, 11,
        2, 7, 9,
        7, 1, 0,
        3, 9, 8,
        4, 8, 0,
    };
   
    // 5.
    //
    // 加載單元矩陣
    glLoadIdentity();
   
    // 移動
    //glTranslatef(0.0f,0.0f,-3.0f);
   
    // 旋轉
    //glRotatef(rot,1.0f,1.0f,1.0f);   
   
    // 設置背景色
    glClearColor(0.7, 0.7, 0.7, 1.0);
   
    // 清除緩存
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   
    // 啟動頂點陣列
    glEnableClientState(GL_VERTEX_ARRAY);
   
    // 啟動顏色陣列
    glEnableClientState(GL_COLOR_ARRAY);
   
    // 提供頂點陣列內容給 OpenGL
    glVertexPointer(3, GL_FLOAT, 0, vertices);
   
    // 提供顏色陣列內容給 OpenGL
    glColorPointer(4, GL_FLOAT, 0, colors);
   
    for (int i = 1; i <= 30; i++)
    {
        glLoadIdentity();
       
        // 移動
        glTranslatef(0.0f,-1.5,-3.0f * (GLfloat)i);
       
        // 旋轉
        glRotatef(rot, 1.0, 1.0, 1.0);
       
        // 6. 不使用 glDrawArrays(), 而是使用 glDrawElements():
        //
        // 備註: 如果你按繪製的正確次序提供頂點, 那麼你應該使用 glDrawArrays(),
        //       但是如果你提供一個陣列然後用另一個以索引值區分頂點次序的陣列的話,
        //       那麼你應該使用 glDrawElements().
        glDrawElements(GL_TRIANGLES, 60, GL_UNSIGNED_BYTE, icosahedronFaces);
    }
   
    // 7. 執行禁止功能
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
   
    // 8. 根據上一個 frame 繪製的時間增加旋轉變量值:
    static NSTimeInterval lastDrawTime;
    if (lastDrawTime)
    {
        NSTimeInterval timeSinceLastDraw = [NSDate timeIntervalSinceReferenceDate] - lastDrawTime;
        rot += 50 * timeSinceLastDraw;
    }
    lastDrawTime = [NSDate timeIntervalSinceReferenceDate];
}
....
//@add for <GLViewDelegate> method

-(void)setupView:(GLView *)view
{
    NSLog(@"step 05. ViewController => setupView:");
   
    const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0; // 設定為 45 度視野
    GLfloat size;
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
   
    CGRect rect = view.bounds;

    // 設定透視 viewport (基於視野角度計算錐台)
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size /
               (rect.size.width / rect.size.height), zNear, zFar);
   
    // 建構一個對應的座標系統
    glViewport(0, 0, rect.size.width, rect.size.height); 
   
    glMatrixMode(GL_MODELVIEW);
   
    glLoadIdentity();
}
....

    編譯並執行:
    隨着多面體遠離你, 它們會變得越來越小, 正像火車鐵軌一樣.

---------------------------------------------------------------------------------
F. 正交多面體的情況
      1. 開啓 ViewController.m 檔案, 修改如下:
....
-(void)setupView:(GLView *)view
{
    NSLog(@"step 05. ViewController => setupView:");
   
    const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0; // 設定為 45 度視野
    GLfloat size;
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
   
    CGRect rect = view.bounds;

    // 設定透視 viewport (基於視野角度計算錐台)
    /*
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size /
               (rect.size.width / rect.size.height), zNear, zFar);
    */
   
    // 設定正交 viewport (基於視野角度計算錐台)
    /* // not work
    glOrthof(-size, size, -size / (rect.size.width / rect.size.height), size /
               (rect.size.width / rect.size.height), zNear, zFar);
    */
    glOrthof(-1.0,                                // Left
             1.0,                                          // Right
             -1.0 / (rect.size.width / rect.size.height),   // Bottom
             1.0 / (rect.size.width / rect.size.height),   // Top
             0.01,                                         // Near
             10000.0);                                     // Far   
    
    // 建構一個對應的座標系統
    glViewport(0, 0, rect.size.width, rect.size.height); 
   
    glMatrixMode(GL_MODELVIEW);
   
    glLoadIdentity();
}
....

      2. 編譯並執行:
    說明: 沒有透視. 第一個二十面體後面的二十九個二十面體完全被第一個擋住了.
               因為沒有透視, 後面的各幾何體的形狀完全取決於其前方的物體.

OpenGL ES 入門: 二. 簡單繪圖之五

since: 2012/04/04
update: 2012/04/04

reference:
1. 原文:
iPhone Development: OpenGL ES From the Ground Up, Part 2: A Look at Simple Drawing

2. 翻譯:
從零開始學習OpenGL ES之二 – 簡單繪圖概述


簡單繪圖之五: 繪製二十面體

A. 說明
      當處理複雜的幾何體時, 有一種方法可以避免多次傳遞同一個頂點, 就是使用通過
      頂點對應於頂點陣列中的索引的方法, 此方法稱之為元素 (elements).

-----------------------------------------------------------------------------------------

B. 繪製多面體的前置作業
     1. 開啓 GLView.h 檔案, 修改如下:
....
@protocol GLViewDelegate

@required
- (void)setupView:(GLView *)view;

@optional
//@update for drawing
- (void)drawView:(GLView *)view;
- (void)drawTriangle3D; // 畫三角形
- (void)drawSquare; // 畫正方形
- (void)drawVertexColor; // 畫頂點顏色
- (void)drawIcosahedron; // 畫二十面體

@end

     2. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫二十面體
- (void)drawIcosahedron
{
    NSLog(@"ViewController => drawIcosahedron");
    // Draw code here
}
....

     3. 開啓 GLView.m 檔案, 修改如下:
....
- (void)drawView
{
....
    //@update for drawing
    //[self.delegate drawTriangle3D]; // 畫三角形
    //[self.delegate drawSquare]; // 畫正方形
    //[self.delegate drawVertexColor]; // 畫頂點顏色
    [self.delegate drawIcosahedron]; // 畫二十面體
....
    //@add for Rendering Frequency
    int intCount = [self.currentRunCount intValue] + 1;
    self.currentRunCount = [NSNumber numberWithInt:intCount];
   
    if (intCount >= self.totalRunTime * kRenderingFrequency) {

        [self stopAnimation];
    }
    //@update for run once
    //[self stopAnimation];
}
....

-----------------------------------------------------------------------------------------

C. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫二十面體
- (void)drawIcosahedron
{
    NSLog(@"ViewController => drawIcosahedron");
    // Draw code here
    //@update
    //
    // 1. 建立了一個靜態變數來跟蹤物體的旋轉
    static GLfloat rot = 0.0;
   
    // This is the same result as using Vertex3D, just faster to type and
    // can be made const this way
    //
    // 2. 定義頂點陣列:
    //
    // 使用了一個與前不同的方法, 但結果是一樣的. 由於我們的幾何體根本不會變化,
    // 所以我們將其定義為 const, 這樣就不需要每一 frame 都分配/清除記憶體:
    static const Vertex3D vertices[]= {
        {0, -0.525731, 0.850651},             // vertices[0]
        {0.850651, 0, 0.525731},              // vertices[1]
        {0.850651, 0, -0.525731},             // vertices[2]
        {-0.850651, 0, -0.525731},            // vertices[3]
        {-0.850651, 0, 0.525731},             // vertices[4]
        {-0.525731, 0.850651, 0},             // vertices[5]
        {0.525731, 0.850651, 0},              // vertices[6]
        {0.525731, -0.850651, 0},             // vertices[7]
        {-0.525731, -0.850651, 0},            // vertices[8]
        {0, -0.525731, -0.850651},            // vertices[9]
        {0, 0.525731, -0.850651},             // vertices[10]
        {0, 0.525731, 0.850651}               // vertices[11]
    };
   
    // 3. 建立一個顏色陣列:
    //
    // 創建一個 Color3D 物件陣列, 每項對應於前一個陣列的頂點:
    static const Color3D colors[] = {
        {1.0, 0.0, 0.0, 1.0},
        {1.0, 0.5, 0.0, 1.0},
        {1.0, 1.0, 0.0, 1.0},
        {0.5, 1.0, 0.0, 1.0},
        {0.0, 1.0, 0.0, 1.0},
        {0.0, 1.0, 0.5, 1.0},
        {0.0, 1.0, 1.0, 1.0},
        {0.0, 0.5, 1.0, 1.0},
        {0.0, 0.0, 1.0, 1.0},
        {0.5, 0.0, 1.0, 1.0},
        {1.0, 0.0, 1.0, 1.0},
        {1.0, 0.0, 0.5, 1.0}
    };
   
    // 4. 建立二十面體:
    //
    // 上述十二個頂點本身並未描述形狀. OpenGL 需要知道怎樣將它們聯繫在一起,
    // 所以我們建立了一個整數陣列 (GLubyte) 指向構成各三角形的頂點.
    //
    // 二十面體的第一個面的三個數是 1,2,6 代表繪製處於索引1 (0.850651, 0, 0.525731),
    // 2 (0.850651, 0, 0.525731), 和 6 (0.525731, 0.850651, 0) 之間的三角形.
    static const GLubyte icosahedronFaces[] = {
        1, 2, 6,
        1, 7, 2,
        3, 4, 5,
        4, 3, 8,
        6, 5, 11,
        5, 6, 10,
        9, 10, 2,
        10, 9, 3,
        7, 8, 9,
        8, 7, 0,
        11, 0, 1,
        0, 11, 4,
        6, 2, 10,
        1, 6, 11,
        3, 5, 10,
        5, 4, 11,
        2, 7, 9,
        7, 1, 0,
        3, 9, 8,
        4, 8, 0,
    };
   
    // 5.
    //
    // 加載單元矩陣
    glLoadIdentity();
   
    // 移動
    glTranslatef(0.0f,0.0f,-3.0f);
   
    // 旋轉
    glRotatef(rot,1.0f,1.0f,1.0f);
   
    // 設置背景色
    glClearColor(0.7, 0.7, 0.7, 1.0);
   
    // 清除緩存
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   
    // 啟動頂點陣列
    glEnableClientState(GL_VERTEX_ARRAY);
   
    // 啟動顏色陣列
    glEnableClientState(GL_COLOR_ARRAY);
   
    // 提供頂點陣列內容給 OpenGL
    glVertexPointer(3, GL_FLOAT, 0, vertices);
   
    // 提供顏色陣列內容給 OpenGL
    glColorPointer(4, GL_FLOAT, 0, colors);
   
   
    // 6. 不使用 glDrawArrays(), 而是使用 glDrawElements():
    //
    // 備註: 如果你按繪製的正確次序提供頂點, 那麼你應該使用 glDrawArrays(),
    //           但是如果你提供一個陣列然後用另一個以索引值區分頂點次序的陣列的話,
    //           那麼你應該使用 glDrawElements().
    glDrawElements(GL_TRIANGLES, 60, GL_UNSIGNED_BYTE, icosahedronFaces);
   
    // 7. 執行禁止功能
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
   
    // 8. 根據上一個 frame 繪製的時間增加旋轉變量值:
    static NSTimeInterval lastDrawTime;
    if (lastDrawTime)
    {
        NSTimeInterval timeSinceLastDraw = [NSDate timeIntervalSinceReferenceDate] - lastDrawTime;

        rot += 50 * timeSinceLastDraw;
    }
    lastDrawTime = [NSDate timeIntervalSinceReferenceDate];
}
....

-----------------------------------------------------------------------------------------

D. 編譯並執行
      漂亮旋轉的二十面體


2012年4月3日 星期二

OpenGL ES 入門: 二. 簡單繪圖之四

since: 2012/04/03
update: 2012/04/03

reference:
1. 原文:
iPhone Development: OpenGL ES From the Ground Up, Part 2: A Look at Simple Drawing

2. 翻譯:
從零開始學習OpenGL ES之二 – 簡單繪圖概述


簡單繪圖之四: 設定頂點顏色

A. 說明
      1. OpenGL ES 允許你將每個頂點使用的顏色置於一個顏色陣列 (color array) 中.

      2. 如果你選擇使用顏色陣列,那麼你需要為每個頂點設定顏色(四個 GLfloat 值).

      3. 可以通過以下的方法來啟動顏色陣列: glEnableClientState(GL_COLOR_ARRAY);

-----------------------------------------------------------------------------------

B. 開啓 OpenGLESCommon.h 檔案, 修改如下:
....
#pragma mark -
#pragma mark Color3D
#pragma mark -

// 顏色定義
typedef struct {
    GLfloat    red;
    GLfloat    green;
    GLfloat    blue;
    GLfloat    alpha;
} Color3D;

// 單個顏色
static inline Color3D Color3DMake(CGFloat inRed, CGFloat inGreen, CGFloat inBlue, CGFloat inAlpha)
{
    Color3D ret;
   
    ret.red = inRed;
    ret.green = inGreen;
    ret.blue = inBlue;
    ret.alpha = inAlpha;
   
    return ret;
}

// 設定現存顏色的值
static inline void Color3DSet(Color3D *color, CGFloat inRed, CGFloat inGreen, CGFloat inBlue, CGFloat inAlpha)
{
    color->red = inRed;
    color->green = inGreen;
    color->blue = inBlue;
    color->alpha = inAlpha;
}
....

-----------------------------------------------------------------------------------

C. 頂點顏色前置作業
      1. 開啓 GLView.h 檔案, 修改如下:
....
//@add for protocol
@protocol GLViewDelegate

@required
- (void)setupView:(GLView *)view;

@optional
//@update for drawing
- (void)drawView:(GLView *)view;
- (void)drawTriangle3D; // 畫三角形
- (void)drawSquare; // 畫正方形
- (void)drawVertexColor; // 畫頂點顏色

@end
....

      2. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫頂點顏色
- (void)drawVertexColor
{
    NSLog(@"ViewController => drawVertexColor");
    // Draw code here
}
....

      3. 開啓 GLView.m 檔案, 修改如下:
....
- (void)drawView
{
....
    //@update for drawing
    //[self.delegate drawTriangle3D]; // 畫三角形
    //[self.delegate drawSquare]; // 畫正方形
    [self.delegate drawVertexColor]; // 畫頂點顏色
....
}
....

-----------------------------------------------------------------------------------

D. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫頂點顏色
- (void)drawVertexColor
{
    NSLog(@"ViewController => drawVertexColor");
    // Draw code here
    Vertex3D    vertex1 = Vertex3DMake(0.0, 1.0, -3.0);
    Vertex3D    vertex2 = Vertex3DMake(1.0, 0.0, -3.0);
    Vertex3D    vertex3 = Vertex3DMake(-1.0, 0.0, -3.0);
    Triangle3D  triangle = Triangle3DMake(vertex1, vertex2, vertex3);
   
    Color3D *colors = malloc(sizeof(Color3D) * 3);
    Color3DSet(&colors[0], 1.0, 0.0, 0.0, 1.0);
    Color3DSet(&colors[1], 0.0, 1.0, 0.0, 1.0);
    Color3DSet(&colors[2], 0.0, 0.0, 1.0, 1.0);
   
    glLoadIdentity();
    glClearColor(0.7, 0.7, 0.7, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glColor4f(1.0, 0.0, 0.0, 1.0);
    glVertexPointer(3, GL_FLOAT, 0, &triangle);
    glColorPointer(4, GL_FLOAT, 0, colors);
    glDrawArrays(GL_TRIANGLES, 0, 9);
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
   
    if (colors != NULL)
        free(colors);
}
....

-----------------------------------------------------------------------------------

E. 編譯並執行

OpenGL ES 入門: 二. 簡單繪圖之三

since: 2012/04/03
update: 2012/04/03

reference:
1. 原文:
iPhone Development: OpenGL ES From the Ground Up, Part 2: A Look at Simple Drawing

2. 翻譯:
從零開始學習OpenGL ES之二 – 簡單繪圖概述


簡單繪圖之三: 畫正方形

A. 架構微調
      1. 說明: 為了讓每次練習的繪圖程式碼能獨自分開, 而不是在同一個方法中
                     (ViewController 的 drawView:), 利用註解來區分, 因此做了些調整:

                     a. 在 GLView.h 裡, 針對不同的繪圖, 而在 <GLViewDelegate> protocol 的
                         宣告中新增不同的繪圖方法.

                     b. 在 ViewController.m 裡, 實作 <GLViewDelegate> protocol 所宣告的
                          不同繪圖方法.

                     c. 最後在 GLView.m 的 drawView 裡, 將原本呼叫
                         [self.delegate drawView:self];
                         改成呼叫: [self.delegate 個別的繪圖方法];

      2. 開啓 GLView.h 檔案, 修改如下:
....
//@add for protocol
@protocol GLViewDelegate

@required
- (void)setupView:(GLView *)view;

@optional
//@update for drawing
- (void)drawView:(GLView *)view;
- (void)drawTriangle3D; // 畫三角形

@end

      3. 開啓 ViewController.m 檔案, 修改如下:
....
- (void)drawView:(GLView *)view
{
/*
....
*/
}

// 畫三角形
- (void)drawTriangle3D
{
    NSLog(@"ViewController => drawTriangle3D");
   
    //@add for Rendering Frequency
    static GLfloat rotation = 0.0;
   
    // 建立三個頂點
    //
    // 三個頂點的 z 值是一樣的,其值(-3.0)是處於原點 "之後" 的
    Vertex3D    vertex1 = Vertex3DMake(0.0, 1.0, -3.0);
    Vertex3D    vertex2 = Vertex3DMake(1.0, 0.0, -3.0);
    Vertex3D    vertex3 = Vertex3DMake(-1.0, 0.0, -3.0);
   
    // 建立三角形
    Triangle3D  triangle = Triangle3DMake(vertex1, vertex2, vertex3);
   
    // 將 OpenGL 中的矩陣設為單位矩陣.
    // 所謂的單位矩陣是矩陣乘法下的單位元素,
    // 任何矩陣乘上單位矩陣都還是等於自己
    //
    // 所以 glLoadIdentity() 的作用是不希望之前的矩陣資料,
    // 殘留到現在的運算.
    glLoadIdentity();
   
    //@add for Rendering Frequency
    glRotatef(rotation, 0.0, 0.0, 1.0);
   
    // 告訴 OpenGL 所有的繪製工作是在一個灰色背景上進行.
    //
    // 設定: R, G, B, alpha(1.0, 代表完全不透明)
    // 白色: (1.0, 1.0, 1.0, 1.0)
    // 黑色: (0.0, 0.0, 0.0, 1.0)
    glClearColor(0.7, 0.7, 0.7, 1.0);
   
    // 通知 OpenGL 清除以前的一切圖形並將其設為 clear 顏色.
    //
    // color buffer - 顏色緩存, 保存當前 frame 各像素的顏色, 基本上就是你在屏幕上
    //                          看到的.

    //
    // depth buffer - 深度緩存(z-buffer), 保存每個潛在像素離觀察者距離的信息,
    //                          使用此信息可以確定一個像素是否需要被繪製出來
    //
    // 記住: 在繪製一個 frame 之前, 必須清除這兩個緩存以保證不會和以前的內容混雜.
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   
    // 啟動 OpenGL 的 vertex arrays(頂點陣列)的特性.
    // 作為基本準則, 我們可以先啟動最後再關閉我們使用的功能
    //
    glEnableClientState(GL_VERTEX_ARRAY);
   
    // 設置繪圖時所需的顏色
    // 此行代碼將繪圖顏色設為鮮艷的紅色
    //
    // 現在, 直到下次調用 glColor4f() 前所有的圖形都是以紅色繪製
    // 有一些例外的情況, 例如繪製紋理形狀時, 但基本上, 這樣設定顏色可以使顏色保持.
    glColor4f(1.0, 0.0, 0.0, 1.0);
   
    // 由於我們使用頂點陣列, 我們必須通知 OpenGL 頂點的陣列在什麼地方.
    //
    // 頂點陣列只是一個 GLfloat 的 C 陣列, 每三個值代表一個頂點.
    // 我們創建了 Triangle3D 物體, 但在內存中, 它完全等同於 9 個連續的 GLfloat,
    // 所以我們可以傳遞此三角形物體的位址.
    //
    // glVertexPointer()
    // 第一個參數, 指示了多少個 GLfloat 代表一個頂點
    // 第二個參數, 告訴 OpenGL 頂點是由 GLfloat 構成
    glVertexPointer(3, GL_FLOAT, 0, &triangle);
   
    // 通知 OpenGL 通過剛才提交的頂點陣列來繪製三角形
    //
    // 第一個參數, 告訴 OpenGL 繪製什麼.
    // 儘管 OpenGL ES 不支持繪製三角形之外的四邊形或其他多邊形, 但它仍然支持
    // 一些其他繪圖模式,
如繪製點, 線, 線迴路, 三角形條和三角形扇.
    glDrawArrays(GL_TRIANGLES, 0, 9);
   
    // 最後, 我們要禁止先前啟動了的特性以保證不會被其他地方的代碼弄混
    glDisableClientState(GL_VERTEX_ARRAY);
   
    //@add for Rendering Frequency
    rotation += 0.5;
}
....

      4. 開啓 GLView.m 檔案, 修改如下:
....
- (void)drawView
{
    NSLog(@"step 06. GLView => drawView");
       
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFrameBuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderBuffer);
   
    // GO: step 07. ViewController => drawView:
    //[self.delegate drawView:self];
    //@update for drawing
    [self.delegate drawTriangle3D]; // 畫三角形
   
    [self.glContext presentRenderbuffer:GL_RENDERBUFFER_OES];
   
    //@add for Rendering Frequency
    int intCount = [self.currentRunCount intValue] + 1;
    self.currentRunCount = [NSNumber numberWithInt:intCount];
   
    if (intCount >= self.totalRunTime * kRenderingFrequency) {

        [self stopAnimation];
    }
}
....

----------------------------------------------------------------------------------

B. 畫正方形之前置作業
       1. 開啓 GLView.h 檔案, 修改如下:
....
//@add for protocol
@protocol GLViewDelegate

@required
- (void)setupView:(GLView *)view;

@optional
//@update for drawing
- (void)drawView:(GLView *)view;
- (void)drawTriangle3D; // 畫三角形
- (void)drawSquare; // 畫正方形

@end

       2. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫正方形
- (void)drawSquare
{
    NSLog(@"ViewController => drawSquare");
    // Draw code here
}
....

       3. 開啓 GLView.m 檔案, 修改如下:
....
- (void)drawView
{
....
    //@update for drawing
    //[self.delegate drawTriangle3D]; // 畫三角形
    [self.delegate drawSquare]; // 畫正方形
....
}
...
----------------------------------------------------------------------------------

C. 畫正方形
之方法一
     1. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫正方形
- (void)drawSquare
{
    NSLog(@"ViewController => drawSquare");
    // Draw code here
    //
    // 定義一個包含兩個 Triangle3D 物體的陣列
    Triangle3D  triangle[2];
   
    triangle[0].v1 = Vertex3DMake(0.0, 1.0, -3.0);
    triangle[0].v2 = Vertex3DMake(1.0, 0.0, -3.0);
    triangle[0].v3 = Vertex3DMake(-1.0, 0.0, -3.0);
    triangle[1].v1 = Vertex3DMake(-1.0, 0.0, -3.0);
    triangle[1].v2 = Vertex3DMake(1.0, 0.0, -3.0);
    triangle[1].v3 = Vertex3DMake(0.0, -1.0, -3.0);
   
    glLoadIdentity();
    glClearColor(0.7, 0.7, 0.7, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColor4f(1.0, 0.0, 0.0, 1.0);
    glVertexPointer(3, GL_FLOAT, 0, &triangle);
    glDrawArrays(GL_TRIANGLES, 0, 18);
    glDisableClientState(GL_VERTEX_ARRAY);
}
....

     2. 編譯並執行

     3. 說明
         由於 Vertex3DMake() 方法在堆疊中創建新的 Vertex3D,  然後複製其值到
         陣列中而造成額外的記憶體被佔用,因此上述代碼並不理想。

----------------------------------------------------------------------------------

D. 畫正方形
之方法二
      1. 開啓 OpenGLESCommon.h 檔案, 修改如下:
....
#pragma mark -
#pragma mark Vertex3D
#pragma mark -
....
// 設定現存頂點的值
static inline void Vertex3DSet(Vertex3D *vertex, CGFloat inX, CGFloat inY, CGFloat inZ)
{
    vertex->x = inX;
    vertex->y = inY;
    vertex->z = inZ;
}
....

      2. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫正方形
- (void)drawSquare
{
    NSLog(@"ViewController => drawSquare");
    // Draw code here
    //
    /*
    // 定義一個包含兩個 Triangle3D 物體的陣列
    Triangle3D  triangle[2];
   
    triangle[0].v1 = Vertex3DMake(0.0, 1.0, -3.0);
    triangle[0].v2 = Vertex3DMake(1.0, 0.0, -3.0);
    triangle[0].v3 = Vertex3DMake(-1.0, 0.0, -3.0);
    triangle[1].v1 = Vertex3DMake(-1.0, 0.0, -3.0);
    triangle[1].v2 = Vertex3DMake(1.0, 0.0, -3.0);
    triangle[1].v3 = Vertex3DMake(0.0, -1.0, -3.0);
    */
   
    //@update
    Triangle3D  *triangles = malloc(sizeof(Triangle3D) * 2);
   
    Vertex3DSet(&triangles[0].v1, 0.0, 1.0, -3.0);
    Vertex3DSet(&triangles[0].v2, 1.0, 0.0, -3.0);
    Vertex3DSet(&triangles[0].v3, -1.0, 0.0, -3.0);
    Vertex3DSet(&triangles[1].v1, -1.0, 0.0, -3.0);
    Vertex3DSet(&triangles[1].v2, 1.0, 0.0, -3.0);
    Vertex3DSet(&triangles[1].v3, 0.0, -1.0, -3.0);
   
    glLoadIdentity();
    glClearColor(0.7, 0.7, 0.7, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColor4f(1.0, 0.0, 0.0, 1.0);
    //glVertexPointer(3, GL_FLOAT, 0, &triangle);
    //@update
    glVertexPointer(3, GL_FLOAT, 0, triangles);
    glDrawArrays(GL_TRIANGLES, 0, 18);
    glDisableClientState(GL_VERTEX_ARRAY);
   
    if (triangles != NULL)
        free(triangles);
}
....

----------------------------------------------------------------------------------

E. 畫正方形
之方法三
      1. 說明: 使用 triangle strips (GL_TRIANGLE_STRIP)方法通過四個頂點
                     (12個 GLfloat)來繪製正方形
.

      2. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫正方形
- (void)drawSquare
{
    NSLog(@"ViewController => drawSquare");
    // Draw code here
    //
    /*
    Triangle3D  *triangles = malloc(sizeof(Triangle3D) * 2);
   
    Vertex3DSet(&triangles[0].v1, 0.0, 1.0, -3.0);
    Vertex3DSet(&triangles[0].v2, 1.0, 0.0, -3.0);
    Vertex3DSet(&triangles[0].v3, -1.0, 0.0, -3.0);
    Vertex3DSet(&triangles[1].v1, -1.0, 0.0, -3.0);
    Vertex3DSet(&triangles[1].v2, 1.0, 0.0, -3.0);
    Vertex3DSet(&triangles[1].v3, 0.0, -1.0, -3.0);
    */
   
    //@update
    Vertex3D  *vertices = malloc(sizeof(Vertex3D) * 4);
   
    Vertex3DSet(&vertices[0], 0.0, 1.0, -3.0);
    Vertex3DSet(&vertices[1], 1.0, 0.0, -3.0);
    Vertex3DSet(&vertices[2], -1.0, 0.0, -3.0);
    Vertex3DSet(&vertices[3], 0.0, -1.0, -3.0);
   
    glLoadIdentity();
    glClearColor(0.7, 0.7, 0.7, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColor4f(1.0, 0.0, 0.0, 1.0);
    //glVertexPointer(3, GL_FLOAT, 0, triangles);
    //@update
    glVertexPointer(3, GL_FLOAT, 0, vertices);
   
    //glDrawArrays(GL_TRIANGLES, 0, 18);
    //@update
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 12);
   
    glDisableClientState(GL_VERTEX_ARRAY);
   
    //if (triangles != NULL)
    //    free(triangles);
    //@update
    if (vertices != NULL)
        free(vertices);
}
....

      3. 開啓 GLView.m 檔案, 修改如下:
....
//@add
- (void)drawView
{
    NSLog(@"step 06. GLView => drawView");
       
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFrameBuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderBuffer);
   
    // GO: step 07. ViewController => drawView:
    //[self.delegate drawView:self];
    //@update for drawing
    //[self.delegate drawTriangle3D]; // 畫三角形
    [self.delegate drawSquare]; // 畫正方形
   
    [self.glContext presentRenderbuffer:GL_RENDERBUFFER_OES];
   
    //@add for Rendering Frequency
    /*
    int intCount = [self.currentRunCount intValue] + 1;
    self.currentRunCount = [NSNumber numberWithInt:intCount];
   
    if (intCount >= self.totalRunTime * kRenderingFrequency) {

        [self stopAnimation];
    }
    */
    //@update for run once
    [self stopAnimation];
}
....