初始化顶点和纹理
public voiid initVertexData(){
float vertices[] = {顶点数 * 3};//顶点坐标
float buffer1 = CreateBuffer(buffer1,vertices);
float texCoor[] = {对应顶点坐标 * 3};//纹理坐标
float buffer2 = CreateBuffer(buffer2,texCoor);
//...
}
private FloatBuffer CreateBuffer(FloatBuffer buffer, float[] vertices) {
//创建顶点坐标数据缓冲
//vertices.length*4是因为一个整数四个字节
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
buffer = vbb.asFloatBuffer();//转换为int型缓冲
buffer.put(vertices);//向缓冲区中放入顶点坐标数据
buffer.position(0);//设置缓冲区起始位置
return buffer;
}
初始化着色器
public void initShader() {
private final String vertexShaderCode =
"attribute vec4 vPosition;" +
"uniform mat4 vMatrix;"+
"void main() {" +
" gl_Position = vPosition;" +
"}";
private final String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";
//...
}
根据着色器创建程序
program = ShaderUtil.createProgram(m_mVertexShader, m_mFragmentShader);
获取着色器中参数引用
PositionHandle = GLES20.glGetAttribLocation(m_mProgram, "aPosition");
VideoHandle=GLES20.glGetUniformLocation(m_mProgram, "uTextureVideo");
//着色器中attribute修饰就用glGetAttribLocation
//着色器中uniform修饰就用glGetUniformLocation
private float[] mViewMatrix=new float[16];
private float[] mProjectMatrix=new float[16];
private float[] mMVPMatrix=new float[16];
//。。。
//。。。
//计算宽高比
float ratio=(float)width/height;
//设置透视投影
Matrix.frustumM(mProjectMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
//设置相机位置
Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 7.0f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
//计算变换矩阵
Matrix.multiplyMM(mMVPMatrix,0,mProjectMatrix,0,mViewMatrix,0);
加载程序,并启用顶点数据
GLES20.glUseProgram(program);
GLES20.glEnableVertexAttribArray(PositionHandle);
GLES20.glGetAttribLocation(mProgram, "vPosition");
GLES20.glGetUniformLocation(mProgram,"vMatrix");//。。。
//以attribute修饰的引用才需要启用
传入数据
GLES20.glVertexAttribPointer
(
m_maPositionHandle,//引用
3,
GLES20.GL_FLOAT,
false,
3 * 4, //每个顶点4个字节
m_mVertexBuffer //buffer
);
GLES20.glUniformMatrix4fv(
mMatrixHandler,
1,
false,
mMVPMatrix,
0);
GLES20.glUniform4fv( mColorHandle, 1, color, 0);
GLES20.glUniform1i(m_texIdVideoHandle, 1);
// 。。。
//attribute修饰的传入6个参数
//uniform修饰的传入2个参数,有时也不一定
绘制矩形
//顶点法
GLES20.glDrawArrays(
GLES20.GL_TRIANGLES,
0, m_vCount//顶点数量
);
//索引法
1、传入数据的所有方法