summaryrefslogtreecommitdiffstats
path: root/tests/manual/examples
diff options
context:
space:
mode:
Diffstat (limited to 'tests/manual/examples')
-rw-r--r--tests/manual/examples/opengl/hellowindow/CMakeLists.txt39
-rw-r--r--tests/manual/examples/opengl/hellowindow/hellowindow.cpp305
-rw-r--r--tests/manual/examples/opengl/hellowindow/hellowindow.h77
-rw-r--r--tests/manual/examples/opengl/hellowindow/hellowindow.pro9
-rw-r--r--tests/manual/examples/opengl/hellowindow/main.cpp125
-rw-r--r--tests/manual/examples/opengl/qopenglwindow/CMakeLists.txt49
-rw-r--r--tests/manual/examples/opengl/qopenglwindow/background.frag30
-rw-r--r--tests/manual/examples/opengl/qopenglwindow/background_renderer.cpp167
-rw-r--r--tests/manual/examples/opengl/qopenglwindow/background_renderer.h46
-rw-r--r--tests/manual/examples/opengl/qopenglwindow/main.cpp154
-rw-r--r--tests/manual/examples/opengl/qopenglwindow/qopenglwindow.pro16
-rw-r--r--tests/manual/examples/opengl/qopenglwindow/shaders.qrc5
12 files changed, 1022 insertions, 0 deletions
diff --git a/tests/manual/examples/opengl/hellowindow/CMakeLists.txt b/tests/manual/examples/opengl/hellowindow/CMakeLists.txt
new file mode 100644
index 0000000000..551cf9faef
--- /dev/null
+++ b/tests/manual/examples/opengl/hellowindow/CMakeLists.txt
@@ -0,0 +1,39 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+cmake_minimum_required(VERSION 3.16)
+project(hellowindow LANGUAGES CXX)
+
+if(NOT DEFINED INSTALL_EXAMPLESDIR)
+ set(INSTALL_EXAMPLESDIR "examples")
+endif()
+
+set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/opengl/hellowindow")
+
+find_package(Qt6 REQUIRED COMPONENTS Core Gui OpenGL)
+
+qt_standard_project_setup()
+
+qt_add_executable(hellowindow
+ hellowindow.cpp hellowindow.h
+ main.cpp
+)
+
+set_target_properties(hellowindow PROPERTIES
+ WIN32_EXECUTABLE TRUE
+ MACOSX_BUNDLE TRUE
+)
+
+target_link_libraries(hellowindow PRIVATE
+ Qt6::Core
+ Qt6::CorePrivate
+ Qt6::Gui
+ Qt6::GuiPrivate
+ Qt6::OpenGL
+)
+
+install(TARGETS hellowindow
+ RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
+ BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
+ LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
+)
diff --git a/tests/manual/examples/opengl/hellowindow/hellowindow.cpp b/tests/manual/examples/opengl/hellowindow/hellowindow.cpp
new file mode 100644
index 0000000000..c9cad95563
--- /dev/null
+++ b/tests/manual/examples/opengl/hellowindow/hellowindow.cpp
@@ -0,0 +1,305 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include "hellowindow.h"
+
+#include <QOpenGLContext>
+#include <QOpenGLFunctions>
+#include <QRandomGenerator>
+#include <qmath.h>
+#include <QElapsedTimer>
+
+Renderer::Renderer(const QSurfaceFormat &format, Renderer *share, QScreen *screen)
+ : m_initialized(false)
+ , m_format(format)
+{
+ m_context = new QOpenGLContext(this);
+ if (screen)
+ m_context->setScreen(screen);
+ m_context->setFormat(format);
+ if (share)
+ m_context->setShareContext(share->m_context);
+ m_context->create();
+
+ m_backgroundColor = QColor::fromRgbF(0.1f, 0.1f, 0.2f, 1.0f);
+ m_backgroundColor.setRed(QRandomGenerator::global()->bounded(64));
+ m_backgroundColor.setGreen(QRandomGenerator::global()->bounded(128));
+ m_backgroundColor.setBlue(QRandomGenerator::global()->bounded(256));
+}
+
+HelloWindow::HelloWindow(const QSharedPointer<Renderer> &renderer, QScreen *screen)
+ : m_colorIndex(0), m_renderer(renderer)
+{
+ setSurfaceType(QWindow::OpenGLSurface);
+ setFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
+
+ setGeometry(QRect(10, 10, 640, 480));
+
+ setFormat(renderer->format());
+ if (screen)
+ setScreen(screen);
+
+ create();
+
+ updateColor();
+
+ connect(renderer.data(), &Renderer::requestUpdate, this, &QWindow::requestUpdate);
+}
+
+void HelloWindow::exposeEvent(QExposeEvent *)
+{
+ if (isExposed())
+ render();
+}
+
+bool HelloWindow::event(QEvent *ev)
+{
+ if (ev->type() == QEvent::UpdateRequest && isExposed())
+ render();
+ return QWindow::event(ev);
+}
+
+void HelloWindow::render()
+{
+ static QElapsedTimer timer;
+ if (!timer.isValid())
+ timer.start();
+ qreal a = (qreal)(((timer.elapsed() * 3) % 36000) / 100.0);
+ auto call = [this, r = m_renderer.data(), a, c = color()]() { r->render(this, a, c); };
+ QMetaObject::invokeMethod(m_renderer.data(), call);
+}
+
+void HelloWindow::mousePressEvent(QMouseEvent *)
+{
+ updateColor();
+}
+
+QColor HelloWindow::color() const
+{
+ return m_color;
+}
+
+void HelloWindow::updateColor()
+{
+ QColor colors[] =
+ {
+ QColor(100, 255, 0),
+ QColor(0, 100, 255)
+ };
+
+ m_color = colors[m_colorIndex];
+ m_colorIndex = 1 - m_colorIndex;
+}
+
+void Renderer::render(HelloWindow *surface, qreal angle, const QColor &color)
+{
+ if (!m_context->makeCurrent(surface))
+ return;
+
+ QSize viewSize = surface->size();
+
+ if (!m_initialized) {
+ initialize();
+ m_initialized = true;
+ }
+
+ QOpenGLFunctions *f = m_context->functions();
+ f->glViewport(0, 0, viewSize.width() * surface->devicePixelRatio(), viewSize.height() * surface->devicePixelRatio());
+ f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ f->glClearColor(m_backgroundColor.redF(), m_backgroundColor.greenF(), m_backgroundColor.blueF(), m_backgroundColor.alphaF());
+ f->glFrontFace(GL_CW);
+ f->glCullFace(GL_FRONT);
+ f->glEnable(GL_CULL_FACE);
+ f->glEnable(GL_DEPTH_TEST);
+
+ m_program->bind();
+ m_vbo.bind();
+
+ m_program->enableAttributeArray(vertexAttr);
+ m_program->enableAttributeArray(normalAttr);
+ m_program->setAttributeBuffer(vertexAttr, GL_FLOAT, 0, 3);
+ const int verticesSize = vertices.count() * 3 * sizeof(GLfloat);
+ m_program->setAttributeBuffer(normalAttr, GL_FLOAT, verticesSize, 3);
+
+ QMatrix4x4 modelview;
+ modelview.rotate(angle, 0.0f, 1.0f, 0.0f);
+ modelview.rotate(angle, 1.0f, 0.0f, 0.0f);
+ modelview.rotate(angle, 0.0f, 0.0f, 1.0f);
+ modelview.translate(0.0f, -0.2f, 0.0f);
+
+ m_program->setUniformValue(matrixUniform, modelview);
+ m_program->setUniformValue(colorUniform, color);
+
+ m_context->functions()->glDrawArrays(GL_TRIANGLES, 0, vertices.size());
+
+ m_context->swapBuffers(surface);
+
+ emit requestUpdate();
+}
+
+Q_GLOBAL_STATIC(QMutex, initMutex)
+
+void Renderer::initialize()
+{
+ // Threaded shader compilation can confuse some drivers. Avoid it.
+ QMutexLocker lock(initMutex());
+
+ QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
+ vshader->compileSourceCode(
+ "attribute highp vec4 vertex;"
+ "attribute mediump vec3 normal;"
+ "uniform mediump mat4 matrix;"
+ "uniform lowp vec4 sourceColor;"
+ "varying mediump vec4 color;"
+ "void main(void)"
+ "{"
+ " vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));"
+ " float angle = max(dot(normal, toLight), 0.0);"
+ " vec3 col = sourceColor.rgb;"
+ " color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);"
+ " color = clamp(color, 0.0, 1.0);"
+ " gl_Position = matrix * vertex;"
+ "}");
+
+ QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
+ fshader->compileSourceCode(
+ "varying mediump vec4 color;"
+ "void main(void)"
+ "{"
+ " gl_FragColor = color;"
+ "}");
+
+ m_program = new QOpenGLShaderProgram(this);
+ m_program->addShader(vshader);
+ m_program->addShader(fshader);
+ m_program->link();
+ m_program->bind();
+
+ vertexAttr = m_program->attributeLocation("vertex");
+ normalAttr = m_program->attributeLocation("normal");
+ matrixUniform = m_program->uniformLocation("matrix");
+ colorUniform = m_program->uniformLocation("sourceColor");
+
+ createGeometry();
+
+ m_vbo.create();
+ m_vbo.bind();
+ const int verticesSize = vertices.count() * 3 * sizeof(GLfloat);
+ m_vbo.allocate(verticesSize * 2);
+ m_vbo.write(0, vertices.constData(), verticesSize);
+ m_vbo.write(verticesSize, normals.constData(), verticesSize);
+}
+
+void Renderer::createGeometry()
+{
+ vertices.clear();
+ normals.clear();
+
+ qreal x1 = +0.06f;
+ qreal y1 = -0.14f;
+ qreal x2 = +0.14f;
+ qreal y2 = -0.06f;
+ qreal x3 = +0.08f;
+ qreal y3 = +0.00f;
+ qreal x4 = +0.30f;
+ qreal y4 = +0.22f;
+
+ quad(x1, y1, x2, y2, y2, x2, y1, x1);
+ quad(x3, y3, x4, y4, y4, x4, y3, x3);
+
+ extrude(x1, y1, x2, y2);
+ extrude(x2, y2, y2, x2);
+ extrude(y2, x2, y1, x1);
+ extrude(y1, x1, x1, y1);
+ extrude(x3, y3, x4, y4);
+ extrude(x4, y4, y4, x4);
+ extrude(y4, x4, y3, x3);
+
+ const int NumSectors = 100;
+ const qreal sectorAngle = 2 * qreal(M_PI) / NumSectors;
+ for (int i = 0; i < NumSectors; ++i) {
+ qreal angle = i * sectorAngle;
+ qreal x5 = 0.30 * qSin(angle);
+ qreal y5 = 0.30 * qCos(angle);
+ qreal x6 = 0.20 * qSin(angle);
+ qreal y6 = 0.20 * qCos(angle);
+
+ angle += sectorAngle;
+ qreal x7 = 0.20 * qSin(angle);
+ qreal y7 = 0.20 * qCos(angle);
+ qreal x8 = 0.30 * qSin(angle);
+ qreal y8 = 0.30 * qCos(angle);
+
+ quad(x5, y5, x6, y6, x7, y7, x8, y8);
+
+ extrude(x6, y6, x7, y7);
+ extrude(x8, y8, x5, y5);
+ }
+
+ for (int i = 0;i < vertices.size();i++)
+ vertices[i] *= 2.0f;
+}
+
+void Renderer::quad(qreal x1, qreal y1, qreal x2, qreal y2, qreal x3, qreal y3, qreal x4, qreal y4)
+{
+ vertices << QVector3D(x1, y1, -0.05f);
+ vertices << QVector3D(x2, y2, -0.05f);
+ vertices << QVector3D(x4, y4, -0.05f);
+
+ vertices << QVector3D(x3, y3, -0.05f);
+ vertices << QVector3D(x4, y4, -0.05f);
+ vertices << QVector3D(x2, y2, -0.05f);
+
+ QVector3D n = QVector3D::normal
+ (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(x4 - x1, y4 - y1, 0.0f));
+
+ normals << n;
+ normals << n;
+ normals << n;
+
+ normals << n;
+ normals << n;
+ normals << n;
+
+ vertices << QVector3D(x4, y4, 0.05f);
+ vertices << QVector3D(x2, y2, 0.05f);
+ vertices << QVector3D(x1, y1, 0.05f);
+
+ vertices << QVector3D(x2, y2, 0.05f);
+ vertices << QVector3D(x4, y4, 0.05f);
+ vertices << QVector3D(x3, y3, 0.05f);
+
+ n = QVector3D::normal
+ (QVector3D(x2 - x4, y2 - y4, 0.0f), QVector3D(x1 - x4, y1 - y4, 0.0f));
+
+ normals << n;
+ normals << n;
+ normals << n;
+
+ normals << n;
+ normals << n;
+ normals << n;
+}
+
+void Renderer::extrude(qreal x1, qreal y1, qreal x2, qreal y2)
+{
+ vertices << QVector3D(x1, y1, +0.05f);
+ vertices << QVector3D(x2, y2, +0.05f);
+ vertices << QVector3D(x1, y1, -0.05f);
+
+ vertices << QVector3D(x2, y2, -0.05f);
+ vertices << QVector3D(x1, y1, -0.05f);
+ vertices << QVector3D(x2, y2, +0.05f);
+
+ QVector3D n = QVector3D::normal
+ (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(0.0f, 0.0f, -0.1f));
+
+ normals << n;
+ normals << n;
+ normals << n;
+
+ normals << n;
+ normals << n;
+ normals << n;
+}
diff --git a/tests/manual/examples/opengl/hellowindow/hellowindow.h b/tests/manual/examples/opengl/hellowindow/hellowindow.h
new file mode 100644
index 0000000000..1e117ab2e0
--- /dev/null
+++ b/tests/manual/examples/opengl/hellowindow/hellowindow.h
@@ -0,0 +1,77 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#ifndef HELLOWINDOW_H
+#define HELLOWINDOW_H
+
+#include <QWindow>
+
+#include <QColor>
+#include <QMutex>
+#include <QOpenGLShaderProgram>
+#include <QOpenGLBuffer>
+#include <QSharedPointer>
+#include <QTimer>
+
+class HelloWindow;
+
+class Renderer : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit Renderer(const QSurfaceFormat &format, Renderer *share = nullptr,
+ QScreen *screen = nullptr);
+
+ QSurfaceFormat format() const { return m_format; }
+
+public slots:
+ void render(HelloWindow *surface, qreal angle, const QColor &color);
+
+signals:
+ void requestUpdate();
+
+private:
+ void initialize();
+
+ void createGeometry();
+ void createBubbles(int number);
+ void quad(qreal x1, qreal y1, qreal x2, qreal y2, qreal x3, qreal y3, qreal x4, qreal y4);
+ void extrude(qreal x1, qreal y1, qreal x2, qreal y2);
+
+ QList<QVector3D> vertices;
+ QList<QVector3D> normals;
+ int vertexAttr;
+ int normalAttr;
+ int matrixUniform;
+ int colorUniform;
+
+ bool m_initialized;
+ QSurfaceFormat m_format;
+ QOpenGLContext *m_context;
+ QOpenGLShaderProgram *m_program;
+ QOpenGLBuffer m_vbo;
+ QColor m_backgroundColor;
+};
+
+class HelloWindow : public QWindow
+{
+public:
+ explicit HelloWindow(const QSharedPointer<Renderer> &renderer, QScreen *screen = nullptr);
+
+ QColor color() const;
+ void updateColor();
+
+protected:
+ bool event(QEvent *ev) override;
+ void exposeEvent(QExposeEvent *event) override;
+ void mousePressEvent(QMouseEvent *) override;
+ void render();
+
+private:
+ int m_colorIndex;
+ QColor m_color;
+ const QSharedPointer<Renderer> m_renderer;
+};
+
+#endif // HELLOWINDOW_H
diff --git a/tests/manual/examples/opengl/hellowindow/hellowindow.pro b/tests/manual/examples/opengl/hellowindow/hellowindow.pro
new file mode 100644
index 0000000000..27c274a378
--- /dev/null
+++ b/tests/manual/examples/opengl/hellowindow/hellowindow.pro
@@ -0,0 +1,9 @@
+QT += gui-private core-private opengl
+
+HEADERS += hellowindow.h
+SOURCES += hellowindow.cpp main.cpp
+
+# install
+target.path = $$[QT_INSTALL_EXAMPLES]/opengl/hellowindow
+INSTALLS += target
+
diff --git a/tests/manual/examples/opengl/hellowindow/main.cpp b/tests/manual/examples/opengl/hellowindow/main.cpp
new file mode 100644
index 0000000000..ee4729a493
--- /dev/null
+++ b/tests/manual/examples/opengl/hellowindow/main.cpp
@@ -0,0 +1,125 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include "hellowindow.h"
+
+#include <qpa/qplatformintegration.h>
+
+#include <QCommandLineParser>
+#include <QCommandLineOption>
+#include <QGuiApplication>
+#include <QScreen>
+#include <QThread>
+
+int main(int argc, char *argv[])
+{
+ QGuiApplication app(argc, argv);
+
+ QCoreApplication::setApplicationName("Qt HelloWindow GL Example");
+ QCoreApplication::setOrganizationName("QtProject");
+ QCoreApplication::setApplicationVersion(QT_VERSION_STR);
+ QCommandLineParser parser;
+ parser.setApplicationDescription(QCoreApplication::applicationName());
+ parser.addHelpOption();
+ parser.addVersionOption();
+ QCommandLineOption multipleOption("multiple", "Create multiple windows");
+ parser.addOption(multipleOption);
+ QCommandLineOption multipleSampleOption("multisample", "Multisampling");
+ parser.addOption(multipleSampleOption);
+ QCommandLineOption multipleScreenOption("multiscreen", "Run on multiple screens");
+ parser.addOption(multipleScreenOption);
+ QCommandLineOption timeoutOption("timeout", "Close after 10s");
+ parser.addOption(timeoutOption);
+ parser.process(app);
+
+ // Some platforms can only have one window per screen. Therefore we need to differentiate.
+ const bool multipleWindows = parser.isSet(multipleOption);
+ const bool multipleScreens = parser.isSet(multipleScreenOption);
+
+ QScreen *screen = QGuiApplication::primaryScreen();
+
+ QRect screenGeometry = screen->availableGeometry();
+
+ QSurfaceFormat format;
+ format.setDepthBufferSize(16);
+ if (parser.isSet(multipleSampleOption))
+ format.setSamples(4);
+
+ QPoint center = QPoint(screenGeometry.center().x(), screenGeometry.top() + 80);
+ QSize windowSize(400, 320);
+ int delta = 40;
+
+ QList<QWindow *> windows;
+ QSharedPointer<Renderer> rendererA(new Renderer(format));
+
+ HelloWindow *windowA = new HelloWindow(rendererA);
+ windowA->setGeometry(QRect(center, windowSize).translated(-windowSize.width() - delta / 2, 0));
+ windowA->setTitle(QStringLiteral("Thread A - Context A"));
+ windowA->setVisible(true);
+ windows.prepend(windowA);
+
+ QList<QThread *> renderThreads;
+ if (multipleWindows) {
+ QSharedPointer<Renderer> rendererB(new Renderer(format, rendererA.data()));
+
+ QThread *renderThread = new QThread;
+ rendererB->moveToThread(renderThread);
+ renderThreads << renderThread;
+
+ HelloWindow *windowB = new HelloWindow(rendererA);
+ windowB->setGeometry(QRect(center, windowSize).translated(delta / 2, 0));
+ windowB->setTitle(QStringLiteral("Thread A - Context A"));
+ windowB->setVisible(true);
+ windows.prepend(windowB);
+
+ HelloWindow *windowC = new HelloWindow(rendererB);
+ windowC->setGeometry(QRect(center, windowSize).translated(-windowSize.width() / 2, windowSize.height() + delta));
+ windowC->setTitle(QStringLiteral("Thread B - Context B"));
+ windowC->setVisible(true);
+ windows.prepend(windowC);
+ }
+ if (multipleScreens) {
+ for (int i = 1; i < QGuiApplication::screens().size(); ++i) {
+ QScreen *screen = QGuiApplication::screens().at(i);
+ QSharedPointer<Renderer> renderer(new Renderer(format, rendererA.data(), screen));
+
+ QThread *renderThread = new QThread;
+ renderer->moveToThread(renderThread);
+ renderThreads.prepend(renderThread);
+
+ QRect screenGeometry = screen->availableGeometry();
+ QPoint center = screenGeometry.center();
+
+ QSize windowSize = screenGeometry.size() * 0.8;
+
+ HelloWindow *window = new HelloWindow(renderer, screen);
+ window->setGeometry(QRect(center, windowSize).translated(-windowSize.width() / 2, -windowSize.height() / 2));
+
+ QChar id = QChar('B' + i);
+ window->setTitle(QStringLiteral("Thread ") + id + QStringLiteral(" - Context ") + id);
+ window->setVisible(true);
+ windows.prepend(window);
+ }
+ }
+
+ for (int i = 0; i < renderThreads.size(); ++i) {
+ QObject::connect(qGuiApp, &QGuiApplication::lastWindowClosed, renderThreads.at(i), &QThread::quit);
+ renderThreads.at(i)->start();
+ }
+
+ // Quit after 10 seconds. For platforms that do not have windows that are closeable.
+ if (parser.isSet(timeoutOption))
+ QTimer::singleShot(10000, qGuiApp, &QCoreApplication::quit);
+
+ const int exitValue = app.exec();
+
+ for (int i = 0; i < renderThreads.size(); ++i) {
+ renderThreads.at(i)->quit(); // some platforms may not have windows to close so ensure quit()
+ renderThreads.at(i)->wait();
+ }
+
+ qDeleteAll(windows);
+ qDeleteAll(renderThreads);
+
+ return exitValue;
+}
diff --git a/tests/manual/examples/opengl/qopenglwindow/CMakeLists.txt b/tests/manual/examples/opengl/qopenglwindow/CMakeLists.txt
new file mode 100644
index 0000000000..f1c407ce17
--- /dev/null
+++ b/tests/manual/examples/opengl/qopenglwindow/CMakeLists.txt
@@ -0,0 +1,49 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+cmake_minimum_required(VERSION 3.16)
+project(qopenglwindow LANGUAGES CXX)
+
+if(NOT DEFINED INSTALL_EXAMPLESDIR)
+ set(INSTALL_EXAMPLESDIR "examples")
+endif()
+
+set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/opengl/qopenglwindow")
+
+find_package(Qt6 REQUIRED COMPONENTS Core Gui OpenGL)
+
+qt_standard_project_setup()
+
+qt_add_executable(qopenglwindow
+ background_renderer.cpp background_renderer.h
+ main.cpp
+)
+
+set_target_properties(qopenglwindow PROPERTIES
+ WIN32_EXECUTABLE TRUE
+ MACOSX_BUNDLE TRUE
+)
+
+target_link_libraries(qopenglwindow PRIVATE
+ Qt6::Core
+ Qt6::Gui
+ Qt6::OpenGL
+)
+
+# Resources:
+set(shaders_resource_files
+ "background.frag"
+)
+
+qt_add_resources(qopenglwindow "shaders"
+ PREFIX
+ "/"
+ FILES
+ ${shaders_resource_files}
+)
+
+install(TARGETS qopenglwindow
+ RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
+ BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
+ LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
+)
diff --git a/tests/manual/examples/opengl/qopenglwindow/background.frag b/tests/manual/examples/opengl/qopenglwindow/background.frag
new file mode 100644
index 0000000000..4af85aae8e
--- /dev/null
+++ b/tests/manual/examples/opengl/qopenglwindow/background.frag
@@ -0,0 +1,30 @@
+#define M_PI 3.14159265358979323846
+#define SPEED 10000.0
+
+uniform int currentTime;
+uniform highp vec2 windowSize;
+
+highp float noise(highp vec2 co)
+{
+ return 0.5 * fract(sin(dot(co.xy, vec2(12.9898,78.233))) * 43758.5453);
+}
+
+highp float curvSpeed()
+{
+ return (mod(float(currentTime), SPEED) / SPEED) * (2.0 * M_PI);
+}
+
+highp float curv(int curvCount)
+{
+ highp float curv_y = 0.1 *(cos((gl_FragCoord.x / windowSize.x) * (float(curvCount * 2) * M_PI) - curvSpeed())) + 0.5;
+ highp float frag_y = gl_FragCoord.y / windowSize.y;
+ return 1.0 - abs(curv_y - frag_y);
+}
+
+void main()
+{
+ highp float coordNoise = noise(gl_FragCoord.xy);
+ highp float proximity = smoothstep(0.85, 1.0, (curv(6) + 1.0) * (coordNoise ));
+ highp vec3 color = vec3(coordNoise) * proximity;
+ gl_FragColor = vec4(color, 1.0);
+}
diff --git a/tests/manual/examples/opengl/qopenglwindow/background_renderer.cpp b/tests/manual/examples/opengl/qopenglwindow/background_renderer.cpp
new file mode 100644
index 0000000000..5939894dfe
--- /dev/null
+++ b/tests/manual/examples/opengl/qopenglwindow/background_renderer.cpp
@@ -0,0 +1,167 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include "background_renderer.h"
+
+#include <qmath.h>
+#include <QFileInfo>
+#include <QTime>
+
+#include <QOpenGLShaderProgram>
+#include <QOpenGLContext>
+#include <QOpenGLFunctions>
+
+#include <math.h>
+
+static const char vertex_shader[] =
+ "attribute highp vec3 vertexCoord;"
+ "void main() {"
+ " gl_Position = vec4(vertexCoord,1.0);"
+ "}";
+
+static const char fragment_shader[] =
+ "void main() {"
+ " gl_FragColor = vec4(0.0,1.0,0.0,1.0);"
+ "}";
+
+static const float vertices[] = { -1, -1, 0,
+ -1, 1, 0,
+ 1, -1, 0,
+ 1, 1, 0 };
+
+FragmentToy::FragmentToy(const QString &fragmentSource, QObject *parent)
+ : QObject(parent)
+ , m_recompile_shaders(true)
+{
+ if (QFile::exists(fragmentSource)) {
+ QFileInfo info(fragmentSource);
+ m_fragment_file_last_modified = info.lastModified();
+ m_fragment_file = fragmentSource;
+#if QT_CONFIG(filesystemwatcher)
+ m_watcher.addPath(info.canonicalPath());
+ QObject::connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &FragmentToy::fileChanged);
+#endif
+ }
+}
+
+FragmentToy::~FragmentToy()
+ = default;
+
+void FragmentToy::draw(const QSize &windowSize)
+{
+ if (!m_program)
+ initializeOpenGLFunctions();
+
+ glDisable(GL_STENCIL_TEST);
+ glDisable(GL_DEPTH_TEST);
+
+ glClearColor(0, 0, 0, 1);
+ glClear(GL_COLOR_BUFFER_BIT);
+ if (!m_vao.isCreated())
+ m_vao.create();
+
+ QOpenGLVertexArrayObject::Binder binder(&m_vao);
+
+ if (!m_vertex_buffer.isCreated()) {
+ m_vertex_buffer.create();
+ m_vertex_buffer.bind();
+ m_vertex_buffer.allocate(vertices, sizeof(vertices));
+ m_vertex_buffer.release();
+ }
+
+ if (!m_program) {
+ m_program.reset(new QOpenGLShaderProgram);
+ m_program->create();
+ m_vertex_shader.reset(new QOpenGLShader(QOpenGLShader::Vertex));
+ if (!m_vertex_shader->compileSourceCode(vertex_shader)) {
+ qWarning() << "Failed to compile the vertex shader:" << m_vertex_shader->log();
+ }
+ if (!m_program->addShader(m_vertex_shader.get())) {
+ qWarning() << "Failed to add vertex shader to program:" << m_program->log();
+ }
+ }
+
+ if (!m_fragment_shader && m_recompile_shaders) {
+ QByteArray data;
+ if (m_fragment_file.size()) {
+ QFile file(m_fragment_file);
+ if (file.open(QIODevice::ReadOnly)) {
+ data = file.readAll();
+ } else {
+ qWarning() << "Failed to load input file, falling back to default";
+ data = QByteArray::fromRawData(fragment_shader, sizeof(fragment_shader));
+ }
+ } else {
+ QFile qrcFile(":/background.frag");
+ if (qrcFile.open(QIODevice::ReadOnly))
+ data = qrcFile.readAll();
+ else
+ data = QByteArray::fromRawData(fragment_shader, sizeof(fragment_shader));
+ }
+ if (data.size()) {
+ m_fragment_shader.reset(new QOpenGLShader(QOpenGLShader::Fragment));
+ if (!m_fragment_shader->compileSourceCode(data)) {
+ qWarning() << "Failed to compile fragment shader:" << m_fragment_shader->log();
+ m_fragment_shader.reset(nullptr);
+ }
+ } else {
+ qWarning() << "Unknown error, no fragment shader";
+ }
+
+ if (m_fragment_shader) {
+ if (!m_program->addShader(m_fragment_shader.get())) {
+ qWarning() << "Failed to add fragment shader to program:" << m_program->log();
+ }
+ }
+ }
+
+ if (m_recompile_shaders) {
+ m_recompile_shaders = false;
+
+ if (m_program->link()) {
+ m_vertex_coord_pos = m_program->attributeLocation("vertexCoord");
+ } else {
+ qWarning() << "Failed to link shader program" << m_program->log();
+ }
+
+ }
+
+ if (!m_program->isLinked())
+ return;
+
+ m_program->bind();
+
+ m_vertex_buffer.bind();
+ m_program->setAttributeBuffer("vertexCoord", GL_FLOAT, 0, 3, 0);
+ m_program->enableAttributeArray("vertexCoord");
+ m_vertex_buffer.release();
+
+ m_program->setUniformValue("currentTime", (uint) QDateTime::currentMSecsSinceEpoch());
+ m_program->setUniformValue("windowSize", windowSize);
+
+ QOpenGLContext::currentContext()->functions()->glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
+
+ m_program->release();
+}
+
+void FragmentToy::fileChanged(const QString &path)
+{
+ Q_UNUSED(path);
+ if (QFile::exists(m_fragment_file)) {
+ QFileInfo fragment_source(m_fragment_file);
+ if (fragment_source.lastModified() > m_fragment_file_last_modified) {
+ m_fragment_file_last_modified = fragment_source.lastModified();
+ m_recompile_shaders = true;
+ if (m_program) {
+ m_program->removeShader(m_fragment_shader.get());
+ m_fragment_shader.reset(nullptr);
+ }
+ }
+ } else {
+ m_recompile_shaders = true;
+ if (m_program) {
+ m_program->removeShader(m_fragment_shader.get());
+ m_fragment_shader.reset(nullptr);
+ }
+ }
+}
diff --git a/tests/manual/examples/opengl/qopenglwindow/background_renderer.h b/tests/manual/examples/opengl/qopenglwindow/background_renderer.h
new file mode 100644
index 0000000000..76c0bec6a8
--- /dev/null
+++ b/tests/manual/examples/opengl/qopenglwindow/background_renderer.h
@@ -0,0 +1,46 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#ifndef FRAGMENT_TOY_H
+#define FRAGMENT_TOY_H
+
+#include <QObject>
+#include <QFile>
+#include <QDateTime>
+#if QT_CONFIG(filesystemwatcher)
+#include <QFileSystemWatcher>
+#endif
+#include <QOpenGLVertexArrayObject>
+#include <QOpenGLBuffer>
+#include <QOpenGLShaderProgram>
+#include <QOpenGLFunctions>
+
+#include <memory>
+
+class FragmentToy : public QObject, protected QOpenGLFunctions
+{
+ Q_OBJECT
+public:
+ explicit FragmentToy(const QString &fragmentSource, QObject *parent = nullptr);
+ ~FragmentToy();
+
+ void draw(const QSize &windowSize);
+
+private:
+ void fileChanged(const QString &path);
+ bool m_recompile_shaders;
+#if QT_CONFIG(filesystemwatcher)
+ QFileSystemWatcher m_watcher;
+#endif
+ QString m_fragment_file;
+ QDateTime m_fragment_file_last_modified;
+
+ std::unique_ptr<QOpenGLShaderProgram> m_program;
+ std::unique_ptr<QOpenGLShader> m_vertex_shader;
+ std::unique_ptr<QOpenGLShader> m_fragment_shader;
+ QOpenGLVertexArrayObject m_vao;
+ QOpenGLBuffer m_vertex_buffer;
+ GLuint m_vertex_coord_pos;
+};
+
+#endif //FRAGMENT_TOY_H
diff --git a/tests/manual/examples/opengl/qopenglwindow/main.cpp b/tests/manual/examples/opengl/qopenglwindow/main.cpp
new file mode 100644
index 0000000000..44810a4ecf
--- /dev/null
+++ b/tests/manual/examples/opengl/qopenglwindow/main.cpp
@@ -0,0 +1,154 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QOpenGLWindow>
+#include <QScreen>
+#include <QPainter>
+#include <QPainterPath>
+#include <QGuiApplication>
+#include <QMatrix4x4>
+#include <QStaticText>
+#include <QKeyEvent>
+
+#include "background_renderer.h"
+
+static QPainterPath painterPathForTriangle()
+{
+ static const QPointF bottomLeft(-1.0, -1.0);
+ static const QPointF top(0.0, 1.0);
+ static const QPointF bottomRight(1.0, -1.0);
+
+ QPainterPath path(bottomLeft);
+ path.lineTo(top);
+ path.lineTo(bottomRight);
+ path.closeSubpath();
+ return path;
+}
+
+class OpenGLWindow : public QOpenGLWindow
+{
+ Q_OBJECT
+
+public:
+ OpenGLWindow();
+
+protected:
+ void paintGL() override;
+ void resizeGL(int w, int h) override;
+ void keyPressEvent(QKeyEvent *e) override;
+
+private:
+ void setAnimating(bool enabled);
+
+ QMatrix4x4 m_window_normalised_matrix;
+ QMatrix4x4 m_window_painter_matrix;
+ QMatrix4x4 m_projection;
+ QMatrix4x4 m_view;
+ QMatrix4x4 m_model_triangle;
+ QMatrix4x4 m_model_text;
+
+ FragmentToy m_fragment_toy;
+ QStaticText m_text_layout;
+ bool m_animate;
+};
+
+// Use NoPartialUpdate. This means that all the rendering goes directly to
+// the window surface, no additional framebuffer object stands in the
+// middle. This is fine since we will clear the entire framebuffer on each
+// paint. Under the hood this means that the behavior is equivalent to the
+// manual makeCurrent - perform OpenGL calls - swapBuffers loop that is
+// typical in pure QWindow-based applications.
+OpenGLWindow::OpenGLWindow()
+ : QOpenGLWindow(QOpenGLWindow::NoPartialUpdate)
+ , m_fragment_toy("./background.frag")
+ , m_text_layout("The triangle and this text is rendered with QPainter")
+ , m_animate(true)
+{
+ setGeometry(300, 300, 500, 500);
+
+ m_view.lookAt(QVector3D(3,1,1),
+ QVector3D(0,0,0),
+ QVector3D(0,1,0));
+
+ setAnimating(m_animate);
+}
+
+void OpenGLWindow::paintGL()
+{
+ m_fragment_toy.draw(size());
+
+ QPainter p(this);
+ p.setWorldTransform(m_window_normalised_matrix.toTransform());
+
+ QMatrix4x4 mvp = m_projection * m_view * m_model_triangle;
+ p.setTransform(mvp.toTransform(), true);
+
+ p.fillPath(painterPathForTriangle(), QBrush(QGradient(QGradient::NightFade)));
+
+ QTransform text_transform = (m_window_painter_matrix * m_view * m_model_text).toTransform();
+ p.setTransform(text_transform, false);
+ p.setPen(QPen(Qt::black));
+ m_text_layout.prepare(text_transform);
+ qreal x = - (m_text_layout.size().width() / 2);
+ qreal y = 0;
+ p.drawStaticText(x, y, m_text_layout);
+
+ m_model_triangle.rotate(-1, 0, 1, 0);
+ m_model_text.rotate(1, 0, 1, 0);
+}
+
+void OpenGLWindow::resizeGL(int w, int h)
+{
+ m_window_normalised_matrix.setToIdentity();
+ m_window_normalised_matrix.translate(w / 2.0, h / 2.0);
+ m_window_normalised_matrix.scale(w / 2.0, -h / 2.0);
+
+ m_window_painter_matrix.setToIdentity();
+ m_window_painter_matrix.translate(w / 2.0, h / 2.0);
+
+ m_text_layout.setTextWidth(std::max(w * 0.2, 80.0));
+
+ m_projection.setToIdentity();
+ m_projection.perspective(45.f, qreal(w) / qreal(h), 0.1f, 100.f);
+}
+
+void OpenGLWindow::keyPressEvent(QKeyEvent *e)
+{
+ if (e->key() == Qt::Key_P) { // pause
+ m_animate = !m_animate;
+ setAnimating(m_animate);
+ }
+}
+
+void OpenGLWindow::setAnimating(bool enabled)
+{
+ if (enabled) {
+ // Animate continuously, throttled by the blocking swapBuffers() call the
+ // QOpenGLWindow internally executes after each paint. Once that is done
+ // (frameSwapped signal is emitted), we schedule a new update. This
+ // obviously assumes that the swap interval (see
+ // QSurfaceFormat::setSwapInterval()) is non-zero.
+ connect(this, &QOpenGLWindow::frameSwapped,
+ this, QOverload<>::of(&QPaintDeviceWindow::update));
+ update();
+ } else {
+ disconnect(this, &QOpenGLWindow::frameSwapped,
+ this, QOverload<>::of(&QPaintDeviceWindow::update));
+ }
+}
+
+int main(int argc, char **argv)
+{
+ QGuiApplication app(argc, argv);
+
+ OpenGLWindow window;
+ QSurfaceFormat fmt;
+ fmt.setDepthBufferSize(24);
+ fmt.setStencilBufferSize(8);
+ window.setFormat(fmt);
+ window.show();
+
+ return app.exec();
+}
+
+#include "main.moc"
diff --git a/tests/manual/examples/opengl/qopenglwindow/qopenglwindow.pro b/tests/manual/examples/opengl/qopenglwindow/qopenglwindow.pro
new file mode 100644
index 0000000000..e7073a324b
--- /dev/null
+++ b/tests/manual/examples/opengl/qopenglwindow/qopenglwindow.pro
@@ -0,0 +1,16 @@
+TEMPLATE = app
+TARGET = qopenglwindow
+INCLUDEPATH += .
+QT += opengl
+
+RESOURCES += shaders.qrc
+
+SOURCES += \
+ main.cpp \
+ background_renderer.cpp
+
+HEADERS += \
+ background_renderer.h
+
+target.path = $$[QT_INSTALL_EXAMPLES]/opengl/qopenglwindow
+INSTALLS += target
diff --git a/tests/manual/examples/opengl/qopenglwindow/shaders.qrc b/tests/manual/examples/opengl/qopenglwindow/shaders.qrc
new file mode 100644
index 0000000000..64eefe2c70
--- /dev/null
+++ b/tests/manual/examples/opengl/qopenglwindow/shaders.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>background.frag</file>
+</qresource>
+</RCC>