1 前言
????????正方形图片贴到圆形上?中将正方形图片上的纹理映射到圆形模型上,同理,也可以将圆形上的纹理映射到凸镜的球形曲面上。如下图,最左边的竖条是原图片的截面(纹理坐标),最右边的竖条是变换后的顶点模型截面(顶点坐标)。
????????原图如下:
????????读者如果对 OpenGL ES 不太熟悉,请回顾以下内容:
????????本文完整代码资源见→【OpenGL ES】凸镜贴图
? ? ? ? 项目目录如下:
2 案例
????????MainActivity.java
package com.zhyan8.convexMirror.activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.zhyan8.convexMirror.opengl.MyGLSurfaceView;
import com.zhyan8.convexMirror.opengl.MyRender;
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(getResources()));
}
@Override
protected void onResume() {
super.onResume();
mGlSurfaceView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mGlSurfaceView.onPause();
}
}
?????????MyGLSurfaceView.java
package com.zhyan8.convexMirror.opengl;
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.convexMirror.opengl;
import android.content.res.Resources;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import com.zhyan8.convexMirror.model.Model;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class MyRender implements GLSurfaceView.Renderer {
private Model mModel;
private int mProgramId;
public MyRender(Resources resources) {
mModel = new Model(resources);
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig) {
//设置背景颜色
GLES30.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
//启动深度测试
gl.glEnable(GLES30.GL_DEPTH_TEST);
//创建程序id
mProgramId = mModel.onModelCreate();
GLES30.glUseProgram(mProgramId);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
//设置视图窗口
GLES30.glViewport(0, 0, width, height);
mModel.onModelChange(width, height);
}
@Override
public void onDrawFrame(GL10 gl) {
//将颜色缓冲区设置为预设的颜色
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT | GLES30.GL_DEPTH_BUFFER_BIT);
//启用顶点的数组句柄
GLES30.glEnableVertexAttribArray(0);
GLES30.glEnableVertexAttribArray(1);
//绘制模型
mModel.onModelDraw();
//禁止顶点数组句柄
GLES30.glDisableVertexAttribArray(0);
GLES30.glDisableVertexAttribArray(1);
}
}
? ? ? ??Model.java
package com.zhyan8.convexMirror.model;
import android.content.res.Resources;
import android.opengl.GLES30;
import com.zhyan8.convexMirror.R;
import com.zhyan8.convexMirror.utils.ArraysUtils;
import com.zhyan8.convexMirror.utils.ShaderUtils;
import com.zhyan8.convexMirror.utils.TextureUtils;
import java.nio.FloatBuffer;
public class Model {
private static final int RING_NUM = 30; // 环数
private static final int RAW_NUM = 50; // 射线数
private static final double CONE_SECTION_FAN_ANGLE = 170.0 / 180.0 * Math.PI; // 圆锥凸镜截面扇形弧度(180度为半球)
private static final double RING_WIDTH = 1.0 / RING_NUM; // 环宽度
private static final double RAW_GAP_ANGLE = 2 * Math.PI / RAW_NUM; // 两条射线间最小夹角
private static final int TEXTURE_DIMENSION = 2; // 纹理坐标维度
private static final int VERTEX_DIMENSION = 3; // 顶点坐标维度
private static final double EPSILON = 0.00000000001; // epsilon,比较小的浮点常量
private Resources mResources;
private MyTransform mTransform;
private float[][] mTextures;
private float[][] mVertices;
private FloatBuffer[] mTexturesBuffers;
private FloatBuffer[] mVerticesBuffers;
private int mTextureId;
private int mProgramId;
private int mPointNumPerRing;
public Model(Resources resources) {
mResources = resources;
mPointNumPerRing = (RAW_NUM + 1) * 2;
mTextures = new float[RING_NUM][mPointNumPerRing * TEXTURE_DIMENSION];
mVertices = new float[RING_NUM][mPointNumPerRing * VERTEX_DIMENSION];
mTexturesBuffers = new FloatBuffer[RING_NUM];
mVerticesBuffers = new FloatBuffer[RING_NUM];
mTransform = new MyTransform();
}
// 模型创建
public int onModelCreate() {
for (int i = 0; i < RING_NUM; i++) {
getRingTexture(i);
getRingVertex(i);
mTexturesBuffers[i] = ArraysUtils.getFloatBuffer(mTextures[i]);
mVerticesBuffers[i] = ArraysUtils.getFloatBuffer(mVertices[i]);
}
mProgramId = ShaderUtils.createProgram(mResources, R.raw.vertex_shader, R.raw.fragment_shader);
mTextureId = TextureUtils.loadTexture(mResources, R.raw.zzz);
mTransform.onTransformCreate(mProgramId);
return mProgramId;
}
// 模型参数变化
public void onModelChange(int width, int height) {
mTransform.onTransformChange(width, height);
}
// 模型绘制
public void onModelDraw() {
mTransform.onTransformExecute();
for (int i = 0; i < RING_NUM; i++) { // 一环一环绘制纹理
//准备顶点坐标和纹理坐标
GLES30.glVertexAttribPointer(0, VERTEX_DIMENSION, GLES30.GL_FLOAT, false, 0, mVerticesBuffers[i]);
GLES30.glVertexAttribPointer(1, TEXTURE_DIMENSION, GLES30.GL_FLOAT, false, 0, mTexturesBuffers[i]);
//激活纹理
GLES30.glActiveTexture(GLES30.GL_TEXTURE);
//绑定纹理
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mTextureId);
//绘制贴图
GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mPointNumPerRing);
// GLES30.glDrawArrays(GLES30.GL_LINE_STRIP, 0, mPointNumPerRing);
}
}
// 计算纹理坐标
private void getRingTexture(int ring) {
int rayNum = RAW_NUM + 1;
double theta = 0;
double radius1 = ring * RING_WIDTH / 2;
double radius2 = (ring + 1) * RING_WIDTH / 2;
int index = 0;
for (int i = 0; i < rayNum; i++) {
mTextures[ring][index++] = (float) (0.5 + radius1 * Math.cos(theta));
mTextures[ring][index++] = (float) (0.5 - radius1 * Math.sin(theta));
mTextures[ring][index++] = (float) (0.5 + radius2 * Math.cos(theta));
mTextures[ring][index++] = (float) (0.5 - radius2 * Math.sin(theta));
theta += RAW_GAP_ANGLE;
}
}
// 计算顶点坐标
private void getRingVertex(int ring) {
int index = 0;
for (int i = 0; i < mTextures[ring].length; i += TEXTURE_DIMENSION) {
float[] pos = getPosInWorldAxis(mTextures[ring][i], mTextures[ring][i + 1]);
textureVertexMapping(pos);
mVertices[ring][index++] = pos[0];
mVertices[ring][index++] = pos[1];
mVertices[ring][index++] = pos[2];
}
}
// 纹理坐标映射到顶点坐标
private void textureVertexMapping(float[] pos) {
double norm = Math.sqrt(pos[0] * pos[0] + pos[1] * pos[1]);
double alpha = CONE_SECTION_FAN_ANGLE / 2;
double beta = norm * alpha;
if (norm > EPSILON) {
double factor = Math.sin(beta) / Math.sin(alpha) / norm;
pos[0] = (float) (pos[0] * factor);
pos[1] = (float) (pos[1] * factor);
}
pos[2] = (float) ((Math.cos(beta) - Math.cos(alpha)) / alpha);
}
//纹理坐标转换为世界坐标
private float[] getPosInWorldAxis(float x, float y) {
float [] pos = new float[VERTEX_DIMENSION];
pos[0] = x * 2 - 1;
pos[1] = 1 - y * 2;
pos[2] = 1f;
return pos;
}
}
? ? ? ??MyTransform.java
package com.zhyan8.convexMirror.model;
import android.opengl.GLES30;
import android.opengl.Matrix;
public class MyTransform {
private static final float SCALE_RATE = 1.0f; // 模型缩放系数
private int mProgramId;
private float mRatio;
private int mRotateAgree = 0;
private int mMvpMatrixHandle;
private float[] mModelMatrix;
private float[] mViewMatrix;
private float[] mProjectionMatrix;
private float[] mMvpMatrix;
// 变换创建
public void onTransformCreate(int programId) {
mProgramId = programId;
mMvpMatrixHandle = GLES30.glGetUniformLocation(mProgramId, "mvpMatrix");
mViewMatrix = getIdentityMatrix(16, 0);
mMvpMatrix = getIdentityMatrix(16, 0);
Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 6, 0, 0, 0, 0, 1, 0);
}
// 变换参数变换
public void onTransformChange(int width, int height) {
mRatio = 1.0f * width / height;
mProjectionMatrix = getIdentityMatrix(16, 0);
Matrix.frustumM(mProjectionMatrix, 0, -mRatio, mRatio, -1, 1, 3, 20);
}
// 变换执行
public void onTransformExecute() {
mModelMatrix = getIdentityMatrix(16, 0);
mRotateAgree = (mRotateAgree + 1) % 360;
Matrix.rotateM(mModelMatrix, 0, mRotateAgree, -1, -1, 1);
Matrix.scaleM(mModelMatrix, 0, SCALE_RATE, SCALE_RATE, SCALE_RATE);
//计算MVP变换矩阵: mvpMatrix = projectionMatrix * viewMatrix * modelMatrix
float[] tempMatrix = new float[16];
Matrix.multiplyMM(tempMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
Matrix.multiplyMM(mMvpMatrix, 0, mProjectionMatrix, 0, tempMatrix, 0);
GLES30.glUniformMatrix4fv(mMvpMatrixHandle, 1, false, mMvpMatrix, 0);
}
private float[] getIdentityMatrix(int size, int offset) {
float[] matrix = new float[size];
Matrix.setIdentityM(matrix, offset);
return matrix;
}
}
?? ? ? ?ShaderUtils.java
package com.zhyan8.convexMirror.utils;
import android.content.res.Resources;
import android.opengl.GLES30;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShaderUtils {
//创建程序id
public static int createProgram(Resources resources, int vertexShaderResId, int fragmentShaderResId) {
final int vertexShaderId = compileShader(resources, GLES30.GL_VERTEX_SHADER, vertexShaderResId);
final int fragmentShaderId = compileShader(resources, GLES30.GL_FRAGMENT_SHADER, fragmentShaderResId);
return linkProgram(vertexShaderId, fragmentShaderId);
}
//通过外部资源编译着色器
private static int compileShader(Resources resources, int type, int shaderId){
String shaderCode = readShaderFromResource(resources, shaderId);
return compileShader(type, shaderCode);
}
//通过代码片段编译着色器
private static int compileShader(int type, String shaderCode){
int shader = GLES30.glCreateShader(type);
GLES30.glShaderSource(shader, shaderCode);
GLES30.glCompileShader(shader);
return shader;
}
//链接到着色器
private static 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 static String readShaderFromResource(Resources resources, int shaderId) {
InputStream is = resources.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();
}
}
? ? ? ??TextureUtils.java
package com.zhyan8.convexMirror.utils;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES30;
import android.opengl.GLUtils;
public class TextureUtils {
//加载纹理贴图
public static int loadTexture(Resources resources, int resourceId) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId, options);
final int[] textureIds = new int[1];
// 生成纹理id
GLES30.glGenTextures(1, textureIds, 0);
// 绑定纹理到OpenGL
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureIds[0]);
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, bitmap, 0);
// 生成MIP贴图
GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D);
// 取消绑定纹理
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
return textureIds[0];
}
}
? ? ? ??ArraysUtils.java
package com.zhyan8.convexMirror.utils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
public class ArraysUtils {
public static FloatBuffer getFloatBuffer(float[] floatArr) {
FloatBuffer fb = ByteBuffer.allocateDirect(floatArr.length * Float.BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
fb.put(floatArr);
fb.position(0);
return fb;
}
}
????????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;
}
? ? ? ??fragment_shader.glsl
#version 300 es
precision mediump float;
uniform sampler2D uTextureUnit;
in vec2 vTexCoord;
out vec4 fragColor;
void main() {
fragColor = texture(uTextureUnit,vTexCoord);
}
3 运行效果
???? ??? ??
|