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

Android OpenGL ES 實戰(二):紋理貼圖的完整流程

編輯:關於 Android 程式設計

要做稍微複雜一點的 OpenGL 應用,紋理是繞不開的技術。說白了,紋理就是把圖片或影片畫面「貼」到 OpenGL 的三維空間裡。

因此紋理也有自己的坐標系,通常稱為 ST 坐標或 UV 坐標。

上圖即紋理坐標空間,需要注意的是它並沒有固定方向的約定。

一、載入圖片並生成紋理

把紋理相關的 OpenGL 呼叫封裝到工具類中:

public class TextureUtils {

    public static int createTexture(InputStream ins) {
        int[] textures = new int[1];
        GLES20.glGenTextures(1, textures, 0);      // 生成一個紋理
        int textureId = textures[0];
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);

        // 紋理取樣與拉伸方式
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);

        // 讓圖片與紋理由關聯,載入 OpenGL 空間
        Bitmap bitmap = BitmapFactory.decodeStream(ins);
        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
        Log.d("OPENGL", "bitmap: " + bitmap);

        bitmap.recycle();   // 已無用處,及時釋放
        return textureId;
    }
}

MIN_FILTER 用 GL_NEAREST 表示縮小時取臨近值,MAG_FILTER 用 GL_LINEAR 表示放大時做線性插值;WRAP_S / WRAP_T 設為 GL_CLAMP_TO_EDGE,則紋理坐標超出 [0,1] 時邊緣像素會向外延伸,避免出現重複鑲嵌。

二、渲染器

public class MyRenderer implements Renderer {

    public static float[] projMatrix = new float[16];    // 投影
    public static float[] viewMatrix = new float[16];    // 相機
    public static float[] mViewPjMatrix;                 // 總變換矩陣
    public static float[] matrixs = new float[16];
    public static int textureId = -1;

    Context context;
    MyDrawModel drawModel;

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

    @Override
    public void onDrawFrame(GL10 arg0) {
        GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
        Log.e("TAG", "textureId: " + textureId);
        drawModel.drawFrame(textureId);
    }

    @Override
    public void onSurfaceChanged(GL10 arg0, int w, int h) {
        GLES20.glViewport(0, 0, w, h);
        float ratio = (float) w / h;
        // 投影矩陣
        Matrix.frustumM(projMatrix, 0, -ratio, ratio, -1, 1, 1, 10);
        // 相機位置
        Matrix.setLookAtM(viewMatrix, 0, 0, 0, 3, 0, 0, 0, 0.0f, 1.0f, 0.0f);
    }

    @Override
    public void onSurfaceCreated(GL10 g, EGLConfig eglConfig) {
        GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        GLES20.glEnable(GLES20.GL_DEPTH_TEST);

        InputStream ins = null;
        drawModel = new MyDrawModel();
        drawModel.init();

        try {
            ins = context.getAssets().open("house.jpg");
            textureId = TextureUtils.createTexture(ins);
            Log.e("TAG", "textureId: " + textureId);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ins.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        GLES20.glDisable(GLES20.GL_CULL_FACE);
    }
}

三個回呼的職責要分清:onSurfaceCreated 做資源初始化(紋理就在這裡生成),onSurfaceChanged 處理視口與投影/相機矩陣,onDrawFrame 才是每幀繪製。紋理 id 之所以放在 static 上,是為了方便繪製模型類直接取用,正式專案中更推薦透過構造參數傳遞。

三、繪製模型

public class MyDrawModel {

    private int programId;
    private int mVPMatrixHandle;  // 總變換矩陣引用
    private int positionHandle;   // 頂點位置
    private int texCoorHandle;    // 頂點紋理坐標
    private FloatBuffer vertexBuffer;
    private FloatBuffer texCoorBuffer;

    public MyDrawModel() { }

    public void init() {
        initData();

        int vertexsharder = GLHelper.compileScript(GLES20.GL_VERTEX_SHADER, GLScript.vertex2);
        int fragmentsharder = GLHelper.compileScript(GLES20.GL_FRAGMENT_SHADER, GLScript.fragment2);
        programId = GLHelper.linkAttach(vertexsharder, fragmentsharder);
        boolean isOK = GLHelper.checkProgram(programId);

        positionHandle = GLES20.glGetAttribLocation(programId, "aPosition");
        texCoorHandle = GLES20.glGetAttribLocation(programId, "aTexCoor");
        mVPMatrixHandle = GLES20.glGetUniformLocation(programId, "uMVPMatrix");

        Log.d("OPENGL", "positionHandle: " + positionHandle
                + ";texCoorHandle: " + texCoorHandle
                + ";mVPMatrixHandle: " + mVPMatrixHandle + ";" + isOK);
    }

    private void initData() {
        // X, Y, Z —— 五個頂點組成一個矩形
        float vertices[] = new float[] {
                0, 0, 0,
                -1.8f, -1f, 0,
                 1.8f, -1f, 0,
                 1.8f,  1f, 0,
                -1.8f,  1f, 0,
                -1.8f, -1f, 0
        };
        ByteBuffer vb = ByteBuffer.allocateDirect(vertices.length * 4);
        vb.order(ByteOrder.nativeOrder());
        vertexBuffer = vb.asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.position(0);

        // 紋理坐標 S, T,與頂點一一對應
        float texCoor[] = new float[] {
                0.5f, 0.5f,
                0f,   1f,
                1f,   1f,
                1f,   0f,
                0f,   0f,
                0f,   1f
        };
        ByteBuffer cb = ByteBuffer.allocateDirect(texCoor.length * 4);
        cb.order(ByteOrder.nativeOrder());
        texCoorBuffer = cb.asFloatBuffer();
        texCoorBuffer.put(texCoor);
        texCoorBuffer.position(0);
    }

    public void drawFrame(int textureId) {
        GLES20.glUseProgram(programId);

        // 初始化模型矩陣
        Matrix.setRotateM(MyRenderer.matrixs, 0, 0, 1, 0, 0);
        Matrix.translateM(MyRenderer.matrixs, 0, 0, 0, 1);

        // 矩陣連乘:投影 × 相機 × 模型
        MyRenderer.mViewPjMatrix = new float[16];
        Matrix.multiplyMM(MyRenderer.mViewPjMatrix, 0,
                MyRenderer.viewMatrix, 0, MyRenderer.matrixs, 0);
        Matrix.multiplyMM(MyRenderer.mViewPjMatrix, 0,
                MyRenderer.projMatrix, 0, MyRenderer.mViewPjMatrix, 0);

        GLES20.glUniformMatrix4fv(mVPMatrixHandle, 1, false, MyRenderer.mViewPjMatrix, 0);

        GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT,
                false, 3 * 4, vertexBuffer);
        GLES20.glVertexAttribPointer(texCoorHandle, 2, GLES20.GL_FLOAT,
                false, 2 * 4, texCoorBuffer);

        GLES20.glEnableVertexAttribArray(positionHandle);
        GLES20.glEnableVertexAttribArray(texCoorHandle);

        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);

        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 6);
    }
}

OpenGL 需要把設備坐標歸一化到 [-1, 1] 空間,因此繞不開矩陣相乘:世界坐標、物體坐標、相機坐標之間的轉換,後續再詳細展開。這裡 GL_TRIANGLE_FAN 配合六個頂點畫出扇形,剛好構成一個矩形。

四、著色器腳本

public class GLScript {

    public static final String vertex1 =
            "attribute vec4 mPosition;\n" +
            "void main() {\n" +
            "    gl_Position = mPosition;\n" +
            "}";

    public static final String fragment1 =
            "precision mediump float;\n" +
            "uniform vec4 mColor;\n" +
            "void main() {\n" +
            "    gl_FragColor = mColor;\n" +
            "}";

    public static final String vertex2 =
            "uniform mat4 uMVPMatrix;\n" +
            "attribute vec3 aPosition;\n" +
            "attribute vec2 aTexCoor;\n" +
            "varying vec2 vTextureCoord;\n" +
            "void main() {\n" +
            "    gl_Position = uMVPMatrix * vec4(aPosition, 1);\n" +
            "    vTextureCoord = aTexCoor;\n" +
            "}";

    public static final String fragment2 =
            "precision mediump float;\n" +
            "varying vec2 vTextureCoord;\n" +
            "uniform sampler2D sTexture;\n" +
            "void main() {\n" +
            "    vec2 coord = vTextureCoord;\n" +
            "    coord.s = coord.s * 0.5;\n" +
            "    gl_FragColor = texture2D(sTexture, coord);\n" +
            "}";
}

第一組著色器只畫純色,第二組才是紋理版本。片元著色器中的

coord.s = coord.s * 0.5;

把 S 軸坐標整體壓縮一半,等於只取紋理圖像的左半部分——這也是為什麼界面上顯示的是原圖的前半段內容。想驗證 UV 坐標的作用,改這一行是最直觀的方式。

五、顯示結果

原圖對照:

其餘工具類(如 GLHelper)與上一篇相同,此處不再重複。

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