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

OpenGL ES 2.0 for Android 實戰:從三角形到彩色立方體

編輯:關於 Android 程式設計

前面幾篇都在處理 OpenGL ES 2.0 的二維繪製,現在該邁進三維世界了。三維远比二維有趣,但複雜度也高出不少——在 Unity3D 裡拖一下就有一個立方體,而在 OpenGL ES 2.0 中你得自己把每一步搭起來。這恰好是它的樂趣所在。

先看整體流程:

一、攝像機的設置

想想你手機的鏡頭:位置不同、朝向不同,同一個物體拍出來的画面就完全不同。OpenGL 中的攝像機也是同樣的道理。

(圖一)

在 OpenGL 中,攝像機由三部分資訊描述:

1. 攝像機位置——在三維空間中以 x、y、z 表示;
2. 鏡頭指向——即觀察目標的座標,一般取物體的中心點。由「攝像機位置」與「目標座標」可確定一個向量,它決定了觀察方向;
3. UP 方向——攝像機頂端所指的方向。

下面這張人眼觀察示意圖更好理解:

(圖二)

位置、朝向、UP 方向有許多不同組合,對同一物體觀察會得到不同結果。國外有位先驅做過一個互動 Demo,可以直接調 gluLookAt 的 eye(攝像機位置)與 center(鏡頭指向)參數,實時觀察右上方位形的變化,非常適合建立直覺:

Demo 下載:download.csdn.net/detail/cassiepython/9541794

二、透視投影

我們觀察物體時有「近大遠小」的效果,透視投影就是為了模擬這一點,概念與美術中的透視透出一脈相承。

(圖三)

其中,視點指攝像機位置,近平面是距離視點較近、垂直於觀察方向的平面,視景體(又稱視錐體)則是錐台形區域。

(圖四)

透視投影的投影線互不平行,因此同樣尺寸的物體在近處投影較大、遠處較小,這正是近大遠小的成因。建議搭配上面的 Demo 反覆調參,效果會更清楚。

三、定義立方體的頂點座標

開始寫程式。此時座標系裡除了 X、Y,還要加入 Z 軸。Z 的範圍與 X、Y 一致,同樣是 -1 到 1。把手機螢幕想成一個平面,看向它,想像視線穿過兩個平行平面——前方為 1,後方為 -1。

接續上一節的專案,在 shape 包下建立 Cube.java:

package com.cumt.shape;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import android.content.Context;

public class Cube {

    private FloatBuffer vertexBuffer;
    private Context context;

    private static final int BYTES_PER_FLOAT = 4;

    static float vertices[] = {
        // 前面
        0,0,1.0f,  1.0f,1.0f,1.0f,  -1.0f,1.0f,1.0f,
        0,0,1.0f, -1.0f,1.0f,1.0f,  -1.0f,-1.0f,1.0f,
        0,0,1.0f, -1.0f,-1.0f,1.0f,  1.0f,-1.0f,1.0f,
        0,0,1.0f,  1.0f,-1.0f,1.0f,  1.0f,1.0f,1.0f,
        // 後面
        0,0,-1.0f, 1.0f,1.0f,-1.0f,  1.0f,-1.0f,-1.0f,
        0,0,-1.0f, 1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f,
        0,0,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f,1.0f,-1.0f,
        0,0,-1.0f, -1.0f,1.0f,-1.0f,  1.0f,1.0f,-1.0f,
        // 左面
        -1.0f,0,0, -1.0f,1.0f,1.0f,  -1.0f,1.0f,-1.0f,
        -1.0f,0,0, -1.0f,1.0f,-1.0f, -1.0f,-1.0f,-1.0f,
        -1.0f,0,0, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f,1.0f,
        -1.0f,0,0, -1.0f,-1.0f,1.0f,  -1.0f,1.0f,1.0f,
        // 右面
        1.0f,0,0,  1.0f,1.0f,1.0f,   1.0f,-1.0f,1.0f,
        1.0f,0,0,  1.0f,-1.0f,1.0f,  1.0f,-1.0f,-1.0f,
        1.0f,0,0,  1.0f,-1.0f,-1.0f, 1.0f,1.0f,-1.0f,
        1.0f,0,0,  1.0f,1.0f,-1.0f,  1.0f,1.0f,1.0f,
        // 上面
        0,1.0f,0,  1.0f,1.0f,1.0f,   1.0f,1.0f,-1.0f,
        0,1.0f,0,  1.0f,1.0f,-1.0f,  -1.0f,1.0f,-1.0f,
        0,1.0f,0,  -1.0f,1.0f,-1.0f, -1.0f,1.0f,1.0f,
        0,1.0f,0,  -1.0f,1.0f,1.0f,  1.0f,1.0f,1.0f,
        // 下面
        0,-1.0f,0, 1.0f,-1.0f,1.0f,  -1.0f,-1.0f,1.0f,
        0,-1.0f,0, -1.0f,-1.0f,1.0f, -1.0f,-1.0f,-1.0f,
        0,-1.0f,0, -1.0f,-1.0f,-1.0f, 1.0f,-1.0f,-1.0f,
        0,-1.0f,0, 1.0f,-1.0f,-1.0f,  1.0f,-1.0f,1.0f
    };

    public Cube(Context context) {
        this.context = context;
        vertexBuffer = ByteBuffer.allocateDirect(vertices.length * BYTES_PER_FLOAT)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.position(0);
    }
}

每個面定義了 12 個頂點:

每個面切為 4 個三角形,每個三角形 3 個點,共 12 個點——因為我們打算用 GL_TRIANGLES 方式繪製。

頂點著色器沿用上一節的 vertex_shader.glsl:

uniform mat4 u_Matrix;
attribute vec4 a_Position;

void main() {
    gl_Position = u_Matrix * a_Position;
}

u_Matrix 用於傳入最終的變換矩陣(投影矩陣與攝像機矩陣的乘積)。接著編譯鏈接著色器,Cube 類擴充為:

public Cube(Context context) {
    this.context = context;
    vertexBuffer = ByteBuffer.allocateDirect(vertices.length * BYTES_PER_FLOAT)
            .order(ByteOrder.nativeOrder())
            .asFloatBuffer();
    vertexBuffer.put(vertices);
    vertexBuffer.position(0);

    getProgram();
    uColorLocation   = GLES20.glGetUniformLocation(program, U_COLOR);
    aPositionLocation = GLES20.glGetAttribLocation(program, A_POSITION);
    uMatrixLocation  = GLES20.glGetUniformLocation(program, U_MATRIX);

    // 傳入頂點數據
    GLES20.glVertexAttribPointer(aPositionLocation, COORDS_PER_VERTEX,
            GLES20.GL_FLOAT, false, 0, vertexBuffer);
    GLES20.glEnableVertexAttribArray(aPositionLocation);
}

private void getProgram() {
    String vertexShaderSource = TextResourceReader
            .readTextFileFromResource(context, R.raw.vertex_shader);
    String fragmentShaderSource = TextResourceReader
            .readTextFileFromResource(context, R.raw.simple_fragment_shader);
    program = ShaderHelper.buildProgram(vertexShaderSource, fragmentShaderSource);
    GLES20.glUseProgram(program);
}

四、設置攝像機與投影矩陣

接下來定義一個工具類來計算最終的變換矩陣,需要用到兩個系統函數:

它們的參數含義與前面講解攝像機、投影時完全對應。在 utils 包中建立 MatrixState:

package com.cumt.utils;

import android.opengl.Matrix;

/** 存儲系統矩陣狀態的類 */
public class MatrixState {

    private static float[] mProjMatrix = new float[16];  // 4x4 投影矩陣
    private static float[] mVMatrix    = new float[16];  // 攝像機位置朝向矩陣

    /** 設置攝像機 */
    public static void setCamera(
            float cx, float cy, float cz,   // 攝像機位置
            float tx, float ty, float tz,   // 攝像機目標點
            float upx, float upy, float upz // 攝像機 UP 向量) {
        Matrix.setLookAtM(mVMatrix, 0, cx, cy, cz, tx, ty, tz, upx, upy, upz);
    }

    /** 設置透視投影參數 */
    public static void setProjectFrustum(
            float left,   // near 面的 left
            float right,  // near 面的 right
            float bottom, // near 面的 bottom
            float top,    // near 面的 top
            float near,   // near 面距離
            float far) {  // far 面距離
        Matrix.frustumM(mProjMatrix, 0, left, right, bottom, top, near, far);
    }

    /** 獲取最終的總變換矩陣 */
    static float[] mMVPMatrix = new float[16];

    public static float[] getFinalMatrix() {
        Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);
        return mMVPMatrix;
    }
}

三個方法各有分工:在渲染類的 onSurfaceChanged 中呼叫前兩個設置攝像機與投影;在 Cube 的 draw() 中呼叫 getFinalMatrix() 取得最終矩陣並傳給著色器。multiplyMM 負責把投影矩陣與攝像機矩陣相乘,結果即為傳入著色器程式所需的 MVP 矩陣。

Cube 的繪製方法:

public void draw() {
    GLES20.glUniform4f(uColorLocation, 1.0f, 0.0f, 0.0f, 0.0f);
    GLES20.glUniformMatrix4fv(uMatrixLocation, 1, false,
            MatrixState.getFinalMatrix(), 0);
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, POSITION_COMPONENT_COUNT);
}

五、渲染類與 Activity

public class MyRender implements Renderer {

    private Context context;
    private Cube cube;

    public MyRender(Context context) {
        this.context = context;
    }

    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        // 打開深度檢測
        GLES20.glEnable(GLES20.GL_DEPTH_TEST);
        // 打開背面剪裁
        GLES20.glEnable(GLES20.GL_CULL_FACE);
        cube = new Cube(context);
    }

    public void onSurfaceChanged(GL10 gl, int width, int height) {
        glViewport(0, 0, width, height);
        float ratio = (float) width / height;
        // 透視投影矩陣
        MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 20, 100);
        // 攝像機位置矩陣
        MatrixState.setCamera(-16f, 8f, 45, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
    }

    public void onDrawFrame(GL10 gl) {
        // 同時清除深度緩衝與顏色緩衝
        glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
        cube.draw();
    }
}
public class MainActivity extends Activity {

    private GLSurfaceView glSurfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                             WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        glSurfaceView = new GLSurfaceView(this);
        glSurfaceView.setEGLContextClientVersion(2);   // 使用 OpenGL ES 2.0
        glSurfaceView.setRenderer(new MyRender(this));
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
        setContentView(glSurfaceView);
    }

    @Override
    protected void onPause() {
        super.onPause();
        glSurfaceView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        glSurfaceView.onResume();
    }
}

執行結果:

一個純紅的立方體誕生了。(有興趣的話,也可以改用線段繪製方式做出一個「空心」立方體。)但這個樣子完全看不出稜邊,接下來替它美化一下——本節先不引入貼圖,改成給每個面不同顏色。

六、為每個面配置顏色

整體思路:

在 Cube 類中新增顏色數據,同樣轉為 FloatBuffer:

// 頂點顏色值陣列,每個頂點 4 個色彩分量 RGBA
static float colors[] = new float[]{
    // 前面:中心白 → 紅
    1,1,1,0,  1,0,0,0,  1,0,0,0,
    1,1,1,0,  1,0,0,0,  1,0,0,0,
    1,1,1,0,  1,0,0,0,  1,0,0,0,
    1,1,1,0,  1,0,0,0,  1,0,0,0,
    // 後面:中心白 → 藍
    1,1,1,0,  0,0,1,0,  0,0,1,0,
    1,1,1,0,  0,0,1,0,  0,0,1,0,
    1,1,1,0,  0,0,1,0,  0,0,1,0,
    1,1,1,0,  0,0,1,0,  0,0,1,0,
    // 左面:中心白 → 洋紅
    1,1,1,0,  1,0,1,0,  1,0,1,0,
    1,1,1,0,  1,0,1,0,  1,0,1,0,
    1,1,1,0,  1,0,1,0,  1,0,1,0,
    1,1,1,0,  1,0,1,0,  1,0,1,0,
    // 右面:中心白 → 黃
    1,1,1,0,  1,1,0,0,  1,1,0,0,
    1,1,1,0,  1,1,0,0,  1,1,0,0,
    1,1,1,0,  1,1,0,0,  1,1,0,0,
    1,1,1,0,  1,1,0,0,  1,1,0,0,
    // 上面:中心白 → 綠
    1,1,1,0,  0,1,0,0,  0,1,0,0,
    1,1,1,0,  0,1,0,0,  0,1,0,0,
    1,1,1,0,  0,1,0,0,  0,1,0,0,
    1,1,1,0,  0,1,0,0,  0,1,0,0,
    // 下面:中心白 → 青
    1,1,1,0,  0,1,1,0,  0,1,1,0,
    1,1,1,0,  0,1,1,0,  0,1,1,0,
    1,1,1,0,  0,1,1,0,  0,1,1,0,
    1,1,1,0,  0,1,1,0,  0,1,1,0,
};

建立新的著色器。頂點著色器 vertex_shader_cube.glsl:

uniform mat4 u_Matrix;
attribute vec4 a_Position;
attribute vec4 a_Color;

varying vec4 v_Color;   // 傳遞給片元著色器的變量

void main() {
    gl_Position = u_Matrix * a_Position;
    v_Color = a_Color;
}

片元著色器 fragment_shader_cube.glsl:

precision mediump float;
varying vec4 v_Color;

void main() {
    gl_FragColor = v_Color;
}

最後在 Cube 類中補上顏色相關的程式碼:

private static final int COORDS_PER_COLOR = 4;
private static final String A_COLOR = "a_Color";

private FloatBuffer colorBuffer;   // 顏色緩衝
private int aColorLocation;

public Cube(Context context) {
    this.context = context;

    vertexBuffer = ByteBuffer.allocateDirect(vertices.length * BYTES_PER_FLOAT)
            .order(ByteOrder.nativeOrder()).asFloatBuffer();
    vertexBuffer.put(vertices);
    vertexBuffer.position(0);

    colorBuffer = ByteBuffer.allocateDirect(colors.length * BYTES_PER_FLOAT)
            .order(ByteOrder.nativeOrder()).asFloatBuffer();
    colorBuffer.put(colors);
    colorBuffer.position(0);

    getProgram();
    aColorLocation    = GLES20.glGetAttribLocation(program, A_COLOR);
    aPositionLocation = GLES20.glGetAttribLocation(program, A_POSITION);
    uMatrixLocation   = GLES20.glGetUniformLocation(program, U_MATRIX);

    // 傳入頂點數據
    GLES20.glVertexAttribPointer(aPositionLocation, COORDS_PER_VERTEX,
            GLES20.GL_FLOAT, false, 0, vertexBuffer);
    GLES20.glEnableVertexAttribArray(aPositionLocation);

    // 傳入顏色數據
    GLES20.glVertexAttribPointer(aColorLocation, COORDS_PER_COLOR,
            GLES20.GL_FLOAT, false, 0, colorBuffer);
    GLES20.glEnableVertexAttribArray(aColorLocation);
}

private void getProgram() {
    String vertexShaderSource = TextResourceReader
            .readTextFileFromResource(context, R.raw.vertex_shader_cube);
    String fragmentShaderSource = TextResourceReader
            .readTextFileFromResource(context, R.raw.fragment_shader_cube);
    program = ShaderHelper.buildProgram(vertexShaderSource, fragmentShaderSource);
    GLES20.glUseProgram(program);
}

public void draw() {
    GLES20.glUniformMatrix4fv(uMatrixLocation, 1, false,
            MatrixState.getFinalMatrix(), 0);
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, POSITION_COMPONENT_COUNT);
}

執行看看:

立方體完成了,是不是漂亮多了。

關於平滑著色

上面的效果之所以呈現「中心白、邊角彩色」的漸層,靠的是 OpenGL ES 的平滑著色機制:當同一個三角形三個頂點的顏色不同時,GPU 會在三角形內部做插值,形成連續的色彩過渡。我們讓每個面的四個三角形都共享中心點的白色,因此自然呈現出由中心向外輻射的漸變。

如果想更深入,可以搜尋「opengl es 平滑著色」關鍵字進一步研究,本文不再展開。

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