-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathopenglwidget.cpp
More file actions
92 lines (72 loc) · 2.25 KB
/
openglwidget.cpp
File metadata and controls
92 lines (72 loc) · 2.25 KB
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
88
89
90
91
92
#include "openglwidget.h"
#include "assimp.h"
OpenGLWidget::OpenGLWidget(QWidget *parent)
: QOpenGLWidget(parent)
{
}
void OpenGLWidget::initializeGL()
{
initializeOpenGLFunctions();
glEnable(GL_DEPTH_TEST);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // 设置背景颜色
vao.create();
vbo.create();
auto vertices = Assimp::loadObj("monkey.obj");
vertexCount = vertices.size();
vbo.bind();
vbo.allocate(vertices.data(), vertices.size() * sizeof(vertices[0]));
vbo.release();
program.addShaderFromSourceFile(QOpenGLShader::Vertex, "orange.vert");
program.addShaderFromSourceFile(QOpenGLShader::Fragment, "orange.frag");
program.link();
}
void OpenGLWidget::resizeGL(int w, int h)
{
glViewport(0, 0, w, h);
camera.setAspect(w, h);
}
void OpenGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT); // 每帧都清空屏幕
qDebug() << "paintGL";
vao.bind();
vbo.bind();
program.bind();
program.setUniformValue("model", camera.model);
program.setUniformValue("view", camera.view);
program.setUniformValue("projection", camera.projection);
QVector3D lightDir(2, 3, 4);
lightDir.normalize();
program.setUniformValue("lightDir", lightDir);
program.setAttributeBuffer("position", GL_FLOAT,
offsetof(Assimp::Vertex, position), 3,
sizeof(Assimp::Vertex));
program.setAttributeBuffer("normal", GL_FLOAT,
offsetof(Assimp::Vertex, normal), 3,
sizeof(Assimp::Vertex));
program.enableAttributeArray("position");
program.enableAttributeArray("normal");
glDrawArrays(GL_TRIANGLES, 0, vertexCount);
program.release();
vbo.release();
vao.release();
}
void OpenGLWidget::mousePressEvent(QMouseEvent *event)
{
lastPos = event->pos();
}
void OpenGLWidget::mouseMoveEvent(QMouseEvent *event)
{
QPointF deltaPos = event->pos() - lastPos;
lastPos = event->pos();
camera.mouseMove(deltaPos.x() / width(), deltaPos.y() / height());
repaint();
}
void OpenGLWidget::mouseReleaseEvent(QMouseEvent *event)
{
}
void OpenGLWidget::wheelEvent(QWheelEvent *event)
{
camera.mouseWheel(event->angleDelta().y() / 120.0f);
repaint();
}