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

OpenGL ES 2.0 在 Android 上的紋理貼圖實戰全解析

編輯:關於 Android 程式設計

開篇聊一聊紋理貼圖

紋理映射(Texture Mapping)也常被稱為紋理貼圖,本質上是一個把「紋理空間」裡的像素,對應映射到「螢幕空間」像素的過程。說得直白一點,就是把一張圖片像貼紙一樣附著到三維物體的表面,讓模型告別單調的純色,變得更立體、更逼真。如果再配合光照計算、顏色混合等技術,還能碰撞出令人驚豔的視覺效果。

你可以把紋理理解成一張圖形或一張照片,把它載入 OpenGL 之後,就能用來妝點我們手繪的幾何形體。本文就帶你從零開始,在 Android 上用 OpenGL ES 2.0 完成一次完整的紋理貼圖。

動手前的準備工作

這次我們要挑戰的目標很明確:把一張圖片完整地貼到一個正方形上。做法是在此前「繪製矩形」那一節的程式碼基礎上繼續擴展。

先新建一個名為 OpenglESRectangle 的專案,把之前畫矩形的相關程式碼複製過來。還記得我們曾經遇到「正圓被拉成橢圓」的困擾嗎?在這裡我們同樣為矩形引入正交投影,這樣才能畫出一個真正方方正正的正方形。此時專案的目錄結構如下:

由於加入了正交投影,相比最初繪製矩形的版本,有三個檔案發生了改動,分別是 MyRender.java、Square.java 以及 simple_vertex_shader.glsl。它們目前的程式碼如下:

 package com.cumt.shape; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import com.cumt.openglesrectangle.R; import com.cumt.utils.ShaderHelper; import com.cumt.utils.TextResourceReader; import android.content.Context; import android.opengl.GLES20; import android.opengl.Matrix; public class Square { private Context context; private static final int BYTES_PER_FLOAT = 4; static final int COORDS_PER_VERTEX = 2; static float squareCoords[] = { -0.5f, 0.5f , 0.5f, 0.5f , 0.5f, -0.5f , -0.5f, -0.5f }; private FloatBuffer vertexBuffer; private static final String A_POSITION = "a_Position"; private static final String U_COLOR = "u_Color"; private static final String U_MATRIX = "u_Matrix"; private int uColorLocation; private int aPositionLocation; private int uMatrixLocation; private int program; private static final int POSITION_COMPONENT_COUNT = 4; float[] projectionMatrix = new float[16]; public Square(Context context) { this.context = context; vertexBuffer = ByteBuffer .allocateDirect(squareCoords.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexBuffer.put(squareCoords); 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.simple_vertex_shader); String fragmentShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.simple_fragment_shader); program = ShaderHelper.buildProgram(vertexShaderSource, fragmentShaderSource); GLES20.glUseProgram(program); } public void projectionMatrix(int width,int height){ final float aspectRatio = width > height ? (float) width / (float) height : (float) height / (float) width; if(width > height){ Matrix.orthoM(projectionMatrix, 0, -aspectRatio, aspectRatio, -1f, 1f, -1f, 1f); }else{ Matrix.orthoM(projectionMatrix, 0, -1f, 1f, -aspectRatio, aspectRatio, -1f, 1f); } } public void draw(){ GLES20.glUniformMatrix4fv(uMatrixLocation, 1, false, projectionMatrix, 0); GLES20.glUniform4f(uColorLocation, 0.0f, 0.0f, 1.0f, 1.0f); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, POSITION_COMPONENT_COUNT); } }
 package com.cumt.render; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import com.cumt.shape.Square; import android.content.Context; import android.opengl.GLSurfaceView.Renderer; import android.util.Log; import static android.opengl.GLES20.glClear; import static android.opengl.GLES20.glClearColor; import static android.opengl.GLES20.glViewport; import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT; public class MyRender implements Renderer { private Context context; public MyRender(Context context){ this.context = context; } Square square; public void onSurfaceCreated(GL10 gl, EGLConfig config) { Log.w("MyRender","onSurfaceCreated"); glClearColor(1.0f, 1.0f, 1.0f, 0.0f); square = new Square(context); } public void onSurfaceChanged(GL10 gl, int width, int height) { Log.w("MyRender","onSurfaceChanged"); glViewport(0,0,width,height); square.projectionMatrix(width, height); } public void onDrawFrame(GL10 gl) { Log.w("MyRender","onDrawFrame"); glClear(GL_COLOR_BUFFER_BIT); square.draw(); } }
 //simple_vertex_shader.glsl uniform mat4 u_Matrix; attribute vec4 a_Position; void main() { gl_Position = u_Matrix * a_Position; } 

把它跑起來,你會看到一個居中的純藍色正方形:

接下來準備我們要貼上去的素材,這是一張 512 × 512 的圖片。這裡要特別提醒:在 OpenGL ES 2.0 中,紋理並不強制要求正方形,但每一條邊的長度都應該是 2 的冪(power of two)。

目標就是這張圖,把它牢牢地貼到剛才那個正方形上。

正式開工:紋理貼圖全流程

整個流程可以先用一張示意圖來建立整體概念:

第一步:編寫紋理工具類

 package com.cumt.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLUtils; import android.util.Log; public class TextureHelper { public static final String TAG = "TextureHelper"; public static int loadTexture(Context context,int resourceId){ final int[] textureObjectId = new int[1]; GLES20.glGenTextures(1,textureObjectId, 0); if(textureObjectId[0] == 0){ if(LoggerConfig.ON){ Log.w(TAG,"Could not generate a new Opengl texture object"); } return 0; } final BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = false; final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),resourceId, options); if(bitmap == null){ if(LoggerConfig.ON){ Log.w(TAG,"ResourceId:"+resourceId+"could not be decoded"); } GLES20.glDeleteTextures(1, textureObjectId, 0); return 0; } GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,textureObjectId[0]); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_LINEAR_MIPMAP_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); return textureObjectId[0]; } } 

這裡有必要聊聊「紋理過濾」的概念。它通常出現在兩種場景:一種是紋理被縮小時(GL_TEXTURE_MIN_FILTER),例如一張 512 × 512 的貼圖最終在螢幕上只佔據 256 × 256 的像素區域,此時一個螢幕像素往往對應著多個紋理單元;另一種則是紋理被放大時(GL_TEXTURE_MAG_FILTER)。

OpenGL 提供的紋理過濾模式主要有:

GL_NEAREST(最近鄰過濾)、GL_NEAREST_MIPMAP_NEAREST、GL_NEAREST_MIPMAP_LINEAR、GL_LINEAR(雙線性過濾)、GL_LINEAR_MIPMAP_NEAREST、GL_LINEAR_MIPMAP_LINEAR(三線性過濾)。

在縮放的不同情境下,可用的模式並不相同。縮小時上述六種都支援;而放大時僅支援 GL_NEAREST 與 GL_LINEAR 兩種。

最近鄰過濾的思路很樸素:當像素座標沒有剛好落在采樣點上時,就取距離最近的采樣點。放大時鋸齒感明顯,每個紋理單元像一個小方塊;縮小時則會丟失大量細節。

雙線性過濾利用插值讓像素之間的過渡更平滑,放大時鋸齒顯著減少,畫面更柔和。

MIP 貼圖則是為了應對「縮得太小導致細節流失、產生噪點,甚至在物體移動時出現閃爍」的問題而生。想深入了解可參考維基百科:https://en.wikipedia.org/wiki/Mipmap

三線性過濾則負責消除不同 MIP 貼圖層級之間的過渡痕跡,換來更為平滑自然的成像。

第二步:編寫新的著色器

動手之前,先認識一下 OpenGL 的二維紋理座標系統:

每張二維紋理都有屬於自己的座標空間,用 S 與 T 兩個維度來描述,取值範圍都在 0 到 1 之間。

頂點著色器:

 //texture_vertex_shader.glsl uniform mat4 u_Matrix; attribute vec4 a_Position; attribute vec2 a_TextureCoordinates; varying vec2 v_TextureCoordinates; void main() { v_TextureCoordinates = a_TextureCoordinates; gl_Position = u_Matrix * a_Position; } 

其中 a_TextureCoordinates 用來接收紋理座標數據,v_TextureCoordinates 則負責把紋理座標傳遞給片段著色器;由於紋理含 S、T 兩個分量,因此選用 vec2 型別。

片段著色器:

 //texture_fragment_shader.glsl precision mediump float; uniform sampler2D u_TextureUnit; varying vec2 v_TextureCoordinates; void main() { gl_FragColor = texture2D(u_TextureUnit, v_TextureCoordinates); }

texture2D 是著色器語言內建的紋理采樣函數,會依據傳入的紋理座標進行采樣,回傳值為 vec4 型別。

第三步:設定紋理座標

 //矩形頂點坐標 與 紋理坐標 static float squareCoords[] = { //x y s t -0.5f, 0.5f , 0 , 0 , // top left 0.5f, 0.5f , 1 , 0 ,// top right 0.5f, -0.5f , 1 , 1 ,// bottom right -0.5f, -0.5f , 0 , 1}; // bottom left 

關鍵在於對應關係:我們把矩形左上角對應到紋理的 (0, 0)。請務必記牢,一張圖片左上角的紋理座標是 (0, 0),而不是 (0, 1)。

紋理工具類已經準備就緒,接下來只要呼叫它,再把數據餵給著色器即可。此時 Square 類的完整程式碼如下:

 package com.cumt.shape; import static android.opengl.GLES20.GL_TEXTURE0; import static android.opengl.GLES20.GL_TEXTURE_2D; import static android.opengl.GLES20.glActiveTexture; import static android.opengl.GLES20.glBindTexture; import static android.opengl.GLES20.glUniform1i; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import com.cumt.openglesrectangle.R; import com.cumt.utils.ShaderHelper; import com.cumt.utils.TextResourceReader; import com.cumt.utils.TextureHelper; import android.content.Context; import android.opengl.GLES20; import android.opengl.Matrix; public class Square { private Context context; private static final int BYTES_PER_FLOAT = 4; static final int COORDS_PER_VERTEX = 2; static float squareCoords[] = { -0.5f, 0.5f , 0 , 0 , 0.5f, 0.5f , 1 , 0 , 0.5f, -0.5f , 1 , 1 , -0.5f, -0.5f , 0 , 1}; private FloatBuffer vertexBuffer; private static final int VERTEX_COUNTS = 4; private static final int POSITION_COMPONENT_COUNT = 2; private static final int TEXTURE_COORDIANTES_COMPONENT_COUNT = 2; private static final int STRIDE = (POSITION_COMPONENT_COUNT + TEXTURE_COORDIANTES_COMPONENT_COUNT) * BYTES_PER_FLOAT; private static final String A_POSITION = "a_Position"; private static final String U_MATRIX = "u_Matrix"; private static final String A_TEXTURE_COORDINATES = "a_TextureCoordinates"; private static final String U_TEXTURE_UNIT = "u_TextureUnit"; private int aPositionLocation; private int uMatrixLocation; private int uTextureUnitLocation; private int aTextureCoordinates; private int program; private int texture; float[] projectionMatrix = new float[16]; public Square(Context context) { this.context = context; vertexBuffer = ByteBuffer .allocateDirect(squareCoords.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexBuffer.put(squareCoords); vertexBuffer.position(0); getProgram(); aPositionLocation = GLES20.glGetAttribLocation(program, A_POSITION); uMatrixLocation = GLES20.glGetUniformLocation(program, U_MATRIX); aTextureCoordinates = GLES20.glGetAttribLocation(program, A_TEXTURE_COORDINATES); uTextureUnitLocation = GLES20.glGetAttribLocation(program, U_TEXTURE_UNIT); texture = TextureHelper.loadTexture(context, R.drawable.umei); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glUniform1i(uTextureUnitLocation, 0); GLES20.glVertexAttribPointer(aPositionLocation, POSITION_COMPONENT_COUNT, GLES20.GL_FLOAT, false, STRIDE, vertexBuffer); GLES20.glEnableVertexAttribArray(aPositionLocation); vertexBuffer.position(POSITION_COMPONENT_COUNT); GLES20.glVertexAttribPointer(aTextureCoordinates, TEXTURE_COORDIANTES_COMPONENT_COUNT, GLES20.GL_FLOAT, false, STRIDE, vertexBuffer); GLES20.glEnableVertexAttribArray(aTextureCoordinates); } private void getProgram(){ String vertexShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.texture_vertex_shader); String fragmentShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.texture_fragment_shader); program = ShaderHelper.buildProgram(vertexShaderSource, fragmentShaderSource); GLES20.glUseProgram(program); } public void projectionMatrix(int width,int height){ final float aspectRatio = width > height ? (float) width / (float) height : (float) height / (float) width; if(width > height){ Matrix.orthoM(projectionMatrix, 0, -aspectRatio, aspectRatio, -1f, 1f, -1f, 1f); }else{ Matrix.orthoM(projectionMatrix, 0, -1f, 1f, -aspectRatio, aspectRatio, -1f, 1f); } } public void draw(){ GLES20.glUniformMatrix4fv(uMatrixLocation, 1, false, projectionMatrix, 0); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, VERTEX_COUNTS); } }

為了便於觀察效果,可以把 MyRender 類 onSurfaceCreated 方法中的清屏顏色改為 glClearColor(0.5f, 0.5f, 0.5f, 1.0f)。

運行一下,你就會看到心愛的圖片已經成功貼到了正方形上:

至此,一次完整的紋理貼圖就大功告成了。

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