#include <QApplication>
#include <myglwidget.h>
#include <glut.h>
#include <QMatrix>
#include <QMouseEvent>
#include <QWheelEvent>
// 立方体的8个顶点坐标
float vertex_point[8][4]={0};
GLint index_list[][4] = {
0, 2, 3, 1,
0, 4, 6, 2,
0, 1, 5, 4,
4, 5, 7, 6,
1, 3, 7, 5,
2, 6, 7, 3,
};
GLfloat colors[][3] = { { 0.0, 0.0, 1.0 }, { 0.0, 1.0, 0.0 }, { 1.0, 0.0, 0.0 },
{ 1.0, 0.0, 1.0 }, { 1.0, 1.0, 0.0 }, { 0.0, 1.0, 1.0 }};
MyGLWidget::MyGLWidget(QWidget *parent) :
QGLWidget(parent),mScale(1)
{
showNormal();
}
MyGLWidget::~MyGLWidget()
{
}
void MyGLWidget::resizeGL(int width, int height)
{
if(height == 0)
height =1;
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,width/height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void MyGLWidget::initializeGL()
{
//行存储
up4ps.setRow(0,{-1.0f, -1.0f, -1.0f,1.0f});
up4ps.setRow(1,{1.0f, -1.0f, -1.0f,1.0f});
up4ps.setRow(2,{-1.0f, 1.0f, -1.0f,1.0f});
up4ps.setRow(3,{1.0f, 1.0f, -1.0f,1.0f});
down4ps.setRow(0,{-1.0f, -1.0f, 1.0f,1.0f});
down4ps.setRow(1,{1.0f, -1.0f, 1.0f,1.0f});
down4ps.setRow(2,{-1.0f, 1.0f, 1.0f,1.0f});
down4ps.setRow(3,{1.0f, 1.0f, 1.0f,1.0f});
glShadeModel(GL_SMOOTH);
glClearColor(1.0f,1.0f,1.0f,0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3,GL_FLOAT,0,vertex_point);
glColorPointer(3,GL_FLOAT,0,colors);
}
void MyGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0f,0.0f,-7.0f);
projection.rotate(rotation);
projection.scale(mScale);
int i = 0, j=0;
float *p;
p=(up4ps*projection).data();
for(i=0;i<4;i++){
for(j=0;j<4;j++,p++){
vertex_point[j][i]=*p;
}
}
p=(down4ps*projection).data();
for(i=0;i<4;i++){
for(j=0;j<4;j++,p++){
vertex_point[j+4][i]=*p;
}
}
glColor3f(0.0f, 1.0f, 0.0f);
glBegin(GL_QUADS); // 绘制四边形
for (i = 0; i < 6; ++i) // 有六个面,循环六次
{
glColor3f(colors[i][0], colors[i][1], colors[i][2]);
for (j = 0; j < 4; ++j) // 每个面有四个顶点,循环四次
{
glVertex3fv(vertex_point[index_list[i][j]]);
}
}
glEnd();
}
void MyGLWidget::timerEvent(QTimerEvent *)
{
updateGL();
}
void MyGLWidget::mousePressEvent(QMouseEvent *event)
{
mousePos = QVector2D(event->pos());
event->accept();
}
void MyGLWidget::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() == Qt::LeftButton)
{
QVector2D diff = QVector2D(event->pos()) - mousePos;
qreal angle =(diff.length())/3.6;
QVector3D rotationAxis = QVector3D(-diff.y(), -diff.x(), 0.0).normalized();
rotation = QQuaternion::fromAxisAndAngle(rotationAxis, angle);//* rotation;
this->update();
mousePos = QVector2D(event->pos());
}
event->accept();
}
void MyGLWidget::wheelEvent(QWheelEvent *event)
{
QPoint numDegrees = event->angleDelta() / 8;
if (numDegrees.y() > 0) {
mScale += 0.1f;
} else if (numDegrees.y() < 0) {
mScale -= 0.1f;
}
this->update();
}