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

OpenGL ES 實作:在 Android 上繪製彩色立方體

編輯:關於 Android 程式設計

直接進主題,先看核心代碼,後面再拆解各個部件的職責。

一、Cube:立方體本體

OpenGL ES 只能畫三角形,因此立方體的每個面都被拆成 4 個三角形,並以立方體中心為原點建立三維座標系:z 軸穿過前後兩面中心,x 軸穿過左右兩面中心,y 軸穿過上下兩面中心。

package test.com.opengles5_3;

import android.opengl.GLES20;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

/**
 * 彩色立方體
 */
public class Cube {
    int mProgram;             // 著色器 program id
    int muMVPMatrixHandle;    // 總變換矩陣引用
    int maPositionHandle;     // 頂點位置屬性引用
    int maColorHandle;        // 頂點顏色屬性引用
    String mVertexShader;     // 頂點著色器腳本
    String mFragmentShader;   // 片元著色器腳本
    FloatBuffer mVertexBuffer;// 頂點座標緩衝
    FloatBuffer mColorBuffer; // 頂點顏色緩衝
    int vCount = 0;

    public Cube(MySurfaceView mv) {
        initVertexData();
        initShader(mv);
    }

    // 初始化頂點座標與著色數據
    public void initVertexData() {
        vCount = 12 * 6; // 6 個面,每面 4 個三角形,共 12 * 6 個頂點

        float vertices[] = new float[] {
            // 前面:以面中心為扇心,向四個角各畫一個三角形
            0,0,Constant.UNIT_SIZE,
            Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
            -Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,

            0,0,Constant.UNIT_SIZE,
            -Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
            -Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,

            0,0,Constant.UNIT_SIZE,
            -Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
            Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,

            0,0,Constant.UNIT_SIZE,
            Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
            Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,

            // 後面、左面、右面、上面、下面依同樣規則填寫:
            // 每個面固定 4 組三角形,中心點座標為該面法線方向上的 UNIT_SIZE,
            // 其餘 8 個頂點為該面的四個角,順序需與前面保持一致(逆時針)。
            // ...(此處省略其餘五面的座標數據,結構與上面完全相同)
        };

        // vertices.length * 4:每個 float 佔 4 個位元組
        ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
        vbb.order(ByteOrder.nativeOrder());
        mVertexBuffer = vbb.asFloatBuffer();
        mVertexBuffer.put(vertices);
        mVertexBuffer.position(0);

        // 每個頂點 4 個色彩分量(RGBA),與頂點一一對應
        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,

            // 後面藍、左面紫、右面黃、上面綠、下面青,規則同上:
            // 每個三角形 3 個頂點,中心點白色、其餘兩點為該面主色。
            // ...(此處省略其餘五面的顏色數據)
        };

        ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
        cbb.order(ByteOrder.nativeOrder());
        mColorBuffer = cbb.asFloatBuffer();
        mColorBuffer.put(colors);
        mColorBuffer.position(0);
    }

    // 初始化 shader
    public void initShader(MySurfaceView mv) {
        mVertexShader = ShaderUtil.loadFromAssetsFile("vertex.sh", mv.getResources());
        mFragmentShader = ShaderUtil.loadFromAssetsFile("frag.sh", mv.getResources());
        mProgram = ShaderUtil.createProgram(mVertexShader, mFragmentShader);

        maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
        maColorHandle = GLES20.glGetAttribLocation(mProgram, "aColor");
        muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
    }

    public void drawSelf() {
        GLES20.glUseProgram(mProgram);
        // 傳入最終變換矩陣
        GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
        // 指定頂點位置與顏色數據
        GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, 3 * 4, mVertexBuffer);
        GLES20.glVertexAttribPointer(maColorHandle, 4, GLES20.GL_FLOAT, false, 4 * 4, mColorBuffer);
        GLES20.glEnableVertexAttribArray(maPositionHandle);
        GLES20.glEnableVertexAttribArray(maColorHandle);
        // 以三角形方式繪製
        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
    }
}

二、MainActivity:全屏橫向的渲染入口

package test.com.opengles5_3;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {
    private MySurfaceView mGLSurfaceView;

    @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);

        mGLSurfaceView = new MySurfaceView(this);
        setContentView(mGLSurfaceView);
        mGLSurfaceView.requestFocus();
        mGLSurfaceView.setFocusableInTouchMode(true);
    }

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

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

三、MatrixState:相機與矩陣狀態管理

這個類集中保管投影矩陣、相機視矩陣與當前變換矩陣,並提供矩陣堆棧的入棧/出棧操作。

package test.com.opengles5_3;

import android.opengl.Matrix;
import java.nio.ByteBuffer;

/**
 * 儲存系統矩陣狀態
 */
public class MatrixState {
    private static float[] mProjMatrix = new float[16]; // 投影矩陣
    private static float[] mVMatrix = new float[16];    // 相機位置朝向矩陣
    private static float[] currMatrix;                  // 當前變換矩陣

    // 變換矩陣堆棧
    static float[][] mStack = new float[10][16];
    static int stackTop = -1;

    public static void setInitStack() {
        currMatrix = new float[16];
        Matrix.setRotateM(currMatrix, 0, 0, 1, 0, 0);
    }

    public static void pushMatrix() {
        stackTop++;
        for (int i = 0; i < 16; i++) {
            mStack[stackTop][i] = currMatrix[i];
        }
    }

    public static void popMatrix() {
        for (int i = 0; i < 16; i++) {
            currMatrix[i] = mStack[stackTop][i];
        }
        stackTop--;
    }

    public static void translate(float x, float y, float z) {
        Matrix.translateM(currMatrix, 0, x, y, z);
    }

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

    // 透視投影
    public static void setProjectFrustum(float left, float right,
                                         float bottom, float top,
                                         float near, float far) {
        Matrix.frustumM(mProjMatrix, 0, left, right, bottom, top, near, far);
    }

    // 正交投影
    public static void setProjectOrtho(float left, float right,
                                       float bottom, float top,
                                       float near, float far) {
        Matrix.orthoM(mProjMatrix, 0, left, right, bottom, top, near, far);
    }

    // 物體的總變換矩陣 = 投影 × 視 × 模型
    static float[] mMVPMatrix = new float[16];

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

    public static float[] getMMatrix() {
        return currMatrix;
    }
}

四、MySurfaceView:渲染器與場景

package test.com.opengles5_3;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MySurfaceView extends GLSurfaceView {

    private SceneRenderer mRenderer;

    public MySurfaceView(Context context) {
        super(context);
        setEGLContextClientVersion(2); // 使用 OpenGL ES 2.0
        mRenderer = new SceneRenderer();
        setRenderer(mRenderer);
        setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); // 主動渲染
    }

    private class SceneRenderer implements GLSurfaceView.Renderer {

        Cube cube;

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
            cube = new Cube(MySurfaceView.this);
            GLES20.glEnable(GLES20.GL_DEPTH_TEST); // 深度檢測
            GLES20.glEnable(GLES20.GL_CULL_FACE);  // 背面剔除
        }

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            GLES20.glViewport(0, 0, width, height);
            Constant.ratio = (float) width / height;
            MatrixState.setProjectFrustum(-Constant.ratio * 0.8f, Constant.ratio * 1.2f,
                    -1, 1, 20, 100);
            MatrixState.setCamera(-16f, 8f, 45, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
            MatrixState.setInitStack();
        }

        @Override
        public void onDrawFrame(GL10 gl) {
            GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);

            // 原位置的立方體
            MatrixState.pushMatrix();
            cube.drawSelf();
            MatrixState.popMatrix();

            // 平移後的立方體
            MatrixState.pushMatrix();
            MatrixState.translate(3, 1, -1);
            cube.drawSelf();
            MatrixState.popMatrix();
        }
    }
}

五、ShaderUtil:著色器編譯與加載工具

這個工具類負責從 assets 讀取 .sh 腳本、編譯著色器、鏈接 program,並在每一步做錯誤檢查。

package test.com.opengles5_3;

import android.content.res.Resources;
import android.opengl.GLES20;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

// 加載頂點 Shader 與片元 Shader 的工具類
public class ShaderUtil {

    // 編譯單個 shader
    public static int loadShader(int shaderType, String source) {
        int shader = GLES20.glCreateShader(shaderType);
        if (shader != 0) {
            GLES20.glShaderSource(shader, source);
            GLES20.glCompileShader(shader);
            int[] compiled = new int[1];
            GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
            if (compiled[0] == 0) {
                Log.e("ES20_ERROR", "Could not compile shader " + shaderType + ":");
                Log.e("ES20_ERROR", GLES20.glGetShaderInfoLog(shader));
                GLES20.glDeleteShader(shader);
                shader = 0;
            }
        }
        return shader;
    }

    // 建立並鏈接 program
    public static int createProgram(String vertexSource, String fragmentSource) {
        int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
        if (vertexShader == 0) {
            return 0;
        }
        int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
        if (pixelShader == 0) {
            return 0;
        }

        int program = GLES20.glCreateProgram();
        if (program != 0) {
            GLES20.glAttachShader(program, vertexShader);
            checkGlError("glAttachShader");
            GLES20.glAttachShader(program, pixelShader);
            checkGlError("glAttachShader");
            GLES20.glLinkProgram(program);

            int[] linkStatus = new int[1];
            GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
            if (linkStatus[0] != GLES20.GL_TRUE) {
                Log.e("ES20_ERROR", "Could not link program: ");
                Log.e("ES20_ERROR", GLES20.glGetProgramInfoLog(program));
                GLES20.glDeleteProgram(program);
                program = 0;
            }
        }
        return program;
    }

    // 逐步檢查 GL 錯誤
    public static void checkGlError(String op) {
        int error;
        while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
            Log.e("ES20_ERROR", op + ": glError " + error);
            throw new RuntimeException(op + ": glError " + error);
        }
    }

    // 從 assets 讀取 shader 腳本
    public static String loadFromAssetsFile(String fname, Resources r) {
        String result = null;
        try {
            InputStream in = r.getAssets().open(fname);
            int ch = 0;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((ch = in.read()) != -1) {
                baos.write(ch);
            }
            byte[] buff = baos.toByteArray();
            baos.close();
            in.close();
            result = new String(buff, "UTF-8");
            result = result.replaceAll("\r\n", "\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

運行效果:

幾個容易忽略的細節:頂點座標與顏色數據必須透過 ByteBuffer 以 nativeOrder 包裝後才能交給 OpenGL ES;每個面的三角形繞序要一致,否則啟用背面剔除後會出現缺面;深度檢測與背面剔除都在 onSurfaceCreated 中開啟,順序不影響結果但必須在繪製前完成。

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