#include "zlopenglwidget.h"
#include "qdebug.h"
#include "QOpenGLShader"
float vertices[] = {
0.5f,0.5f,0.0f,
0.5f,-0.5f,0.0f,
-0.5f,-0.5f,0.0f,
-0.5f,0.5f,0.0f
};
unsigned int indicesRect[]=
{
0,1,3,
1,2,3
};
unsigned int indicesTri[]=
{
0,1,3
};
const char *vertexShaderSource =
"#version 330 core \n"
"layout(location=0) in vec3 aPos;\n"
"void main()\n"
"{\n"
"gl_Position = vec4 (aPos.x,aPos.y,aPos.z,1.0f);\n"
"}\n\0";
const char *fragmentShaderSource =
"#version 330 core \n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4 (1.0f,0.5f,0.2f,1.0f);\n"
"}\n\0";
ZLOpenGLWidget::ZLOpenGLWidget(QWidget *parent)
:QOpenGLWidget(parent)
{
}
ZLOpenGLWidget::~ZLOpenGLWidget()
{
glDeleteVertexArrays(1,&VAO);
glDeleteBuffers(1,&VBO);
glDeleteBuffers(2,EBO);
}
void ZLOpenGLWidget::draw(int type)
{
auto f_clear=[&]()
{
glClearColor(0.2f,0.2f,0.3f,1.0f);
glClear(GL_COLOR_BUFFER_BIT);
};
auto f_Rect=[&]()
{
glClearColor(0.2f,0.2f,0.3f,1.0f);
glClear(GL_COLOR_BUFFER_BIT);
shaderProgram.bind();
glBindVertexArray(VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO[0]);
glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0);
};
auto f_Tri=[&]()
{
f_clear();
shaderProgram.bind();
glBindVertexArray(VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO[1]);
glDrawElements(GL_TRIANGLES,3,GL_UNSIGNED_INT,0);
};
makeCurrent();
switch(type)
{
case eClear:
f_clear();
break;
case eRect:
f_Rect();
break;
case eTri:
f_Tri();
break;
}
doneCurrent();
}
void ZLOpenGLWidget::initializeGL()
{
initializeOpenGLFunctions();
glGenVertexArrays(1,&VAO);
glGenBuffers(1,&VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER,VBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,3*sizeof(float),(void*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER,0);
glGenBuffers(2,EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO[0]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indicesRect),indicesRect,GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indicesTri),indicesTri,GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
QOpenGLShader* vertex = new QOpenGLShader(QOpenGLShader::Vertex);
vertex->compileSourceCode(vertexShaderSource) ;
QOpenGLShader* fragment = new QOpenGLShader(QOpenGLShader::Fragment);
fragment->compileSourceCode(fragmentShaderSource) ;
shaderProgram.addShader(vertex);
shaderProgram.addShader(fragment);
if(! shaderProgram.link())
{
qDebug()<<"Error"<<shaderProgram.log();
}
}
void ZLOpenGLWidget::resizeGL(int w, int h)
{
Q_UNUSED(w);
Q_UNUSED(h);
}
void ZLOpenGLWidget::paintGL()
{
}
|