Qt+OpenGL——索引绘制四边形

头文件

#ifndef GLWIDGET_H
#define GLWIDGET_H

#include <QOpenGLWidget>
#include <QOpenGLFunctions_4_5_Core>

#include <QOpenGLShaderProgram>

class GLWidget : public QOpenGLWidget,public QOpenGLFunctions_4_5_Core
{
    Q_OBJECT
public:
    explicit GLWidget(QWidget *parent=nullptr);
    ~GLWidget();

protected:

    void iniDatas();

    void initializeGL(); //初始化相关的操作全在这个函数中完成
    void resizeGL(int w,int h);
    void paintGL();
private:
    QOpenGLShaderProgram *m_pShaderProgram = nullptr;

};

#endif // GLWIDGET_H

源文件

#include "glwidget.h"
#include <QOpenGLBuffer>

#include <QDebug>


#define BUFFER_OFFSET(offset) ((void*)(offset))


GLuint VAO = -1;
GLWidget::GLWidget(QWidget *parent):
    QOpenGLWidget(parent)
{

}

GLWidget::~GLWidget()
{

}

void GLWidget::iniDatas()
{
    static const float triangle[]={
        -0.5f,-0.5f,0.0f,
        0.5f,-0.5f,0.0f,
        0.0f,0.5f,0.0f
    };

    static const 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 indices[] = {
        0,1,2,
        2,0,3
    };

    glGenVertexArrays(1,&VAO);
    glBindVertexArray(VAO);

    GLuint VBO;
    glGenBuffers(1,&VBO);
    glBindBuffer(GL_ARRAY_BUFFER,VBO);
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);
    glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(float) * 3,BUFFER_OFFSET(0));
    glEnableVertexAttribArray(0);

    GLuint EBO;
    glGenBuffers(1,&EBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_STATIC_DRAW);

    glBindVertexArray(0);//解绑
    glBindBuffer(GL_ARRAY_BUFFER,0);

    //    glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);//填充图,,默认
    //    glPolygonMode(GL_FRONT_AND_BACK,GL_POINT);//散点图
    glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);//线框图
}

void GLWidget::initializeGL()
{
    initializeOpenGLFunctions();

    m_pShaderProgram = new QOpenGLShaderProgram(this);
    m_pShaderProgram->addShaderFromSourceFile(QOpenGLShader::Vertex,":/shaders/vertext.vert");
    m_pShaderProgram->addShaderFromSourceFile(QOpenGLShader::Fragment,":/shaders/fragment.frag");
    m_pShaderProgram->link();
    m_pShaderProgram->bind();

    iniDatas();
}

void GLWidget::resizeGL(int w, int h)
{
    glViewport(0,0,w,h);
}

void GLWidget::paintGL()
{
    static const GLfloat color[] = {0.0f,0.0f,0.0f,1.0f};

    glClearBufferfv(GL_COLOR,0,color);

    if(VAO == -1){
        return;
    }

    glUseProgram(m_pShaderProgram->programId());
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0);
    glBindVertexArray(0);

    update();
}

着色器相关代码

1、顶点着色器

#version 450 core

layout(location=0) in vec3 aPos;
void main()
{
        gl_Position = vec4(aPos,1);
}

2、片元着色器

#version 450 core
out vec4 FragColor;

void main()
{
	FragColor = vec4(1.0f,0.5f,0.2f,1.0f);
}

对应效果:
在这里插入图片描述

相关推荐
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:白松林 返回首页