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

OpenGL ES 2.0 在 Android 上:手把手畫出一顆逼真的球

編輯:關於 Android 程式設計

先搞懂球座標系

動手之前,先來認識球的座標系:

設球面上有一點 A,球心為 O。OA 在 xOy 平面上的投影與 X 軸的夾角記為 φ(範圍 0 到 360,單位為度),OA 與 Z 軸的夾角記為 θ(範圍 0 到 180,單位為度),球半徑為 r,則有以下關係:

r × sinθ = y / sinφ
r × sinθ = x / cosφ
z = r × cosθ

由此便能推導出 X、Y、Z 三軸座標。

我們此前已經知道,在 OpenGL ES 中,任何三維形體歸根結底都是由三角形拼湊而成,球自然也不例外。那麼如何僅用一堆三角形拼出一顆球呢?回想一下當初畫圓的思路:我們實際畫的是一個正 N 邊形,當 N 足夠大,肉眼看上去就是一個圓。球同理:

當我們切分得足夠細密時,它看起來就是一個球了:

球的頂點座標與繪製

從矩形的角度來看,我們要畫的球其實是由無數小矩形拼成的:

把其中一個小矩形單拎出來分析。

問題一:如何確定這個矩形的位置?其實只要知道它左上角的頂點座標,整個矩形便定死了。而這個頂點座標顯然與三個量有關:角度 φ(0 到 360 度)、角度 θ(0 到 180 度),以及半徑 r。r 可以取一個固定值,因此只需一層雙重循環,就能遍歷出所有矩形的左上角頂點。先寫一段計算該頂點的程式碼:

 public void initVertexData(){ int angleSpan = 90; float r = 0.6f; final float UNIT_SIZE = 1.0f; for (int vAngle = 0; vAngle < 180; vAngle = vAngle + angleSpan) { for (int hAngle = 0; hAngle <= 360; hAngle = hAngle + angleSpan) { float x0 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.cos(Math .toRadians(hAngle))); float y0 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.sin(Math .toRadians(hAngle))); float z0 = (float) (r * UNIT_SIZE * Math.cos(Math .toRadians(vAngle))); } } }

每輪循環我們都得到一個四邊形的左上角頂點。學會求它之後,另外三個頂點也就手到擒來了。好,畫球計劃正式起步!我們直接在此前那一節的專案基礎上繼續(會用到之前的工具類,別從零開始),在 shape 目錄下新建一個 Ball 類:

 package com.cumt.shape; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.ArrayList; public class Ball { private static final float UNIT_SIZE = 1.0f; private float r = 0.6f; final int angleSpan = 10; private FloatBuffer vertexBuffer; int vCount = 0; private static final int BYTES_PER_FLOAT = 4; private static final int COORDS_PER_VERTEX = 3; public void initVertexData() { ArrayList alVertix = new ArrayList(); for (int vAngle = 0; vAngle < 180; vAngle = vAngle + angleSpan) { for (int hAngle = 0; hAngle <= 360; hAngle = hAngle + angleSpan) { float x0 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.cos(Math .toRadians(hAngle))); float y0 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.sin(Math .toRadians(hAngle))); float z0 = (float) (r * UNIT_SIZE * Math.cos(Math .toRadians(vAngle))); float x1 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.cos(Math .toRadians(hAngle + angleSpan))); float y1 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.sin(Math .toRadians(hAngle + angleSpan))); float z1 = (float) (r * UNIT_SIZE * Math.cos(Math .toRadians(vAngle))); float x2 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)) * Math .cos(Math.toRadians(hAngle + angleSpan))); float y2 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)) * Math .sin(Math.toRadians(hAngle + angleSpan))); float z2 = (float) (r * UNIT_SIZE * Math.cos(Math .toRadians(vAngle + angleSpan))); float x3 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)) * Math .cos(Math.toRadians(hAngle))); float y3 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)) * Math .sin(Math.toRadians(hAngle))); float z3 = (float) (r * UNIT_SIZE * Math.cos(Math .toRadians(vAngle + angleSpan))); alVertix.add(x1); alVertix.add(y1); alVertix.add(z1); alVertix.add(x3); alVertix.add(y3); alVertix.add(z3); alVertix.add(x0); alVertix.add(y0); alVertix.add(z0); alVertix.add(x1); alVertix.add(y1); alVertix.add(z1); alVertix.add(x2); alVertix.add(y2); alVertix.add(z2); alVertix.add(x3); alVertix.add(y3); alVertix.add(z3); } } vCount = alVertix.size() / COORDS_PER_VERTEX; float vertices[] = new float[vCount * COORDS_PER_VERTEX]; for (int i = 0; i < alVertix.size(); i++) { vertices[i] = alVertix.get(i); } vertexBuffer = ByteBuffer .allocateDirect(vertices.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexBuffer.put(vertices); vertexBuffer.position(0); } } 

這裡用 ArrayList 存放頂點座標,要特別留意順序——因為每個小矩形仍是由兩個三角形組成的,這六個頂點必須恰好拼出這兩個三角形。

接著在 res/raw 目錄下新建頂點與片段著色器:

 //vertex_shader_ball.glsl uniform mat4 u_Matrix; attribute vec4 a_Position; void main() { gl_Position = u_Matrix * a_Position; } 
 precision mediump float; void main() { gl_FragColor=vec4(0.2,1.0,0.129,0); }

之後和前面一樣,編譯、鏈接。此時 Ball 類的完整程式碼如下:

 package com.cumt.shape; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.ArrayList; import android.content.Context; import android.opengl.GLES20; import com.cumt.opengeschange.R; import com.cumt.utils.MatrixState; import com.cumt.utils.ShaderHelper; import com.cumt.utils.TextResourceReader; public class Ball { private Context context; private static final float UNIT_SIZE = 1.0f; private float r = 0.6f; final int angleSpan = 10; private FloatBuffer vertexBuffer; int vCount = 0; private static final int BYTES_PER_FLOAT = 4; private static final int COORDS_PER_VERTEX = 3; private int program; private static final String A_POSITION = "a_Position"; private static final String U_MATRIX = "u_Matrix"; private int uMatrixLocation; private int aPositionLocation; public Ball(Context context){ this.context = context; initVertexData(); getProgram(); 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); } public void initVertexData() { ArrayList alVertix = new ArrayList(); for (int vAngle = 0; vAngle < 180; vAngle = vAngle + angleSpan) { for (int hAngle = 0; hAngle <= 360; hAngle = hAngle + angleSpan) { float x0 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.cos(Math .toRadians(hAngle))); float y0 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.sin(Math .toRadians(hAngle))); float z0 = (float) (r * UNIT_SIZE * Math.cos(Math .toRadians(vAngle))); float x1 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.cos(Math .toRadians(hAngle + angleSpan))); float y1 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle)) * Math.sin(Math .toRadians(hAngle + angleSpan))); float z1 = (float) (r * UNIT_SIZE * Math.cos(Math .toRadians(vAngle))); float x2 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)) * Math .cos(Math.toRadians(hAngle + angleSpan))); float y2 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)) * Math .sin(Math.toRadians(hAngle + angleSpan))); float z2 = (float) (r * UNIT_SIZE * Math.cos(Math .toRadians(vAngle + angleSpan))); float x3 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)) * Math .cos(Math.toRadians(hAngle))); float y3 = (float) (r * UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)) * Math .sin(Math.toRadians(hAngle))); float z3 = (float) (r * UNIT_SIZE * Math.cos(Math .toRadians(vAngle + angleSpan))); alVertix.add(x1); alVertix.add(y1); alVertix.add(z1); alVertix.add(x3); alVertix.add(y3); alVertix.add(z3); alVertix.add(x0); alVertix.add(y0); alVertix.add(z0); alVertix.add(x1); alVertix.add(y1); alVertix.add(z1); alVertix.add(x2); alVertix.add(y2); alVertix.add(z2); alVertix.add(x3); alVertix.add(y3); alVertix.add(z3); } } vCount = alVertix.size() / COORDS_PER_VERTEX; float vertices[] = new float[vCount * COORDS_PER_VERTEX]; for (int i = 0; i < alVertix.size(); i++) { vertices[i] = alVertix.get(i); } vertexBuffer = ByteBuffer .allocateDirect(vertices.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexBuffer.put(vertices); vertexBuffer.position(0); } private void getProgram(){ String vertexShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.vertex_shader_ball); String fragmentShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.fragment_shader_ball); 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, vCount); } } 

接著在 MyRender 中創建球物件,設置照相機與透視投影並繪製:

 package com.cumt.render; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import com.cumt.shape.Ball; import com.cumt.utils.MatrixState; import android.content.Context; import android.opengl.GLES20; 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; public class MyRender implements Renderer { private Context context; Ball ball; public MyRender(Context context){ this.context = context; } public void onSurfaceCreated(GL10 gl, EGLConfig config) { Log.w("MyRender","onSurfaceCreated"); glClearColor(0.5f,0.5f,0.5f, 1.0f); GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glEnable(GLES20.GL_CULL_FACE); ball = new Ball(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(0, 0, 30, 0f, 0f, 0f, 0f, 1.0f, 0.0f); } public void onDrawFrame(GL10 gl) { glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); ball.draw(); } } 

再來實現透過螢幕點擊事件來旋轉物體,在原來的 MySurfaceView 中加入該功能:

 package com.cumt.opengeschange; import com.cumt.render.MyRender; import com.cumt.utils.MatrixState; import android.content.Context; import android.opengl.GLSurfaceView; import android.view.MotionEvent; import android.view.View; public class MySurfaceView extends GLSurfaceView { private MyRender myRender; public MySurfaceView(Context context) { super(context); myRender = new MyRender(context); this.setEGLContextClientVersion(2); this.setRenderer(myRender); this.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); this.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: MatrixState.rotate(20f, 0, 1, 0); } return true; } }); } }

跑起來看看:

棋盤紋理著色

什麼狀況?分明是個圓嘛!而且點擊螢幕後也沒什麼變化。其實我們已經把球畫出來了,只是缺少光照或紋理,肉眼很難辨認它是個球。接下來,我們就來想辦法讓它「球味十足」。光照暫且不談,先考慮棋盤紋理著色器。所謂棋盤紋理,如下圖所示:

來梳理一下繪製策略。不妨把球想像成由一個邊長為 2r 的立方體切割而來(r 為球半徑)。把這個立方體切成一個個小立方體,每個小立方體的位置由所在層數、行數、列數共同決定。類推到球表面:此時球面是一個個分割後的小矩形,每個小矩形的位置同樣由層數、行數、列數確定。

假設分割的層數、行數、列數都是 n,某頂點座標為 (x, y, z),如何求它所在的層、行、列?球半徑為 r,直徑為 2r,則每個小正方形邊長為 2r / n。該頂點 Y 軸座標為 y,距底層的距離為 y + r,故所在層數為 (y + r) / (2r / n);同理,行數為 (x + r) / (2r / n),列數為 (z + r) / (2r / n)。三者相加必為奇數或偶數:若為奇數,把該片元著色為一種顏色;若為偶數,則著為另一種顏色。如此便完成了棋盤著色策略。

下面動手改動著色器。先看頂點著色器:

 //vertex_shader_ball.glsl uniform mat4 u_Matrix; attribute vec4 a_Position; varying vec4 vPosition; void main() { gl_Position = u_Matrix * a_Position; vPosition = a_Position; } 

這裡新增了一個 varying vec4 vPosition,用於把頂點座標傳遞給片元著色器,後者再定義同名 varying 變數來接收。

片段著色器:

 precision mediump float; varying vec4 vPosition; void main() { float uR = 0.6; vec4 color; float n = 8.0; float span = 2.0*uR/n; int i = int((vPosition.x + uR)/span); int j = int((vPosition.y + uR)/span); int k = int((vPosition.z + uR)/span); int colorType = int(mod(float(i+j+k),2.0)); if(colorType == 1) { color = vec4(0.2,1.0,0.129,0); } else { color = vec4(1.0,1.0,1.0,0); } gl_FragColor=color; } 

OK,再跑一遍看看:

Good job!點擊螢幕,我們還能看到球繞著 Y 軸旋轉起來了。一顆立體感十足的球,就這樣在我們手中誕生。

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