1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
// Add to .pro file:
// LIBS += -lopengl32
#ifdef _WIN32
#include <windows.h>
extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
extern "C" __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001;
#endif
#include <QApplication>
#include <QOpenGLWidget>
#include <QOpenGLShaderProgram>
#include <QOpenGLBuffer>
#include <QTimer>
#include <QMatrix4x4>
class Widget : public QOpenGLWidget {
Q_OBJECT
public:
Widget(QWidget *parent = nullptr) : QOpenGLWidget(parent) {
setWindowTitle("Qt5, OpenGL 3.3");
resize(268, 268);
}
private:
QOpenGLShaderProgram m_program;
QOpenGLBuffer m_vertPosBuffer;
QTimer m_timer;
QMatrix4x4 m_rotationMatrix;
void initializeGL() override {
glClearColor(0.5f, 0.8f, 0.7f, 1.f);
const char *vertShaderSrc =
"#version 330 core\n"
"in vec3 aPosition;"
"uniform mat4 uRotationMatrix;"
"void main()"
"{"
" gl_Position = uRotationMatrix * vec4(aPosition, 1.0);"
"}";
const char *fragShaderSrc =
"#version 330 core\n"
"out vec4 fragColor;"
"void main()"
"{"
" fragColor = vec4(0.5, 0.2, 0.9, 1.0);"
"}";
m_program.addShaderFromSourceCode(QOpenGLShader::Vertex, vertShaderSrc);
m_program.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShaderSrc);
m_program.link();
m_program.bind();
float vertPositions[] = {
-0.5f, -0.5f, 0.f,
0.5f, -0.5f, 0.f,
0.f, 0.5f, 0.f
};
m_vertPosBuffer.create();
m_vertPosBuffer.bind();
m_vertPosBuffer.allocate(vertPositions, sizeof(vertPositions));
m_program.bindAttributeLocation("aPosition", 0);
m_program.setAttributeBuffer(0, GL_FLOAT, 0, 3);
m_program.enableAttributeArray(0);
connect(&m_timer, &QTimer::timeout, this, &Widget::slotAnimate);
m_timer.start(1000.f/30.f);
}
void paintGL() override {
glClear(GL_COLOR_BUFFER_BIT);
m_program.bind();
m_program.setUniformValue("uRotationMatrix", m_rotationMatrix);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
void resizeGL(int w, int h) override {
glViewport(0, 0, w, h);
}
void slotAnimate() {
m_rotationMatrix.rotate(5.f, QVector3D(0.f, 0.f, 1.f));
update();
}
};
#include "main.moc"
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
|