m2b-ar-tp2/glarea.cpp
2021-10-06 19:49:42 +02:00

146 lines
2.7 KiB
C++

// Basé sur :
// CC-BY Edouard.Thiel@univ-amu.fr - 22/01/2019
#include "glarea.h"
#include <QDebug>
#include <QSurfaceFormat>
#include <QMatrix4x4>
GLArea::GLArea(QWidget *parent) :
QOpenGLWidget(parent)
{
QSurfaceFormat sf;
sf.setDepthBufferSize(24);
sf.setSamples(16);
setFormat(sf);
setEnabled(true); // événements clavier et souris
setFocusPolicy(Qt::StrongFocus); // accepte focus
setFocus(); // donne le focus
}
GLArea::~GLArea()
{
makeCurrent();
doneCurrent();
}
void GLArea::initializeGL()
{
initializeOpenGLFunctions();
glClearColor(0.5f,0.5f,1.0f,1.0f);
glEnable(GL_DEPTH_TEST);
emit onInit((QOpenGLExtraFunctions *) this);
}
void GLArea::resizeGL(int w, int h)
{
glViewport(0, 0, w, h);
windowRatio = float(w) / h;
}
void GLArea::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Matrice de projection
QMatrix4x4 projectionMatrix;
projectionMatrix.perspective(45.0f, windowRatio, 1.0f, 1000.0f);
// Matrice de vue (caméra)
QMatrix4x4 viewMatrix;
viewMatrix.translate(xPos, yPos, zPos);
viewMatrix.rotate(xRot, 1, 0, 0);
viewMatrix.rotate(yRot, 0, 1, 0);
viewMatrix.rotate(zRot, 0, 0, 1);
emit onPaint((QOpenGLExtraFunctions *) this,
projectionMatrix,
viewMatrix);
}
void GLArea::keyPressEvent(QKeyEvent *ev)
{
float da = 1.0f;
switch(ev->key()) {
case Qt::Key_A :
xRot -= da;
update();
break;
case Qt::Key_Q :
xRot += da;
update();
break;
case Qt::Key_Z :
yRot -= da;
update();
break;
case Qt::Key_S :
yRot += da;
update();
break;
case Qt::Key_E :
zRot -= da;
update();
break;
case Qt::Key_D :
zRot += da;
update();
break;
}
}
void GLArea::keyReleaseEvent(QKeyEvent *ev)
{
qDebug() << __FUNCTION__ << ev->text();
}
void GLArea::mousePressEvent(QMouseEvent *ev)
{
lastPos = ev->pos();
}
void GLArea::mouseReleaseEvent(QMouseEvent *ev)
{
qDebug() << __FUNCTION__ << ev->x() << ev->y() << ev->button();
}
void GLArea::mouseMoveEvent(QMouseEvent *ev)
{
int dx = ev->x() - lastPos.x();
int dy = ev->y() - lastPos.y();
if (ev->buttons() & Qt::LeftButton) {
xRot += dy;
yRot += dx;
update();
} else if (ev->buttons() & Qt::RightButton) {
xPos += dx/10.0f;
yPos -= dy/10.0f;
update();
} else if (ev->buttons() & Qt::MidButton) {
xPos += dx/10.0f;
zPos += dy;
update();
}
lastPos = ev->pos();
}