EBO(顶点索引缓冲区)
重新写一个shader程序:
shaderMode.vs
#version 430
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
in vec3 vPosition;
void main(void)
{
gl_Position=proj_matrix*mv_matrix*vec4(vPosition,1.0);
}
shaderModel.fs
#version 430
out vec4 color;
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
void main(void)
{
color =vec4(1.0,0.0,0.0,1.0) ;
}
myTest.h
#pragma once
#include "Camera.h"
class myTest : protected QOpenGLFunctions_4_3_Core
{
public:
myTest();
~myTest();
void init(QOpenGLShaderProgram* shaderProgram);
void draw(Camera camera);
private:
GLuint vPosition;
float cubeLocX=4.0, cubeLocY=0.0, cubeLocZ=-8.0;
GLuint mvLoc;
QMatrix4x4 mvMat;
QOpenGLVertexArrayObject vao;
QOpenGLBuffer vbo, ebo;
QOpenGLShaderProgram* shaderProgram;
};
myTest.cpp
#include "stdafx.h"
#include "myTest.h"
myTest::myTest():ebo(QOpenGLBuffer::IndexBuffer){
}
myTest::~myTest() {
vbo.destroy();
}
void myTest::init(QOpenGLShaderProgram* shaderProgram) {
initializeOpenGLFunctions();
this->shaderProgram = shaderProgram;
shaderProgram->bind();
GLfloat vertexPositions[] = {
-0.5,-0.5,-0.5,
-0.5,-0.5,0.5,
0.5,-0.5,0.5,
0.5,-0.5,-0.5,
-0.5,0.5,-0.5,
-0.5,0.5,0.5,
0.5,0.5,0.5,
0.5,0.5,-0.5,
};
GLuint triIndexs[] = { 0,2,1,
0,2,3,
2,5,1,
2,5,6,
2,7,3,
2,7,6,
0,5,1,
0,5,4,
4,6,5,
4,6,7,
0,7,4,
0,7,3 };
vao.create();
vbo.create();
ebo.create();
vao.bind();
vbo.bind();
vbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
vbo.allocate(vertexPositions, sizeof(vertexPositions));
vPosition = shaderProgram->attributeLocation("vPosition");
shaderProgram->setAttributeBuffer(vPosition, GL_FLOAT, 0, 3, sizeof(float) * 3);
glEnableVertexAttribArray(vPosition);
ebo.bind();
ebo.setUsagePattern(QOpenGLBuffer::StaticDraw);
ebo.allocate(triIndexs, sizeof(triIndexs));
vao.release();
shaderProgram->release();
}
void myTest::draw(Camera camera) {
shaderProgram->bind();
mvLoc = shaderProgram->uniformLocation("mv_matrix");
//构建视图矩阵
QMatrix4x4 m;
m.translate(cubeLocX, cubeLocY, cubeLocZ);
QMatrix4x4 v;
v.lookAt(QVector3D(camera.location.x, camera.location.y, camera.location.z),
QVector3D(camera.viewPoint.x, camera.viewPoint.y, camera.viewPoint.z),
QVector3D(camera.worldY.x, camera.worldY.y, camera.worldY.z));
mvMat = v * m;
shaderProgram->setUniformValue(mvLoc, mvMat);
vao.bind();
//glDrawArrays(GL_TRIANGLES, 0, 36);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
vao.release();
shaderProgram->release();
}
效果图:右边红色立方体是新画的
目录
VSC++2019+QT+OpenGL
QT+OpenGL一之绘制立方体(三角形图元)
QT+OpenGL二之纹理贴图
QT+OpenGL三之矩阵简解
QT+OpenGL四之相机的移动和旋转
QT+OpenGL五之绘制不同的模型(vao,vbo机制)
QT+OpenGL六之天空盒
QT+OpenGL七之使用EBO
QT+OPenGL八之模型准备
QT+OPenGL九之模型解码
QT+OPenGL十之光照模型
QT+OPenGL十一之漫反射和镜面反射贴图
QT+OPenGL十二之定向光
QT+OPenGL十三之真正的点光源和聚光灯
QT+OPenGL十四之多光源混合的问题
QT+OPenGL十五之深度缓冲区
QT+OPenGL十六之模板缓冲区
QT+OPenGL十七帧缓冲区(离屏渲染)
QT+OPenGL十八抗锯齿
QT+OPenGL十九镜面反射效率调整
QT+OPenGL二十Gamma校正