Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android OpenGL ES:3D 空間建模與 glDrawArrays 繪製

編輯:關於 Android 程式設計

要在 OpenGL ES 中打造 3D 場景,就得先學會用三角形拼出各種立體物件,再透過頂點數組把它們畫出來。本文以四稜錐與四方體為例,說明 3D 空間的建模與繪製流程。

一、用三角形組成立體物件

OpenGL ES 中的立體物件,歸根究柢都是由三角形拼組而成:四稜錐由 4 個三角形構成,四方體則由 6 個三角形構成。

這裡有個關鍵難點:若希望物件能繞「自身的中心軸」旋轉,就必須讓物件的中心座標永遠落在原點 (0.0f, 0.0f, 0.0f);此外,所有三角形的頂點都要按照逆時針順序繪製,這樣正面朝向才會正確。

二、glDrawArrays 繪製方式

3D 空間的繪製依靠 glDrawArrays 函數:

void glDrawArrays(GLenum mode, GLint first, GLsizei count);

參數說明:
mode:繪製方式,OpenGL 2.0 以後提供 GL_POINTS、GL_LINES、GL_LINE_LOOP、GL_LINE_STRIP、GL_TRIANGLES、GL_TRIANGLE_STRIP、GL_TRIANGLE_FAN 等選項。
first:從頂點緩存中的第幾個位置開始繪製,一般為 0。
count:本次要繪製的頂點數量。

三、繪製頂點數組

以四稜錐與四方體為例,分別用迴圈分批繪製各個面:

// 繪製四稜錐(4 個三角形,每面 3 個頂點)
for (int i = 0; i < 4; i++) {
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, i * 3, 3);
}

// 繪製四方體(6 個面,每面 4 個頂點)
for (int i = 0; i < 6; i++) {
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, i * 4, 4);
}

附:構建頂點數組

以下示範如何用 IntBuffer 包裝四稜錐與四方體的頂點座標(這裡用 0x10000 代表 1.0 的定點表示法):

int one = 0x10000;

// 四稜錐頂點數組(4 個三角形,共 12 個頂點)
private IntBuffer triggerBuffer = IntBuffer.wrap(new int[]{
    0,   one,  0,
    -one, -one, 0,
    one,  -one, one,

    0,   one,  0,
    one,  -one, one,
    one,  -one, -one,

    0,   one,  0,
    one,  -one, -one,
    -one, -one, -one,

    0,   one,  0,
    -one, -one, -one,
    -one, -one, one
});

// 四方體頂點數組(6 個面,共 24 個頂點)
private IntBuffer quaterBuffer = IntBuffer.wrap(new int[]{
    one,   one, -one,
    -one,  one, -one,
    one,   one,  one,
    -one,  one,  one,

    one,  -one,  one,
    -one, -one,  one,
    one,  -one, -one,
    -one, -one, -one,

    one,   one, one,
    -one,  one, one,
    one,  -one, one,
    -one, -one, one,

    one,  -one, -one,
    -one, -one, -one,
    one,   one, -one,
    -one,  one, -one,

    -one,  one, one,
    -one,  one, -one,
    -one, -one, one,
    -one, -one, -one,

    one,   one, -one,
    one,   one,  one,
    one,  -one, -one,
    one,  -one,  one
});

把這些頂點數據準備好,再搭配 glDrawArrays 分批繪製,你就能在螢幕上畫出會旋轉的 3D 幾何體了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved