1 前言

​ 纹理贴图是指:将图片贴在模型的表面。

​ 纹理贴图的本质是:将图片划分为一系列三角形,使得图片顶点序列模型顶点序列中的顶点一一对应,对于模型中任意三角形内部的坐标和图片中对应三角形内部的坐标,可以通过插值,建立一一对应关系,模型中任意位置的颜色由其对应的图片位置的颜色填充。

​ 本文完整代码资源见→【OpenGL ES】纹理贴图

​ 项目目录如下:

2 案例

​ MainActivity.java

package com.zhyan8.texture;

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.texture;

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.texture;

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 FloatBuffer vertexBuffer;
private FloatBuffer textureBuffer;
private MyGLUtils mGLUtils;
private float[] mvpMatrix = new float[16];
private int mvpMatrixLocation;
private int mTextureId; public MyRender(Context context) {
mGLUtils = new MyGLUtils(context);
getFloatBuffer();
} @Override
public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig) {
//设置背景颜色
GLES30.glClearColor(0.1f, 0.2f, 0.3f, 0.4f);
//编译着色器
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);
//链接程序片段
int programId = mGLUtils.linkProgram(vertexShaderId, fragmentShaderId);
GLES30.glUseProgram(programId);
mvpMatrixLocation = GLES30.glGetUniformLocation(programId, "mvpMatrix");
mTextureId = mGLUtils.loadTexture(R.raw.xxx);
} @Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
//设置视图窗口
GLES30.glViewport(0, 0, width, height);
mGLUtils.transform(width, height, mvpMatrix);
} @Override
public void onDrawFrame(GL10 gl) {
//将颜色缓冲区设置为预设的颜色
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
GLES30.glUniformMatrix4fv(mvpMatrixLocation, 1, false, mvpMatrix, 0);
//启用顶点的数组句柄
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);
//绑定纹理
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mTextureId);
//绘制贴图
GLES30.glDrawArrays(GLES30.GL_TRIANGLE_FAN, 0, 4);
//禁止顶点数组句柄
GLES30.glDisableVertexAttribArray(0);
GLES30.glDisableVertexAttribArray(1);
} private void getFloatBuffer() {
float[] vertex = new float[] {
1f, 1f, 0f, //V0
-1f, 1f, 0f, //V1
-1f, -1f, 0f, //V2
1f, -1f, 0f //V3
};
float[] texture = {
1f, 0f, //V0
0f, 0f, //V1
0f, 1.0f, //V2
1f, 1.0f //V3
};
vertexBuffer = mGLUtils.getFloatBuffer(vertex);
textureBuffer = mGLUtils.getFloatBuffer(texture);
}
}

​ MyGLUtils.java

package com.zhyan8.texture;

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 Bitmap mBitmap; 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 resourceId) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
mBitmap = BitmapFactory.decodeResource(mContext.getResources(), 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, mBitmap, 0);
// 生成MIP贴图
GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D);
// 取消绑定纹理
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
return textureIds[0];
} //调整图片宽高适配屏幕尺寸
public void transform(int width, int height, float[] matrix) {
int mapWidth = mBitmap.getWidth();
int mapHeight = mBitmap.getHeight();
float mapRatio = mapWidth / (float)mapHeight;
float ratio = width / (float)height;
float w = 1.0f;
float h = 1.0f;
if (mapRatio > ratio) { //宽度最大,高度适配
h = mapRatio / ratio;
} else { //高度最大,宽度适配
w = ratio / mapRatio;
}
Matrix.orthoM(matrix, 0, -w, w, -h, h,-1, 1);
}
}

​ vertex_shader.glsl

#version 300 es
layout (location = 0) in vec4 aPosition;
layout (location = 1) in vec2 aTextureCoord;
uniform mat4 mvpMatrix;
out vec2 vTexCoord;
void main() {
gl_Position = mvpMatrix * aPosition;
vTexCoord = aTextureCoord;
} //attribute vec4 aPosition;
//attribute vec2 aTextureCoord;
//uniform mat4 mvpMatrix;
//varying vec2 vTexCoord;
//void main() {
// gl_Position = mvpMatrix * aPosition;
// 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);
} //precision mediump float;
//uniform sampler2D uTextureUnit;
//varying vec2 vTexCoord;
//void main() {
// gl_FragColor = texture2D(uTextureUnit, vTexCoord);
//}

​ 片元着色器的作用:处理经光栅化阶段生成的每个片元,计算每个像素的颜色和透明度。

​ 在片元着色器中,浮点值没有默认的精度值,每个着色器必须声明一个默认的 float 精度。

运行结果:

​ 声明:本文转自【OpenGL ES】纹理贴图

【OpenGL ES】纹理贴图的更多相关文章

  1. Android OpenGL ES 开发(九): OpenGL ES 纹理贴图

    一.概念 一般说来,纹理是表示物体表面的一幅或几幅二维图形,也称纹理贴图(texture).当把纹理按照特定的方式映射到物体表面上的时候,能使物体看上去更加真实.当前流行的图形系统中,纹理绘制已经成为 ...

  2. android ndk调用OpenGL 实现纹理贴图Texture

    android ndk调用OpenGL 实现纹理贴图Texture 时间 2014-06-25 05:24:39  CSDN博客 原文  http://blog.csdn.net/chrisfxs/a ...

  3. OpenGL ES: 纹理采样 texture sample

    Sampler (GLSL) Sampler通常是在Fragment shader(片元着色器)内定义的,这是一个uniform类型的变量,即处理不同的片元时这个变量是一致不变的.一个sampler和 ...

  4. 一文详解 OpenGL ES 纹理颜色混合

    在OpenGL中绘制的时候,有时候想使新画的颜色和已经有的颜色按照一定的方式进行混合.例如:想使物体拥有半透明的效果,或者绘制叠加光亮的效果,这时候就需要用到OpenGLES混合. 如上图所示,为石头 ...

  5. opengl学习笔记(四):openCV读入图片,openGL实现纹理贴图

    在opengl中实现三维物体的纹理贴图的第一步就是要读入图片,然后指定该图片为纹理图片. 首先利用opencv的cvLoadImage函数把图像读入到内存中 img = cvLoadImage(); ...

  6. OpenGL之纹理贴图(Texture)

    学习自: https://learnopengl-cn.github.io/01%20Getting%20started/06%20Textures/ 先上一波效果图: 实际上就是:画了一个矩形,然后 ...

  7. OpenGL(二十二) gluBuild2DMipmaps 加载Mip纹理贴图

    当纹理被用于渲染一个面积比它本身小很多的对象时,会由于纹理图像的降采样率不足而导致混叠现象,主要的表现特征是纹理图像的闪烁,出现纹理躁动.特别是在场景远近移动变换时,这种闪烁情况更为明显,严重可能会影 ...

  8. TextureView+SurfaceTexture+OpenGL ES来播放视频(三)

    引自:http://www.jianshu.com/p/291ff6ddc164 做好的Demo截图 opengl-video 前言 讲了这么多,可能有人要问了,播放视频用个android封装的Vid ...

  9. Android OpenGL ES 开发

    OpenGL(Open Graphics Library) 是开放图形库,是一个跨平台的图形 API.OpenGL ES(OpenGL for Embedded System)是专为移动端提供的一个子 ...

  10. OpenGL ES着色器语言之变量和数据类型(一)(官方文档第四章)和varying,uniform,attribute修饰范围

    OpenGL ES着色器语言之变量和数据类型(一)(官方文档第四章)   所有变量和函数在使用前必须声明.变量和函数名是标识符. 没有默认类型,所有变量和函数声明必须包含一个声明类型以及可选的修饰符. ...

随机推荐

  1. [转帖]oracle 审计日志清理

    https://www.cnblogs.com/bangchen/p/7268086.html   --进入审计日志目录: cd $ORACLE_BASE/admin/$ORACLE_SID/adum ...

  2. [转帖] q命令-用SQL分析文本文件

    https://www.cnblogs.com/codelogs/p/16060830.html 简介# 在Linux上分析文本文件时,一般会使用到grep.sed.awk.sort.uniq等命令, ...

  3. [转帖]全球CPU市场格局(2022)

    https://www.eet-china.com/mp/a222817.html 本文选自"2022年国产服务器CPU研究框架",重点分析2022年CPU产业链.CPU市场规模. ...

  4. 【转帖】磁盘IOPS的计算

    计算磁盘IOPS的三个因素: 1.RAID类型的读写比 不同RAID类型的IOPS计算公式: RAID类型 公式 RAID5.RAID3 Drive IOPS=Read IOPS + 4*Write ...

  5. mysql8 initialize 命令 初学版 lower_case_table_names

    1. 今天开发找我跟我说 我安装的mysql 不对. 比较蛋疼.  需要修改一个参数 但是数据库已经初始进去了  重装起来比较麻烦. 硬着头皮搞. 2. 参数的名字为: lower_case_tabl ...

  6. Windows 2019 standard 安装 Sqlserver 2019 Standard 时报错 不知道如何处理

    Microsoft Windows [版本 10.0.17763.1] (c) 2018 Microsoft Corporation.保留所有权利. D:\>setup.exe Microsof ...

  7. Spring缓存是如何实现的?如何扩展使其支持过期删除功能?

    前言:在我们的应用中,有一些数据是通过rpc获取的远端数据,该数据不会经常变化,允许客户端在本地缓存一定时间. 该场景逻辑简单,缓存数据较小,不需要持久化,所以不希望引入其他第三方缓存工具加重应用负担 ...

  8. empty来显示暂无数据简直太好用,阻止用户复制文本user-select

    element-ui表格某一列无数据显示-- 很多时候,表格的某一列可能是没有数据的. 空着了不好看,ui小姐姐会说显示 -- 这个时候,小伙伴是怎么做的呢? 使用循环来判断是否为空,然后赋值为-- ...

  9. RN 动态渲染列表

    写在组件中 想要图片出来还应该给图片宽高哈!! alignItems: 'center', //水平居中 动态渲染列表 返回的是一个数组 网络图片的渲染方式 <Image source={{ur ...

  10. 将字符串变成数组split

    字符串变成数组,常用来获取数组中我们需要的值. var str="http://op/adfie/life.png"; let arr=str.split('.'); consol ...