OpenGL ES绘制魔方
Posted little_fat_sheep
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OpenGL ES绘制魔方相关的知识,希望对你有一定的参考价值。
1 前言
在立方体贴图(6张图)中,绘制了一个立方体,贴了 6 张图,本文的魔方案例,将实现绘制 27个立方体,贴 162 张图。贴图图片如下:
说明:inside.png 为魔方内部色块,用粉红色块代替白色块是为了凸显白色线框。
读者如果对 OpenGL ES 不太熟悉,请回顾以下内容:
本文完整代码资源见→【OpenGL ES】绘制魔方
项目目录如下:
2 案例
MainActivity.java
package com.zhyan8.rubik;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
private GLSurfaceView mGlSurfaceView;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
mGlSurfaceView = new MyGLSurfaceView(this);
setContentView(mGlSurfaceView);
mGlSurfaceView.setRenderer(new MyRender(this));
@Override
protected void onResume()
super.onResume();
mGlSurfaceView.onResume();
@Override
protected void onPause()
super.onPause();
mGlSurfaceView.onPause();
MyGLSurfaceView.java
package com.zhyan8.rubik;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
public class MyGLSurfaceView extends GLSurfaceView
public MyGLSurfaceView(Context context)
super(context);
setEGLContextClientVersion(3);
public MyGLSurfaceView(Context context, AttributeSet attrs)
super(context, attrs);
setEGLContextClientVersion(3);
MyRender.java
package com.zhyan8.rubik;
import android.content.Context;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class MyRender implements GLSurfaceView.Renderer
private Model model;
private FloatBuffer vertexBuffer;
private FloatBuffer textureBuffer;
private int[] mipmap;
private MyGLUtils mGLUtils;
private int mProgramId;
private float mRatio;
private int[] mTextureIds;
public MyRender(Context context)
model = new Model();
mGLUtils = new MyGLUtils(context);
getFloatBuffer();
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig)
//设置背景颜色
GLES30.glClearColor(0.1f, 0.2f, 0.3f, 0.4f);
//启动深度测试
gl.glEnable(GLES30.GL_DEPTH_TEST);
//编译着色器
final int vertexShaderId = mGLUtils.compileShader(GLES30.GL_VERTEX_SHADER, R.raw.vertex_shader);
final int fragmentShaderId = mGLUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, R.raw.fragment_shader);
//链接程序片段
mProgramId = mGLUtils.linkProgram(vertexShaderId, fragmentShaderId);
GLES30.glUseProgram(mProgramId);
mTextureIds = mGLUtils.loadTexture(mipmap);
@Override
public void onSurfaceChanged(GL10 gl, int width, int height)
//设置视图窗口
GLES30.glViewport(0, 0, width, height);
mRatio = 1.0f * width / height;
@Override
public void onDrawFrame(GL10 gl)
//将颜色缓冲区设置为预设的颜色
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT | GLES30.GL_DEPTH_BUFFER_BIT);
mGLUtils.transform(mProgramId, mRatio); //计算MVP变换矩阵
//启用顶点的数组句柄
GLES30.glEnableVertexAttribArray(0);
GLES30.glEnableVertexAttribArray(1);
//准备顶点坐标和纹理坐标
GLES30.glVertexAttribPointer(0, 3, GLES30.GL_FLOAT, false, 0, vertexBuffer);
GLES30.glVertexAttribPointer(1, 2, GLES30.GL_FLOAT, false, 0, textureBuffer);
//激活纹理
GLES30.glActiveTexture(GLES30.GL_TEXTURE);
//绘制纹理
drawTextures();
//禁止顶点数组句柄
GLES30.glDisableVertexAttribArray(0);
GLES30.glDisableVertexAttribArray(1);
private void getFloatBuffer()
vertexBuffer = mGLUtils.getFloatBuffer(model.getVertex());
textureBuffer = mGLUtils.getFloatBuffer(model.getTexture());
mipmap = model.getMipmap();
private void drawTextures()
int count = 4;
for (int i =0; i < mTextureIds.length; i++)
int first = i * count;
//绑定纹理
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mTextureIds[i]);
//绘制魔方(162个方块,每个方块2个三角形)
GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, first, count);
GLUtils.java
package com.zhyan8.rubik;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES30;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
public class MyGLUtils
private Context mContext;
private int mRotateAgree = 0;
public MyGLUtils(Context context)
mContext = context;
public FloatBuffer getFloatBuffer(float[] floatArr)
FloatBuffer fb = ByteBuffer.allocateDirect(floatArr.length * Float.BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
fb.put(floatArr);
fb.position(0);
return fb;
//通过代码片段编译着色器
public int compileShader(int type, String shaderCode)
int shader = GLES30.glCreateShader(type);
GLES30.glShaderSource(shader, shaderCode);
GLES30.glCompileShader(shader);
return shader;
//通过外部资源编译着色器
public int compileShader(int type, int shaderId)
String shaderCode = readShaderFromResource(shaderId);
return compileShader(type, shaderCode);
//链接到着色器
public int linkProgram(int vertexShaderId, int fragmentShaderId)
final int programId = GLES30.glCreateProgram();
//将顶点着色器加入到程序
GLES30.glAttachShader(programId, vertexShaderId);
//将片元着色器加入到程序
GLES30.glAttachShader(programId, fragmentShaderId);
//链接着色器程序
GLES30.glLinkProgram(programId);
return programId;
//从shader文件读出字符串
private String readShaderFromResource(int shaderId)
InputStream is = mContext.getResources().openRawResource(shaderId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder sb = new StringBuilder();
try
while ((line = br.readLine()) != null)
sb.append(line);
sb.append("\\n");
br.close();
catch (Exception e)
e.printStackTrace();
return sb.toString();
//加载纹理贴图
public int[] loadTexture(int[] resIds)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap[] bitmaps = new Bitmap[resIds.length];
// 生成纹理id
final int[] textureIds = new int[resIds.length];
GLES30.glGenTextures(resIds.length, textureIds, 0);
for (int i = 0; i < resIds.length; i++)
bitmaps[i] = BitmapFactory.decodeResource(mContext.getResources(), resIds[i], options);
// 绑定纹理到OpenGL
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureIds[i]);
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR_MIPMAP_LINEAR);
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR);
// 加载bitmap到纹理中
GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmaps[i], 0);
// 生成MIP贴图
GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D);
// 取消绑定纹理
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
bitmaps[i].recycle();
return textureIds;
//计算MVP变换矩阵
public void transform(int programId, float ratio)
//初始化modelMatrix, viewMatrix, projectionMatrix
float[] modelMatrix = getIdentityMatrix(16, 0); //模型变换矩阵
float[] viewMatrix = getIdentityMatrix(16, 0); //观测变换矩阵
float[] projectionMatrix = getIdentityMatrix(16, 0); //投影变换矩阵
//获取modelMatrix, viewMatrix, projectionMatrix
mRotateAgree = (mRotateAgree + 2) % 360;
Matrix.rotateM(modelMatrix, 0, mRotateAgree, -1, -1, 1); //获取模型旋转变换矩阵
Matrix.setLookAtM(viewMatrix, 0, 0, 5, 10, 0, 0, 0, 0, 1, 0); //获取观测变换矩阵
Matrix.frustumM(projectionMatrix, 0, -ratio, ratio, -1, 1, 3, 20); //获取投影变换矩阵
//计算MVP变换矩阵: mvpMatrix = projectionMatrix * viewMatrix * modelMatrix
float[] tempMatrix = new float[16];
float[] mvpMatrix = new float[16];
Matrix.multiplyMM(tempMatrix, 0, viewMatrix, 0, modelMatrix, 0);
Matrix.multiplyMM(mvpMatrix, 0, projectionMatrix, 0, tempMatrix, 0);
//设置MVP变换矩阵
int mvpMatrixHandle = GLES30.glGetUniformLocation(programId, "mvpMatrix");
GLES30.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0);
private float[] getIdentityMatrix(int size, int offset)
float[] matrix = new float[size];
Matrix.setIdentityM(matrix, offset);
return matrix;
Model.java
package com.zhyan8.rubik;
public class Model
private final int PLANE_NUM = 3 * 6; // 面数
private final int SQUARE_NUM_PER_PLANE = 9; // 每面方块数
private final int VERTEXT_NUM_PER_SQUARE = 4; // 每个方块顶点数
private final int DIMENSION_PER_VERTEXT = 3; // 每个顶点坐标维度
private final int DIMENSION_PER_TEXTURE = 2; // 每个纹理坐标维度
private final float SQUARE_SIDE = 0.7f; // 每个方块的边长
private final float HALF_PLANE_SIDE = 1.5f * SQUARE_SIDE; //每个面的边长的一半
private final int[] RESOURCE_ID = new int[] // 图片资源id
R.raw.white, R.raw.yellow, R.raw.blue, R.raw.green,
R.raw.orange, R.raw.red, R.raw.inside
;
// 顶点坐标数组
private float[][][][] vertex = new float[PLANE_NUM][SQUARE_NUM_PER_PLANE][VERTEXT_NUM_PER_SQUARE][DIMENSION_PER_VERTEXT];
// 纹理坐标数组
private float[][][][] texture = new float[PLANE_NUM][SQUARE_NUM_PER_PLANE][VERTEXT_NUM_PER_SQUARE][DIMENSION_PER_TEXTURE];
// 贴图资源数组
private int[][] mipmap = new int[PLANE_NUM][SQUARE_NUM_PER_PLANE];
public Model()
initModel();
// 初始化模型顶点坐标和纹理坐标
private void initModel()
for (int i = 0; i < 3; i++) // 遍历三视图
initView(i);
// 初始化三视图顶点坐标和纹理坐标
private void initView(int direction)
int baseIndex = direction * 6;
int axis = 2 - direction; // 固定的坐标轴
for (int i = 0; i < 6; i++)
int planeIndex = baseIndex + i;
float value = HALF_PLANE_SIDE - ((i + 1) / 2) * SQUARE_SIDE;
initPlane(planeIndex, axis, value);
initMipmap(direction, planeIndex, i);
// 初始化贴图资源
private void initMipmap(int direction, int planeIndex, int seq)
int near = direction * 2;
int far = near + 1;
int inside = 6;
int index = (seq == 0 ? near : (seq == 5 ? far : inside));
for (int i = 0; i < SQUARE_NUM_PER_PLANE; i++)
mipmap[planeIndex][i] = RESOURCE_ID[index];
// 初始化一个面顶点坐标和纹理坐标
private void initPlane(int planeIndex, int axis, float value)
for (int i = 0; i < 9; i++)
initSquare(planeIndex, i, axis, value);
// 初始化一个方块顶点坐标和纹理坐标
private void initSquare(int planeIndex, int squareIndex, int axis, float value)
float row = HALF_PLANE_SIDE - SQUARE_SIDE * (squareIndex / 3);
float col = -HALF_PLANE_SIDE + SQUARE_SIDE * (squareIndex % 3);
switch(axis)
case 0: // 右视图
for (int i = 0; i < 4; i++)
vertex[planeIndex][squareIndex][i][0] = value;
vertex[planeIndex][squareIndex][i][1] = row - SQUARE_SIDE * (i / 2);
vertex[planeIndex][squareIndex][i][2] = col + SQUARE_SIDE * (i % 2);
break;
case 1: // 俯视图
for (int i = 0; i < 4; i++)
vertex[planeIndex][squareIndex][i][0] = col + SQUARE_SIDE * (i % 2);
vertex[planeIndex][squareIndex][i][1] = value; //axis
vertex[planeIndex][squareIndex][i][2] = row - SQUARE_SIDE * (i / 2);
break;
case 2: // 正视图
for (int i = 0; i < 4; i++)
vertex[planeIndex][squareIndex][i][0] = col + SQUARE_SIDE * (i % 2);
vertex[planeIndex][squareIndex][i][1] = row - SQUARE_SIDE * (i / 2);
vertex[planeIndex][squareIndex][i][2] = value;
break;
for (int i = 0; i < 4; i++)
texture[planeIndex][squareIndex][i][0] = i % 2;
texture[planeIndex][squareIndex][i][1] = i / 2;
// 获取顶点坐标
public float[] getVertex()
int length = PLANE_NUM * SQUARE_NUM_PER_PLANE * VERTEXT_NUM_PER_SQUARE * DIMENSION_PER_VERTEXT;
float[] res = new float[length];
int index = 0;
for (int i = 0; i < PLANE_NUM; i++)
for (int j = 0; j < SQUARE_NUM_PER_PLANE; j++)
for (int k = 0; k < VERTEXT_NUM_PER_SQUARE; k++)
int ver = k * DIMENSION_PER_VERTEXT;
for (int l = 0; l < DIMENSION_PER_VERTEXT; l++)
res[index++] = vertex[i][j][k][l];
return res;
// 获取纹理坐标
public float[] getTexture()
int length = PLANE_NUM * SQUARE_NUM_PER_PLANE * VERTEXT_NUM_PER_SQUARE * DIMENSION_PER_TEXTURE;
float[] res = new float[length];
int index = 0;
for (int i = 0; i < PLANE_NUM; i++)
for (int j = 0; j < SQUARE_NUM_PER_PLANE; j++)
for (int k = 0; k < VERTEXT_NUM_PER_SQUARE; k++)
for (int l = 0; l < DIMENSION_PER_TEXTURE; l++)
res[index++] = texture[i][j][k][l];
return res;
public int[] getMipmap()
int length = PLANE_NUM * SQUARE_NUM_PER_PLANE;
int[] res = new int[length];
int index = 0;
for (int i = 0; i < PLANE_NUM; i++)
for (int j = 0; j < SQUARE_NUM_PER_PLANE; j++)
res[index++] = mipmap[i][j];
return res;
说明:魔方绘制的循序是,从前往后,从上往下,从右往左绘制每一个面,共 18 个面。
vertex_shader.glsl
#version 300 es
layout (location = 0) in vec4 vPosition;
layout (location = 1) in vec2 aTextureCoord;
uniform mat4 mvpMatrix;
out vec2 vTexCoord;
void main()
gl_Position = mvpMatrix * vPosition;
vTexCoord = aTextureCoord;
顶点着色器的作用:进行矩阵变换位置、根据光照公式计算顶点颜⾊、⽣成 / 变换纹理坐标,并且把位置和纹理坐标发送到片元着色器。
顶点着色器中,如果没有指定默认精度,则 int 和 float 的默认精度都为 highp。
fragment_shader.glsl
#version 300 es
precision mediump float;
uniform sampler2D uTextureUnit;
in vec2 vTexCoord;
out vec4 fragColor;
void main()
fragColor = texture(uTextureUnit,vTexCoord);
片元着色器的作用:处理经光栅化阶段生成的每个片元,计算每个像素的颜色和透明度。
在片元着色器中,浮点值没有默认的精度值,每个着色器必须声明一个默认的 float 精度。
运行效果:
声明:本文转自【OpenGL ES】绘制魔方
以上是关于OpenGL ES绘制魔方的主要内容,如果未能解决你的问题,请参考以下文章