Polish code of some opengl examples

Change-Id: If24ae1845176fc525cf6a239a5079f4802f8df3f
Reviewed-by: Friedemann Kleint <Friedemann.Kleint@digia.com>
This commit is contained in:
hjk 2012-12-19 11:27:10 +01:00 committed by The Qt Project
parent 4eac2c4728
commit 0136252cb2
29 changed files with 182 additions and 255 deletions

View File

@ -38,10 +38,11 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "glwidget.h" #include "glwidget.h"
#include "helper.h" #include "helper.h"
#include <QTimer>
//! [0] //! [0]
GLWidget::GLWidget(Helper *helper, QWidget *parent) GLWidget::GLWidget(Helper *helper, QWidget *parent)
: QGLWidget(QGLFormat(QGL::SampleBuffers), parent), helper(helper) : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), helper(helper)

View File

@ -45,10 +45,6 @@
//! [0] //! [0]
class Helper; class Helper;
QT_BEGIN_NAMESPACE
class QPaintEvent;
class QWidget;
QT_END_NAMESPACE
class GLWidget : public QGLWidget class GLWidget : public QGLWidget
{ {

View File

@ -38,9 +38,12 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "helper.h" #include "helper.h"
#include <QPainter>
#include <QPaintEvent>
#include <QWidget>
//! [0] //! [0]
Helper::Helper() Helper::Helper()
{ {
@ -70,14 +73,15 @@ void Helper::paint(QPainter *painter, QPaintEvent *event, int elapsed)
painter->setPen(circlePen); painter->setPen(circlePen);
painter->rotate(elapsed * 0.030); painter->rotate(elapsed * 0.030);
qreal r = elapsed/1000.0; qreal r = elapsed / 1000.0;
int n = 30; int n = 30;
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {
painter->rotate(30); painter->rotate(30);
qreal radius = 0 + 120.0*((i+r)/n); qreal factor = (i + r) / n;
qreal circleRadius = 1 + ((i+r)/n)*20; qreal radius = 0 + 120.0 * factor;
qreal circleRadius = 1 + factor * 20;
painter->drawEllipse(QRectF(radius, -circleRadius, painter->drawEllipse(QRectF(radius, -circleRadius,
circleRadius*2, circleRadius*2)); circleRadius * 2, circleRadius * 2));
} }
painter->restore(); painter->restore();
//! [2] //! [2]
@ -85,6 +89,6 @@ void Helper::paint(QPainter *painter, QPaintEvent *event, int elapsed)
//! [3] //! [3]
painter->setPen(textPen); painter->setPen(textPen);
painter->setFont(textFont); painter->setFont(textFont);
painter->drawText(QRect(-50, -50, 100, 100), Qt::AlignCenter, "Qt"); painter->drawText(QRect(-50, -50, 100, 100), Qt::AlignCenter, QStringLiteral("Qt"));
} }
//! [3] //! [3]

View File

@ -44,11 +44,7 @@
#include <QBrush> #include <QBrush>
#include <QFont> #include <QFont>
#include <QPen> #include <QPen>
#include <QWidget>
QT_BEGIN_NAMESPACE
class QPainter;
class QPaintEvent;
QT_END_NAMESPACE
//! [0] //! [0]
class Helper class Helper

View File

@ -38,9 +38,10 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QApplication>
#include "window.h" #include "window.h"
#include <QApplication>
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
QApplication app(argc, argv); QApplication app(argc, argv);

View File

@ -38,10 +38,11 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "widget.h" #include "widget.h"
#include "helper.h" #include "helper.h"
#include <QPainter>
#include <QTimer>
//! [0] //! [0]
Widget::Widget(Helper *helper, QWidget *parent) Widget::Widget(Helper *helper, QWidget *parent)

View File

@ -45,9 +45,6 @@
//! [0] //! [0]
class Helper; class Helper;
QT_BEGIN_NAMESPACE
class QPaintEvent;
QT_END_NAMESPACE
class Widget : public QWidget class Widget : public QWidget
{ {

View File

@ -38,15 +38,19 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "glwidget.h" #include "glwidget.h"
#include "widget.h" #include "widget.h"
#include "window.h" #include "window.h"
#include <QGridLayout>
#include <QLabel>
#include <QTimer>
//! [0] //! [0]
Window::Window() Window::Window()
: QWidget()
{ {
setWindowTitle(tr("2D Painting on Native and OpenGL Widgets"));
Widget *native = new Widget(&helper, this); Widget *native = new Widget(&helper, this);
GLWidget *openGL = new GLWidget(&helper, this); GLWidget *openGL = new GLWidget(&helper, this);
QLabel *nativeLabel = new QLabel(tr("Native")); QLabel *nativeLabel = new QLabel(tr("Native"));
@ -65,7 +69,5 @@ Window::Window()
connect(timer, SIGNAL(timeout()), native, SLOT(animate())); connect(timer, SIGNAL(timeout()), native, SLOT(animate()));
connect(timer, SIGNAL(timeout()), openGL, SLOT(animate())); connect(timer, SIGNAL(timeout()), openGL, SLOT(animate()));
timer->start(50); timer->start(50);
setWindowTitle(tr("2D Painting on Native and OpenGL Widgets"));
} }
//! [0] //! [0]

View File

@ -41,14 +41,9 @@
#ifndef WINDOW_H #ifndef WINDOW_H
#define WINDOW_H #define WINDOW_H
#include <QWidget>
#include "helper.h" #include "helper.h"
QT_BEGIN_NAMESPACE #include <QWidget>
class QLabel;
class QWidget;
QT_END_NAMESPACE
//! [0] //! [0]
class Window : public QWidget class Window : public QWidget

View File

@ -49,14 +49,13 @@ struct VertexData
QVector2D texCoord; QVector2D texCoord;
}; };
GeometryEngine::GeometryEngine() : vboIds(new GLuint[2]) GeometryEngine::GeometryEngine()
{ {
} }
GeometryEngine::~GeometryEngine() GeometryEngine::~GeometryEngine()
{ {
glDeleteBuffers(2, vboIds); glDeleteBuffers(2, vboIds);
delete[] vboIds;
} }
void GeometryEngine::init() void GeometryEngine::init()

View File

@ -41,8 +41,8 @@
#ifndef GEOMETRYENGINE_H #ifndef GEOMETRYENGINE_H
#define GEOMETRYENGINE_H #define GEOMETRYENGINE_H
#include <QtOpenGL/QGLFunctions> #include <QGLFunctions>
#include <QtOpenGL/QGLShaderProgram> #include <QGLShaderProgram>
class GeometryEngine : protected QGLFunctions class GeometryEngine : protected QGLFunctions
{ {
@ -51,14 +51,12 @@ public:
virtual ~GeometryEngine(); virtual ~GeometryEngine();
void init(); void init();
void drawCubeGeometry(QGLShaderProgram *program); void drawCubeGeometry(QGLShaderProgram *program);
private: private:
void initCubeGeometry(); void initCubeGeometry();
GLuint *vboIds; GLuint vboIds[2];
}; };
#endif // GEOMETRYENGINE_H #endif // GEOMETRYENGINE_H

View File

@ -47,16 +47,15 @@
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
QApplication a(argc, argv); QApplication app(argc, argv);
a.setApplicationName("cube"); app.setApplicationName("cube");
a.setApplicationVersion("0.1"); app.setApplicationVersion("0.1");
#ifndef QT_NO_OPENGL #ifdef QT_NO_OPENGL
MainWidget w; MainWidget widget;
w.resize(640, 480); widget.show();
w.show();
#else #else
QLabel * notifyLabel = new QLabel("OpenGL Support required"); QLabel note("OpenGL Support required");
notifyLabel->show(); note.show();
#endif #endif
return a.exec(); return app.exec();
} }

View File

@ -40,39 +40,26 @@
#include "mainwidget.h" #include "mainwidget.h"
#include "geometryengine.h"
#include <QtOpenGL/QGLShaderProgram>
#include <QBasicTimer>
#include <QMouseEvent> #include <QMouseEvent>
#include <QDebug>
#include <math.h> #include <math.h>
#include <locale.h> #include <locale.h>
MainWidget::MainWidget(QWidget *parent) : MainWidget::MainWidget(QWidget *parent) :
QGLWidget(parent), QGLWidget(parent),
timer(new QBasicTimer),
program(new QGLShaderProgram),
geometries(new GeometryEngine),
angularSpeed(0) angularSpeed(0)
{ {
} }
MainWidget::~MainWidget() MainWidget::~MainWidget()
{ {
delete timer; timer = 0;
delete program; program = 0;
delete geometries; geometries = 0;
deleteTexture(texture); deleteTexture(texture);
} }
//! [0] //! [0]
void MainWidget::mousePressEvent(QMouseEvent *e) void MainWidget::mousePressEvent(QMouseEvent *e)
{ {
// Saving mouse press position // Save mouse press position
mousePressPosition = QVector2D(e->localPos()); mousePressPosition = QVector2D(e->localPos());
} }
@ -97,17 +84,15 @@ void MainWidget::mouseReleaseEvent(QMouseEvent *e)
//! [0] //! [0]
//! [1] //! [1]
void MainWidget::timerEvent(QTimerEvent *e) void MainWidget::timerEvent(QTimerEvent *)
{ {
Q_UNUSED(e);
// Decrease angular speed (friction) // Decrease angular speed (friction)
angularSpeed *= 0.99; angularSpeed *= 0.99;
// Stop rotation when speed goes below threshold // Stop rotation when speed goes below threshold
if (angularSpeed < 0.01) if (angularSpeed < 0.01) {
angularSpeed = 0.0; angularSpeed = 0.0;
else { } else {
// Update rotation // Update rotation
rotation = QQuaternion::fromAxisAndAngle(rotationAxis, angularSpeed) * rotation; rotation = QQuaternion::fromAxisAndAngle(rotationAxis, angularSpeed) * rotation;
@ -120,13 +105,8 @@ void MainWidget::timerEvent(QTimerEvent *e)
void MainWidget::initializeGL() void MainWidget::initializeGL()
{ {
initializeGLFunctions(); initializeGLFunctions();
qglClearColor(Qt::black); qglClearColor(Qt::black);
qDebug() << "Initializing shaders...";
initShaders(); initShaders();
qDebug() << "Initializing textures...";
initTextures(); initTextures();
//! [2] //! [2]
@ -137,33 +117,32 @@ void MainWidget::initializeGL()
glEnable(GL_CULL_FACE); glEnable(GL_CULL_FACE);
//! [2] //! [2]
qDebug() << "Initializing geometries..."; geometries.init();
geometries->init();
// using QBasicTimer because its faster that QTimer // Use QBasicTimer because its faster than QTimer
timer->start(12, this); timer.start(12, this);
} }
//! [3] //! [3]
void MainWidget::initShaders() void MainWidget::initShaders()
{ {
// Overriding system locale until shaders are compiled // Override system locale until shaders are compiled
setlocale(LC_NUMERIC, "C"); setlocale(LC_NUMERIC, "C");
// Compiling vertex shader // Compile vertex shader
if (!program->addShaderFromSourceFile(QGLShader::Vertex, ":/vshader.glsl")) if (!program.addShaderFromSourceFile(QGLShader::Vertex, ":/vshader.glsl"))
close(); close();
// Compiling fragment shader // Compile fragment shader
if (!program->addShaderFromSourceFile(QGLShader::Fragment, ":/fshader.glsl")) if (!program.addShaderFromSourceFile(QGLShader::Fragment, ":/fshader.glsl"))
close(); close();
// Linking shader pipeline // Link shader pipeline
if (!program->link()) if (!program.link())
close(); close();
// Binding shader pipeline for use // Bind shader pipeline for use
if (!program->bind()) if (!program.bind())
close(); close();
// Restore system locale // Restore system locale
@ -174,7 +153,7 @@ void MainWidget::initShaders()
//! [4] //! [4]
void MainWidget::initTextures() void MainWidget::initTextures()
{ {
// Loading cube.png // Load cube.png image
glEnable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
texture = bindTexture(QImage(":/cube.png")); texture = bindTexture(QImage(":/cube.png"));
@ -198,7 +177,7 @@ void MainWidget::resizeGL(int w, int h)
glViewport(0, 0, w, h); glViewport(0, 0, w, h);
// Calculate aspect ratio // Calculate aspect ratio
qreal aspect = (qreal)w / ((qreal)h?h:1); qreal aspect = qreal(w) / qreal(h ? h : 1);
// Set near plane to 3.0, far plane to 7.0, field of view 45 degrees // Set near plane to 3.0, far plane to 7.0, field of view 45 degrees
const qreal zNear = 3.0, zFar = 7.0, fov = 45.0; const qreal zNear = 3.0, zFar = 7.0, fov = 45.0;
@ -223,12 +202,12 @@ void MainWidget::paintGL()
matrix.rotate(rotation); matrix.rotate(rotation);
// Set modelview-projection matrix // Set modelview-projection matrix
program->setUniformValue("mvp_matrix", projection * matrix); program.setUniformValue("mvp_matrix", projection * matrix);
//! [6] //! [6]
// Using texture unit 0 which contains cube.png // Use texture unit 0 which contains cube.png
program->setUniformValue("texture", 0); program.setUniformValue("texture", 0);
// Draw cube geometry // Draw cube geometry
geometries->drawCubeGeometry(program); geometries.drawCubeGeometry(&program);
} }

View File

@ -41,30 +41,26 @@
#ifndef MAINWIDGET_H #ifndef MAINWIDGET_H
#define MAINWIDGET_H #define MAINWIDGET_H
#include <QtOpenGL/QGLWidget> #include "geometryengine.h"
#include <QtOpenGL/QGLFunctions>
#include <QGLWidget>
#include <QGLFunctions>
#include <QMatrix4x4> #include <QMatrix4x4>
#include <QQuaternion> #include <QQuaternion>
#include <QVector2D> #include <QVector2D>
#include <QBasicTimer>
#include <QGLShaderProgram>
QT_BEGIN_NAMESPACE
class QBasicTimer;
class QGLShaderProgram;
QT_END_NAMESPACE
class GeometryEngine; class GeometryEngine;
class MainWidget : public QGLWidget, protected QGLFunctions class MainWidget : public QGLWidget, protected QGLFunctions
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit MainWidget(QWidget *parent = 0); explicit MainWidget(QWidget *parent = 0);
virtual ~MainWidget(); ~MainWidget();
signals:
public slots:
protected: protected:
void mousePressEvent(QMouseEvent *e); void mousePressEvent(QMouseEvent *e);
@ -79,9 +75,9 @@ protected:
void initTextures(); void initTextures();
private: private:
QBasicTimer *timer; QBasicTimer timer;
QGLShaderProgram *program; QGLShaderProgram program;
GeometryEngine *geometries; GeometryEngine geometries;
GLuint texture; GLuint texture;

View File

@ -38,13 +38,13 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets> #include "glwidget.h"
#include <QtOpenGL>
#include <QMouseEvent>
#include <QTimer>
#include <math.h> #include <math.h>
#include "glwidget.h"
GLWidget::GLWidget(QWidget *parent) GLWidget::GLWidget(QWidget *parent)
: QGLWidget(parent) : QGLWidget(parent)
{ {
@ -191,44 +191,39 @@ GLuint GLWidget::makeGear(const GLfloat *reflectance, GLdouble innerRadius,
GLdouble r2 = outerRadius + toothSize / 2.0; GLdouble r2 = outerRadius + toothSize / 2.0;
GLdouble delta = (2.0 * Pi / toothCount) / 4.0; GLdouble delta = (2.0 * Pi / toothCount) / 4.0;
GLdouble z = thickness / 2.0; GLdouble z = thickness / 2.0;
int i, j;
glShadeModel(GL_FLAT); glShadeModel(GL_FLAT);
for (i = 0; i < 2; ++i) { for (int i = 0; i < 2; ++i) {
GLdouble sign = (i == 0) ? +1.0 : -1.0; GLdouble sign = (i == 0) ? +1.0 : -1.0;
glNormal3d(0.0, 0.0, sign); glNormal3d(0.0, 0.0, sign);
glBegin(GL_QUAD_STRIP); glBegin(GL_QUAD_STRIP);
for (j = 0; j <= toothCount; ++j) { for (int j = 0; j <= toothCount; ++j) {
GLdouble angle = 2.0 * Pi * j / toothCount; GLdouble angle = 2.0 * Pi * j / toothCount;
glVertex3d(r0 * cos(angle), r0 * sin(angle), sign * z); glVertex3d(r0 * cos(angle), r0 * sin(angle), sign * z);
glVertex3d(r1 * cos(angle), r1 * sin(angle), sign * z); glVertex3d(r1 * cos(angle), r1 * sin(angle), sign * z);
glVertex3d(r0 * cos(angle), r0 * sin(angle), sign * z); glVertex3d(r0 * cos(angle), r0 * sin(angle), sign * z);
glVertex3d(r1 * cos(angle + 3 * delta), r1 * sin(angle + 3 * delta), glVertex3d(r1 * cos(angle + 3 * delta), r1 * sin(angle + 3 * delta), sign * z);
sign * z);
} }
glEnd(); glEnd();
glBegin(GL_QUADS); glBegin(GL_QUADS);
for (j = 0; j < toothCount; ++j) { for (int j = 0; j < toothCount; ++j) {
GLdouble angle = 2.0 * Pi * j / toothCount; GLdouble angle = 2.0 * Pi * j / toothCount;
glVertex3d(r1 * cos(angle), r1 * sin(angle), sign * z); glVertex3d(r1 * cos(angle), r1 * sin(angle), sign * z);
glVertex3d(r2 * cos(angle + delta), r2 * sin(angle + delta), glVertex3d(r2 * cos(angle + delta), r2 * sin(angle + delta), sign * z);
sign * z); glVertex3d(r2 * cos(angle + 2 * delta), r2 * sin(angle + 2 * delta), sign * z);
glVertex3d(r2 * cos(angle + 2 * delta), r2 * sin(angle + 2 * delta), glVertex3d(r1 * cos(angle + 3 * delta), r1 * sin(angle + 3 * delta), sign * z);
sign * z);
glVertex3d(r1 * cos(angle + 3 * delta), r1 * sin(angle + 3 * delta),
sign * z);
} }
glEnd(); glEnd();
} }
glBegin(GL_QUAD_STRIP); glBegin(GL_QUAD_STRIP);
for (i = 0; i < toothCount; ++i) { for (int i = 0; i < toothCount; ++i) {
for (j = 0; j < 2; ++j) { for (int j = 0; j < 2; ++j) {
GLdouble angle = 2.0 * Pi * (i + (j / 2.0)) / toothCount; GLdouble angle = 2.0 * Pi * (i + j / 2.0) / toothCount;
GLdouble s1 = r1; GLdouble s1 = r1;
GLdouble s2 = r2; GLdouble s2 = r2;
if (j == 1) if (j == 1)
@ -251,7 +246,7 @@ GLuint GLWidget::makeGear(const GLfloat *reflectance, GLdouble innerRadius,
glShadeModel(GL_SMOOTH); glShadeModel(GL_SMOOTH);
glBegin(GL_QUAD_STRIP); glBegin(GL_QUAD_STRIP);
for (i = 0; i <= toothCount; ++i) { for (int i = 0; i <= toothCount; ++i) {
GLdouble angle = i * 2.0 * Pi / toothCount; GLdouble angle = i * 2.0 * Pi / toothCount;
glNormal3d(-cos(angle), -sin(angle), 0.0); glNormal3d(-cos(angle), -sin(angle), 0.0);
glVertex3d(r0 * cos(angle), r0 * sin(angle), +z); glVertex3d(r0 * cos(angle), r0 * sin(angle), +z);

View File

@ -94,4 +94,4 @@ private:
QPoint lastPos; QPoint lastPos;
}; };
#endif #endif // GLWIDGET_H

View File

@ -38,14 +38,14 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QApplication>
#include "mainwindow.h" #include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
QApplication app(argc, argv); QApplication app(argc, argv);
MainWindow mainWin; MainWindow window;
mainWin.show(); window.show();
return app.exec(); return app.exec();
} }

View File

@ -38,12 +38,11 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include <QtOpenGL>
#include "glwidget.h" #include "glwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include <QtWidgets>
MainWindow::MainWindow() MainWindow::MainWindow()
{ {
centralWidget = new QWidget; centralWidget = new QWidget;

View File

@ -44,12 +44,12 @@
#include <QMainWindow> #include <QMainWindow>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
class QAction;
class QLabel; class QLabel;
class QMenu; class QMenu;
class QScrollArea; class QScrollArea;
class QSlider; class QSlider;
QT_END_NAMESPACE QT_END_NAMESPACE
class GLWidget; class GLWidget;
class MainWindow : public QMainWindow class MainWindow : public QMainWindow
@ -91,4 +91,4 @@ private:
QAction *aboutQtAct; QAction *aboutQtAct;
}; };
#endif #endif // MAINWINDOW_H

View File

@ -41,9 +41,6 @@
#include "hellowindow.h" #include "hellowindow.h"
#include <QOpenGLContext> #include <QOpenGLContext>
#include <QTimer>
#include <qmath.h> #include <qmath.h>
Renderer::Renderer(const QSurfaceFormat &format, Renderer *share, QScreen *screen) Renderer::Renderer(const QSurfaceFormat &format, Renderer *share, QScreen *screen)
@ -77,10 +74,8 @@ HelloWindow::HelloWindow(const QSharedPointer<Renderer> &renderer)
updateColor(); updateColor();
} }
void HelloWindow::exposeEvent(QExposeEvent *event) void HelloWindow::exposeEvent(QExposeEvent *)
{ {
Q_UNUSED(event);
render(); render();
if (!m_timer) { if (!m_timer) {
@ -109,10 +104,7 @@ void HelloWindow::updateColor()
}; };
m_color = colors[m_colorIndex]; m_color = colors[m_colorIndex];
m_colorIndex = 1 - m_colorIndex;
m_colorIndex++;
if (m_colorIndex >= int(sizeof(colors) / sizeof(colors[0])))
m_colorIndex = 0;
} }
void Renderer::render(QSurface *surface, const QColor &color, const QSize &viewSize) void Renderer::render(QSurface *surface, const QColor &color, const QSize &viewSize)
@ -171,31 +163,29 @@ void Renderer::initialize()
glClearColor(0.1f, 0.1f, 0.2f, 1.0f); glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this); QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
const char *vsrc = vshader->compileSourceCode(
"attribute highp vec4 vertex;\n" "attribute highp vec4 vertex;"
"attribute mediump vec3 normal;\n" "attribute mediump vec3 normal;"
"uniform mediump mat4 matrix;\n" "uniform mediump mat4 matrix;"
"uniform lowp vec4 sourceColor;\n" "uniform lowp vec4 sourceColor;"
"varying mediump vec4 color;\n" "varying mediump vec4 color;"
"void main(void)\n" "void main(void)"
"{\n" "{"
" vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));\n" " vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));"
" float angle = max(dot(normal, toLight), 0.0);\n" " float angle = max(dot(normal, toLight), 0.0);"
" vec3 col = sourceColor.rgb;\n" " vec3 col = sourceColor.rgb;"
" color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);\n" " color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);"
" color = clamp(color, 0.0, 1.0);\n" " color = clamp(color, 0.0, 1.0);"
" gl_Position = matrix * vertex;\n" " gl_Position = matrix * vertex;"
"}\n"; "}");
vshader->compileSourceCode(vsrc);
QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this); QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
const char *fsrc = fshader->compileSourceCode(
"varying mediump vec4 color;\n" "varying mediump vec4 color;"
"void main(void)\n" "void main(void)"
"{\n" "{"
" gl_FragColor = color;\n" " gl_FragColor = color;"
"}\n"; "}");
fshader->compileSourceCode(fsrc);
m_program = new QOpenGLShaderProgram(this); m_program = new QOpenGLShaderProgram(this);
m_program->addShader(vshader); m_program->addShader(vshader);

View File

@ -40,21 +40,15 @@
#include <QWindow> #include <QWindow>
#include <QtGui/qopengl.h>
#include <QtGui/qopenglshaderprogram.h>
#include <QColor> #include <QColor>
#include <QTime> #include <QOpenGLShaderProgram>
#include <QSharedPointer> #include <QSharedPointer>
#include <QTimer>
QT_BEGIN_NAMESPACE
class QOpenGLContext;
class QTimer;
QT_END_NAMESPACE
class Renderer : public QObject class Renderer : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit Renderer(const QSurfaceFormat &format, Renderer *share = 0, QScreen *screen = 0); explicit Renderer(const QSurfaceFormat &format, Renderer *share = 0, QScreen *screen = 0);
@ -89,6 +83,7 @@ private:
class HelloWindow : public QWindow class HelloWindow : public QWindow
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit HelloWindow(const QSharedPointer<Renderer> &renderer); explicit HelloWindow(const QSharedPointer<Renderer> &renderer);

View File

@ -38,21 +38,22 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QGuiApplication> #include "hellowindow.h"
#include <qpa/qplatformintegration.h> #include <qpa/qplatformintegration.h>
#include <private/qguiapplication_p.h> #include <private/qguiapplication_p.h>
#include <QGuiApplication>
#include <QScreen> #include <QScreen>
#include <QThread> #include <QThread>
#include "hellowindow.h" int main(int argc, char *argv[])
int main(int argc, char **argv)
{ {
QGuiApplication app(argc, argv); QGuiApplication app(argc, argv);
const bool multipleWindows = const bool multipleWindows =
QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL) QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL)
&& !QGuiApplication::arguments().contains(QLatin1String("--single")); && !QGuiApplication::arguments().contains(QStringLiteral("--single"));
QScreen *screen = QGuiApplication::primaryScreen(); QScreen *screen = QGuiApplication::primaryScreen();
@ -71,7 +72,7 @@ int main(int argc, char **argv)
HelloWindow *windowA = new HelloWindow(rendererA); HelloWindow *windowA = new HelloWindow(rendererA);
windowA->setGeometry(QRect(center, windowSize).translated(-windowSize.width() - delta / 2, 0)); windowA->setGeometry(QRect(center, windowSize).translated(-windowSize.width() - delta / 2, 0));
windowA->setTitle(QLatin1String("Thread A - Context A")); windowA->setTitle(QStringLiteral("Thread A - Context A"));
windowA->setVisible(true); windowA->setVisible(true);
windows.prepend(windowA); windows.prepend(windowA);
@ -85,13 +86,13 @@ int main(int argc, char **argv)
HelloWindow *windowB = new HelloWindow(rendererA); HelloWindow *windowB = new HelloWindow(rendererA);
windowB->setGeometry(QRect(center, windowSize).translated(delta / 2, 0)); windowB->setGeometry(QRect(center, windowSize).translated(delta / 2, 0));
windowB->setTitle(QLatin1String("Thread A - Context A")); windowB->setTitle(QStringLiteral("Thread A - Context A"));
windowB->setVisible(true); windowB->setVisible(true);
windows.prepend(windowB); windows.prepend(windowB);
HelloWindow *windowC = new HelloWindow(rendererB); HelloWindow *windowC = new HelloWindow(rendererB);
windowC->setGeometry(QRect(center, windowSize).translated(-windowSize.width() / 2, windowSize.height() + delta)); windowC->setGeometry(QRect(center, windowSize).translated(-windowSize.width() / 2, windowSize.height() + delta));
windowC->setTitle(QLatin1String("Thread B - Context B")); windowC->setTitle(QStringLiteral("Thread B - Context B"));
windowC->setVisible(true); windowC->setVisible(true);
windows.prepend(windowC); windows.prepend(windowC);
@ -113,7 +114,7 @@ int main(int argc, char **argv)
window->setGeometry(QRect(center, windowSize).translated(-windowSize.width() / 2, -windowSize.height() / 2)); window->setGeometry(QRect(center, windowSize).translated(-windowSize.width() / 2, -windowSize.height() / 2));
QChar id = QChar('B' + i); QChar id = QChar('B' + i);
window->setTitle(QLatin1String("Thread ") + id + QLatin1String(" - Context ") + id); window->setTitle(QStringLiteral("Thread ") + id + QStringLiteral(" - Context ") + id);
window->setVisible(true); window->setVisible(true);
windows.prepend(window); windows.prepend(window);
} }
@ -128,6 +129,7 @@ int main(int argc, char **argv)
for (int i = 0; i < renderThreads.size(); ++i) for (int i = 0; i < renderThreads.size(); ++i)
renderThreads.at(i)->wait(); renderThreads.at(i)->wait();
qDeleteAll(windows); qDeleteAll(windows);
qDeleteAll(renderThreads); qDeleteAll(renderThreads);

View File

@ -38,8 +38,6 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "bubble.h" #include "bubble.h"
Bubble::Bubble(const QPointF &position, qreal radius, const QPointF &velocity) Bubble::Bubble(const QPointF &position, qreal radius, const QPointF &velocity)

View File

@ -41,15 +41,7 @@
#ifndef BUBBLE_H #ifndef BUBBLE_H
#define BUBBLE_H #define BUBBLE_H
#include <QBrush> #include <QPainter>
#include <QColor>
#include <QPointF>
#include <QRect>
#include <QRectF>
QT_BEGIN_NAMESPACE
class QPainter;
QT_END_NAMESPACE
class Bubble class Bubble
{ {
@ -72,4 +64,4 @@ private:
QColor outerColor; QColor outerColor;
}; };
#endif #endif // BUBBLE_H

View File

@ -38,16 +38,16 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include <QtOpenGL>
#include <stdlib.h>
#include <math.h>
#include "bubble.h" #include "bubble.h"
#include "qtlogo.h" #include "qtlogo.h"
#include "glwidget.h" #include "glwidget.h"
#include <QMouseEvent>
#include <QTime>
#include <math.h>
#include <stdlib.h>
#ifndef GL_MULTISAMPLE #ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE 0x809D #define GL_MULTISAMPLE 0x809D
#endif #endif

View File

@ -41,19 +41,11 @@
#ifndef GLWIDGET_H #ifndef GLWIDGET_H
#define GLWIDGET_H #define GLWIDGET_H
#include <QBrush>
#include <QFont>
#include <QImage>
#include <QPen>
#include <QGLWidget> #include <QGLWidget>
#include <QTimer> #include <QTimer>
class Bubble; class Bubble;
class QtLogo; class QtLogo;
QT_BEGIN_NAMESPACE
class QPaintEvent;
class QWidget;
QT_END_NAMESPACE
//! [0] //! [0]
class GLWidget : public QGLWidget class GLWidget : public QGLWidget
@ -108,4 +100,4 @@ private:
//! [4] //! [4]
}; };
#endif #endif // GLWIDGET_H

View File

@ -38,9 +38,10 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QApplication>
#include "glwidget.h" #include "glwidget.h"
#include <QApplication>
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
QApplication app(argc, argv); QApplication app(argc, argv);

View File

@ -1,10 +1,12 @@
QT += opengl widgets
VPATH += ../shared VPATH += ../shared
INCLUDEPATH += ../shared INCLUDEPATH += ../shared
QT += opengl widgets
HEADERS = bubble.h \ HEADERS = bubble.h \
glwidget.h \ glwidget.h \
qtlogo.h qtlogo.h
SOURCES = bubble.cpp \ SOURCES = bubble.cpp \
glwidget.cpp \ glwidget.cpp \
main.cpp \ main.cpp \

View File

@ -38,14 +38,14 @@
** **
****************************************************************************/ ****************************************************************************/
#include "qtlogo.h"
#include <QGLWidget> #include <QGLWidget>
#include <QMatrix4x4> #include <QMatrix4x4>
#include <QVector3D> #include <QVector3D>
#include <qmath.h> #include <qmath.h>
#include "qtlogo.h"
static const qreal tee_height = 0.311126; static const qreal tee_height = 0.311126;
static const qreal cross_width = 0.25; static const qreal cross_width = 0.25;
static const qreal bar_thickness = 0.113137; static const qreal bar_thickness = 0.113137;
@ -117,7 +117,7 @@ void Geometry::finalize()
void Geometry::appendSmooth(const QVector3D &a, const QVector3D &n, int from) void Geometry::appendSmooth(const QVector3D &a, const QVector3D &n, int from)
{ {
// Smooth normals are acheived by averaging the normals for faces meeting // Smooth normals are achieved by averaging the normals for faces meeting
// at a point. First find the point in geometry already generated // at a point. First find the point in geometry already generated
// (working backwards, since most often the points shared are between faces // (working backwards, since most often the points shared are between faces
// recently added). // recently added).
@ -125,28 +125,27 @@ void Geometry::appendSmooth(const QVector3D &a, const QVector3D &n, int from)
for ( ; v >= from; --v) for ( ; v >= from; --v)
if (qFuzzyCompare(vertices[v], a)) if (qFuzzyCompare(vertices[v], a))
break; break;
if (v < from)
{ if (v < from) {
// The vert was not found so add it as a new one, and initialize // The vertex was not found so add it as a new one, and initialize
// its corresponding normal // its corresponding normal
v = vertices.count(); v = vertices.count();
vertices.append(a); vertices.append(a);
normals.append(n); normals.append(n);
} } else {
else
{
// Vert found, accumulate normals into corresponding normal slot. // Vert found, accumulate normals into corresponding normal slot.
// Must call finalize once finished accumulating normals // Must call finalize once finished accumulating normals
normals[v] += n; normals[v] += n;
} }
// In both cases (found or not) reference the vert via its index
// In both cases (found or not) reference the vertex via its index
faces.append(v); faces.append(v);
} }
void Geometry::appendFaceted(const QVector3D &a, const QVector3D &n) void Geometry::appendFaceted(const QVector3D &a, const QVector3D &n)
{ {
// Faceted normals are achieved by duplicating the vert for every // Faceted normals are achieved by duplicating the vertex for every
// normal, so that faces meeting at a vert get a sharp edge. // normal, so that faces meeting at a vertex get a sharp edge.
int v = vertices.count(); int v = vertices.count();
vertices.append(a); vertices.append(a);
normals.append(n); normals.append(n);
@ -189,32 +188,29 @@ void Patch::draw() const
void Patch::addTri(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &n) void Patch::addTri(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &n)
{ {
QVector3D norm = n.isNull() ? QVector3D::normal(a, b, c) : n; QVector3D norm = n.isNull() ? QVector3D::normal(a, b, c) : n;
if (sm == Smooth)
{ if (sm == Smooth) {
geom->appendSmooth(a, norm, initv); geom->appendSmooth(a, norm, initv);
geom->appendSmooth(b, norm, initv); geom->appendSmooth(b, norm, initv);
geom->appendSmooth(c, norm, initv); geom->appendSmooth(c, norm, initv);
} } else {
else
{
geom->appendFaceted(a, norm); geom->appendFaceted(a, norm);
geom->appendFaceted(b, norm); geom->appendFaceted(b, norm);
geom->appendFaceted(c, norm); geom->appendFaceted(c, norm);
} }
count += 3; count += 3;
} }
void Patch::addQuad(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &d) void Patch::addQuad(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &d)
{ {
QVector3D norm = QVector3D::normal(a, b, c); QVector3D norm = QVector3D::normal(a, b, c);
if (sm == Smooth)
{ if (sm == Smooth) {
addTri(a, b, c, norm); addTri(a, b, c, norm);
addTri(a, c, d, norm); addTri(a, c, d, norm);
} } else {
else // If faceted share the two common vertices
{
// If faceted share the two common verts
addTri(a, b, c, norm); addTri(a, b, c, norm);
int k = geom->vertices.count(); int k = geom->vertices.count();
geom->appendSmooth(a, norm, k); geom->appendSmooth(a, norm, k);
@ -224,9 +220,9 @@ void Patch::addQuad(const QVector3D &a, const QVector3D &b, const QVector3D &c,
} }
} }
static inline QVector<QVector3D> extrude(const QVector<QVector3D> &verts, qreal depth) static inline QVector<QVector3D> extrude(const QVector<QVector3D> &vertices, qreal depth)
{ {
QVector<QVector3D> extr = verts; QVector<QVector3D> extr = vertices;
for (int v = 0; v < extr.count(); ++v) for (int v = 0; v < extr.count(); ++v)
extr[v].setZ(extr[v].z() - depth); extr[v].setZ(extr[v].z() - depth);
return extr; return extr;
@ -240,6 +236,7 @@ public:
for (int i = 0; i < parts.count(); ++i) for (int i = 0; i < parts.count(); ++i)
parts[i]->translate(t); parts[i]->translate(t);
} }
void rotate(qreal deg, QVector3D axis) void rotate(qreal deg, QVector3D axis)
{ {
for (int i = 0; i < parts.count(); ++i) for (int i = 0; i < parts.count(); ++i)
@ -248,7 +245,7 @@ public:
// No special Rectoid destructor - the parts are fetched out of this member // No special Rectoid destructor - the parts are fetched out of this member
// variable, and destroyed by the new owner // variable, and destroyed by the new owner
QList<Patch*> parts; QList<Patch *> parts;
}; };
class RectPrism : public Rectoid class RectPrism : public Rectoid